From 568f0f21685b7900cf6d1653ab9cbedac0bea08c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 20:44:36 -0800 Subject: [PATCH 001/126] Links: Relink, Embed and Unembed keep a distorted image's corners An image changed by Perspective Distort or Free Distort was refused by Relink, Embed and Unembed. Each now keeps the image's corners in one undo step: - Relink puts the new file's pixels between the corners, as Update Links does, whatever `preserve` or the image's Placement Options say. - Embed keeps the file's pixels in the document between the corners, reading the file first when the image shows its saved preview. - Unembed writes the pixels to the file and links the image to it with the same corners. Unembed into a folder keeps the corners too. Relink and Update Links also follow the clipping path a PSD, PSB or DCS file names for a distorted image: the path is drawn through the corners, a clip group of the old file's path takes the new file's, and it becomes a plain group when the new file names none. Unembed of an image from a PSD or PSB file took away the clip group of the file's clipping path, plain images included: the PNG or TIFF it writes keeps the path, but the file was read without it. A PNG or TIFF that keeps the path now comes with it when it is read, so Unembed, and a later Place, Relink or Update Links of the written file, keep the clip group. The params text of Relink, Embed and Unembed, docs/mcp.md and the progress-doc line describe the new behavior. --- crates/engine/src/cmd/fileio/load.rs | 9 +- crates/engine/src/cmd/fileio/tests_psdread.rs | 95 ++++++++++ crates/engine/src/cmd/links.rs | 121 +++++++++---- crates/engine/src/tests/links.rs | 170 ++++++++++++++++++ crates/engine/src/tests/xform.rs | 3 - docs/mcp.md | 18 +- docs/target-app-parity.md | 2 +- 7 files changed, 369 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 4e59e378a5..9de13076ae 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -962,7 +962,8 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; /// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported -/// clipping path ([`image_clip`]). +/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes +/// it) comes with it. pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -1139,13 +1140,15 @@ pub fn texture_image(bytes: &[u8]) -> Result { texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) } -/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed. +/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a +/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]). fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result { if width == 0 || height == 0 { return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) + let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 249a3f320c..ad17346d19 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,101 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective +/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners, +/// a clip group of the old file's clipping path loses it when the new file names none, and a later +/// file's clipping path clips it again. +#[test] +fn relink_follows_the_clipping_path_of_a_distorted_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-relink-distorted"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let square = write_file(&dir, "square.psd", &red_psd(&square_resources())); + let plain = write_file(&dir, "plain.psd", &red_psd(&[])); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone(); + assert!(node(&s).is_distorted_image()); + let corners = node(&s).image_corners().unwrap(); + // A path's anchors (in the image's pixels) where the image's corners put them. + let mapped = |s: &Session, pixels: &[[f64; 2]]| -> Vec<[f64; 2]> { + let map = node(s).image_map().unwrap(); + pixels.iter().map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()).map(|p| [p.x, p.y]).collect() + }; + let near = + |a: &[[f64; 2]], b: &[[f64; 2]]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let triangle = mapped(&s, &[[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]]); + assert!(near(&anchors, &triangle) && even_odd && held == image, "{anchors:?} vs {triangle:?}"); + s.execute("links.relink", &json!({"ids": [image.0], "path": square})).unwrap(); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let squared = mapped(&s, &[[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]]); + assert!(near(&anchors, &squared) && even_odd && held == image, "the new file's clipping path: {anchors:?} vs {squared:?}"); + assert_eq!(node(&s).image_corners().unwrap(), corners); + s.execute("links.relink", &json!({"ids": [image.0], "path": plain})).unwrap(); + match s.doc().unwrap().doc.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + s.execute("links.relink", &json!({"ids": [image.0], "path": cut})).unwrap(); + let (anchors, _, held) = clip_group(&s.doc().unwrap().doc, group); + assert!(near(&anchors, &triangle) && held == image, "clipped again: {anchors:?} vs {triangle:?}"); + assert!(node(&s).is_distorted_image()); + assert_eq!(node(&s).image_corners().unwrap(), corners); +} + +/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, for a +/// plain image and for one changed by Perspective Distort or Free Distort, and so do reading the +/// written file again and placing it. +#[test] +fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); + // An RGB file is kept as a PNG, a CMYK one as a TIFF. + let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); + let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; + for ((kind, file), distort) in files.iter().flat_map(|f| [(f, false), (f, true)]) { + let data = vectorcraft_format::base64_encode(file); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if distort { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + } + let before = clip_group(&s.doc().unwrap().doc, group); + // Without an extension the image is written in the format it is stored in. + let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}-{distort}"))})).unwrap(); + let path = r["path"].as_str().unwrap().to_string(); + let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; + assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); + for step in ["unembed", "relink"] { + if step == "relink" { + s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "linked to the file written"); + assert_eq!(d.node(image).unwrap().is_distorted_image(), distort); + // A distorted image's clipping path is drawn through its corners again, within rounding. + let (anchors, even_odd, held) = clip_group(d, group); + let near = anchors.len() == before.0.len() + && anchors.iter().zip(&before.0).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, distorted: {distort}: {anchors:?} vs {:?}", before.0); + } + // Placing the written file gives the same clip group as placing the PSD file did. + if !distort { + let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap(); + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); + assert!(even_odd && anchors.len() == before.0.len(), "{kind}, place: {anchors:?} vs {:?}", before.0); + } + } +} + /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a /// text chunk within the size limit that reads as a path gives one back. #[test] diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 8fcd589c52..233994d655 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -33,7 +33,7 @@ use vectorcraft_doc::{ Appearance, DataValue, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, PlacedDocument, PlacementOptions, StoredPlace, StoredRoot, }; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; +use vectorcraft_geom::{Affine, FillRule, Homography, PathData, Rect, shapes}; use super::fileio::{self, RasterImage, absolute_path, file_created, file_stamp, read_file, write_file}; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_doc, ids_param, object_param, str_param, switch_or, text_param}; @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say; the clipping path its file names is drawn through the corners. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", has_doc, relink ), @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Embed Image", [], None, - "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). One undo step → {embedded: [ids], missing: [ids]}", + "{ids?: [image or placed document ids] (default: the selected linked ones)} break the links (the Links panel's Break Link): images keep the linked files' pixels in the document; a placed document becomes an editable copy of its art, as placing its file without link gives (its symbols, patterns, swatches and images joining the document). An image whose file can't be found and that shows the saved preview, or a placed document whose file can't be read or changed, stays linked: relink or update it first. An image placed from a DCS file can't be embedded (an error, and nothing changes). An image changed by Perspective Distort or Free Distort keeps its corners. One undo step → {embedded: [ids], missing: [ids]}", has_doc, embed ), @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners); written as stored, an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path for later reads. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). +/// can't be read ([`readable`]). A PNG or TIFF written from a PSD or PSB file's image (by Unembed) +/// comes with the clipping path it keeps ([`fileio::raster_image`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; @@ -791,13 +792,20 @@ fn clip_to( new_xf: Affine, held: Option<(&PathData, FillRule)>, ) -> ClipTo { + let old = old_clip.filter(|_| held.is_some()).map(|(path, rule)| (path.transformed(old_xf), *rule)); + let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); + placed_clip_to(old.as_ref(), clip, file, held) +} + +/// [`clip_to`] with the clipping paths of the old file (`old`) and of the new file (`file`) already +/// on the page. +fn placed_clip_to(old: Option<&FileClip>, clip: Option, file: Option, held: Option<(&PathData, FillRule)>) -> ClipTo { // Whether the clip group holding just the image is the old file's: a clipping path whose fill // rule was changed in the document is not. - let file_held = match (old_clip, held) { - (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(&old.transformed(old_xf), held), + let file_held = match (old, held) { + (Some((old, old_rule)), Some((held, rule))) => rule == *old_rule && same_path(old, held), _ => false, }; - let file = img.clip.as_ref().map(|(path, rule)| (path.transformed(new_xf), *rule)); if let Some(clip) = clip { let placement = clip_shape(clip); return match file { @@ -1210,14 +1218,43 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } -/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its -/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader -/// that places it by the transform still gives it its old size. -fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) { - if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { - im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); +/// Distorted image `n` shows the file read for `link` (`img`) and keeps its corners: the new pixels +/// fill them. Its transform is scaled to the new pixel size, so a reader that places it by the +/// transform still gives it its old size. Its Placement Options do not apply. The result is what +/// happens to its clip, as [`clip_to`] decides from the clipping path of the clip group holding +/// just it (`held`): the clipping paths of its old file (`old_clip`, in its old pixels) and of the +/// new file are mapped to the page through its corners, anchors and handles alike, as a distort +/// maps a path's. +fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { + let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); + if let NodeKind::Image(im) = &mut n.kind { + if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { + im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); + } + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); } - (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); + let file = img.clip.as_ref().and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); + placed_clip_to(old.as_ref(), None, file, held) +} + +/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points +/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front +/// of it, and one past it to the far side. `None` when a point maps to no finite page point. +fn warped(path: &PathData, map: &Homography) -> Option { + let [[a, b, c], [d, e, f], [g, h, i]] = map.0; + let apply = |p: vectorcraft_geom::Point| { + let w = g * p.x + h * p.y + i; + let w = if w.abs() < 1e-9 { 1e-9_f64.copysign(w) } else { w }; + let q = vectorcraft_geom::Point::new((a * p.x + b * p.y + c) / w, (d * p.x + e * p.y + f) / w); + q.is_finite().then_some(q) + }; + let mut out = path.clone(); + for sp in &mut out.subpaths { + for anchor in &mut sp.anchors { + (anchor.p, anchor.h_in, anchor.h_out) = (apply(anchor.p)?, apply(anchor.h_in)?, apply(anchor.h_out)?); + } + } + Some(out) } /// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each @@ -1244,12 +1281,15 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { let mut n = n.clone(); let mut clip = ClipTo::Keep; - let distorted = n.is_distorted_image(); + if n.is_distorted_image() { + let old_clip = match &n.kind { + NodeKind::Image(im) => old.get(&im.key).and_then(|(_, clip)| clip.clone()), + _ => None, + }; + let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); + return (n, clip); + } if let NodeKind::Image(im) = &mut n.kind { - if distorted { - refill_distorted(im, &link, &img); - return (n, clip); - } let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (old_pt, old_clip) = match old.get(&im.key) { @@ -1266,10 +1306,13 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio } for id in ids { if d.node(*id).is_some_and(Node::is_distorted_image) { - if let Some(n) = d.node_mut(*id) - && let NodeKind::Image(im) = &mut n.kind - { - refill_distorted(im, &link, &img); + let old_clip = match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::Image(im)) => d.images.get(&im.key).and_then(file_clip), + _ => None, + }; + let held = clip_path_of(d, *id).map(|(path, rule)| (path.clone(), rule)); + if let Some(n) = d.node_mut(*id) { + clips.push((*id, refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))))); } continue; } @@ -2153,11 +2196,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { } (None, None, None) => return Err(bad(C, "give path (a file) or folder")), } - // A new file's placement options place a plain image: a distorted one is left as it is. - let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)); - if let Some(id) = distorted { - return Err(super::xform::distorted_image_error(C, *id)); - } // Every file is read and checked before any is copied. let mut checked = vec![]; for (ids, path) in files { @@ -2620,9 +2658,6 @@ fn embed(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the linked images or placed documents, or pass ids")); } - if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) { - return Err(super::xform::distorted_image_error(C, *id)); - } // A DCS file's plates print from its file. let separated = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated), @@ -2751,9 +2786,6 @@ fn unembed(s: &mut Session, p: &Value) -> Result { if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); } - if n.is_distorted_image() { - return Err(super::xform::distorted_image_error(C, id)); - } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. let stored = stored_extension(blob); @@ -3124,4 +3156,23 @@ mod tests { let long = unembed_stem(&"é".repeat(200)); assert!(long.len() <= 150 && long.chars().all(|c| c == 'é'), "{}", long.len()); } + + /// A clipping path mapped through a distorted image's corners keeps the points that lie on or + /// past the map's horizon, each mapped as a distort maps a path's point. + #[test] + fn points_past_the_horizon_are_mapped_as_a_distort_maps_them() { + use vectorcraft_geom::{Anchor, Point, SubPath}; + // w = 1 + x / 100: the horizon is the line x = -100. + let map = Homography([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.01, 0.0, 1.0]]); + let (at, handle, on) = (Point::new(0.0, 0.0), Point::new(-200.0, 0.0), Point::new(-100.0, 5.0)); + assert!(map.apply(handle).is_none() && map.apply(on).is_none()); + let path = PathData::new(vec![SubPath::new(vec![Anchor::smooth(at, handle), Anchor::corner(on)], false)]); + let out = warped(&path, &map).expect("a path"); + let (first, second) = (out.subpaths[0].anchors[0], out.subpaths[0].anchors[1]); + assert_eq!((first.p, first.h_in), (at, Point::new(200.0 / 3.0, 0.0))); + // w = -1: the handle maps to the far side. + assert_eq!(first.h_out, Point::new(200.0, 0.0)); + // w = 0 is taken as a billionth. + assert!(second.p.is_finite() && (second.p.x.abs() - 1e11).abs() < 1.0 && (second.p.y.abs() - 5e9).abs() < 1.0, "{:?}", second.p); + } } diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6386716232..efaf396a4e 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -655,6 +655,176 @@ fn update_links_keeps_a_distorted_images_corners() { scale_matches_ppi(&mut s); } +/// Relink with scope `all` puts the new file's pixels between the corners of the distorted images +/// in symbols too, and scales each one's transform to the new pixel size, so a placement by the +/// transform keeps the old size. +#[test] +fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() { + let dir = Folder::new("distorted-relink-all"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let before = s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + // The far corner of the pixels as the transform alone places them. + let far = |s: &Session| { + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") }; + im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height)) + }; + let far_before = far(&s); + // A distorted copy in a symbol shows the same file. + let copy = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [copy.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap(); + let in_symbol = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if let NodeKind::Image(im) = &n.kind { + out.push((n.image_quad(), (im.width, im.height))); + } + }); + out + }; + let [(Some(symbol_quad), (20, 10))] = in_symbol(&s)[..] else { panic!("one distorted image in the symbol: {:?}", in_symbol(&s)) }; + let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap(); + let relinked = r["relinked"].as_array().unwrap(); + assert!(relinked.len() == 2 && relinked.contains(&json!(id.0)), "the image and the symbol's: {r}"); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert_eq!((n.is_distorted_image(), n.image_corners().unwrap()), (true, before)); + assert_eq!((image(&s, id).width, image(&s, id).height), (60, 20)); + assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s)); + assert_eq!(in_symbol(&s), [(Some(symbol_quad), (60, 20))], "the symbol's image keeps its corners"); +} + +/// Relink, Embed and Unembed keep a distorted image's corners, each in one undo step: Relink puts +/// the new file's pixels between them whatever `preserve` and the Placement Options say, Embed +/// keeps the pixels in the document, and Unembed links the image to the file it writes. +#[test] +fn relink_embed_and_unembed_keep_a_distorted_images_corners() { + let dir = Folder::new("distorted-relink"); + let (photo, other, written) = (dir.file("photo.png"), dir.file("other.png"), dir.file("written.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // Around the artboard's center, where `centre_colour` looks. + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + let distorted = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().is_distorted_image(); + let clipped = |s: &Session| { + let d = &s.doc().unwrap().doc; + matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })) + }; + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); + + let undo = undo_len(&s); + let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "preserve": "fileDimensions"})).unwrap(); + assert_eq!(r["relinked"], json!([id.0]), "{r}"); + assert_eq!(undo_len(&s), undo + 1); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + assert!(!clipped(&s), "not clipped by its Placement Options"); + let im = image(&s, id); + assert_eq!((im.width, im.height), (60, 20)); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str())); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(r["embedded"], json!([id.0]), "{r}"); + assert_eq!(undo_len(&s), undo + 2); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + assert!(image(&s, id).link.is_none()); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + let r = s.execute("links.unembed", &json!({"id": id.0, "path": written})).unwrap(); + assert_eq!(r["id"], json!(id.0), "{r}"); + assert_eq!(undo_len(&s), undo + 3); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + assert!(!clipped(&s)); + let im = image(&s, id); + assert_eq!((im.width, im.height), (60, 20)); + assert!(im.link.is_some()); + assert!(Path::new(&written).exists()); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + // Undo takes each back to the same corners, and the first file's pixels in the end. + for _ in 0..3 { + s.execute("edit.undo", &json!({})).unwrap(); + assert!(distorted(&s)); + assert_eq!(corners(&s), before); + } + assert_eq!((image(&s, id).width, image(&s, id).height), (20, 10)); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + +/// Unembed into a folder keeps a distorted image's corners, in one undo step. +#[test] +fn unembed_to_a_folder_keeps_a_distorted_images_corners() { + let dir = Folder::new("distorted-unembed-folder"); + let (photo, out) = (dir.file("photo.png"), dir.file("out")); + std::fs::create_dir_all(&out).unwrap(); + write(&photo, &png(20, 10, RED)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("links.unembed", &json!({"ids": [id.0], "folder": out})).unwrap(); + assert_eq!(r["unembedded"][0]["id"], json!(id.0), "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image()); + assert_eq!(corners(&s), before); + assert!(image(&s, id).link.is_some()); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + +/// Embed reads the file of a distorted image that shows its saved preview and keeps the file's +/// pixels in the document between the image's corners, in one undo step. +#[test] +fn embed_reads_a_distorted_images_file_between_its_corners() { + let dir = Folder::new("distorted-embed-preview"); + let photo = dir.file("photo.png"); + // Large enough that the document saves a smaller preview of it. + write(&photo, &png(600, 300, RED)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + let doc_path = dir.file("poster.vectorcraft"); + save(&mut s, &doc_path); + std::fs::remove_file(&photo).unwrap(); + open(&mut s, &doc_path); + assert!(s.doc().unwrap().doc.images[&image(&s, id).key].is_proxy(), "the preview stands in"); + assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image()); + write(&photo, &png(400, 200, BLUE)); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(r, json!({"embedded": [id.0], "missing": []})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(n.is_distorted_image()); + assert_eq!(n.image_corners().unwrap(), before); + let im = image(&s, id); + assert_eq!((im.width, im.height, im.link.is_none()), (400, 200, true)); + assert!(!s.doc().unwrap().doc.images[&im.key].is_proxy(), "the file's pixels are in the document"); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); +} + /// Update Links reads a changed file again for the images inside symbols, patterns and opacity /// masks too: those showing the same content as an image in the layers, and those no object in the /// layers shows. Each takes the file's place as its own Placement Options say, in one undo step, diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index ccc735440e..ac73b66727 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -723,9 +723,6 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() { for (cmd, params) in [ ("object.cropImage", json!({})), ("imageTrace.make", json!({})), - ("links.relink", json!({"path": "/nowhere/pic.png"})), - ("links.embed", json!({"ids": [img.0]})), - ("links.unembed", json!({})), ("object.createObjectMosaic", json!({})), ("object.mesh.create", json!({})), ( diff --git a/docs/mcp.md b/docs/mcp.md index 729d5523cc..4a56181924 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6662,12 +6662,14 @@ rules opens with the image placed by its transform. A drag is one undo step, and where they are records none. Image info (`image.info`) gives a distorted image's resolution at its middle, and Link Info (`links.info`) gives its scale and rotation there. -Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Relink (`links.relink`), -Embed (`links.embed`), Unembed (`links.unembed`), Create Object Mosaic (`object.createObjectMosaic`), Create -Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with `replace`) refuse a distorted image with -an error that names the distortion. Update Links (`links.update`) puts a changed file's pixels between a distorted -image's corners, without applying its Placement Options. Mask (`object.maskImage`) draws its clipping path through the -image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the +Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Create Object Mosaic +(`object.createObjectMosaic`), Create Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with +`replace`) refuse a distorted image with an error that names the distortion. Update Links (`links.update`) and Relink +(`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or +Relink's `preserve`. The clipping path a PSD, PSB or DCS file names is drawn through the corners: a clip group of the +old file's clipping path takes the new file's, or becomes a plain group when the new file names none. Embed +(`links.embed`) and Unembed (`links.unembed`) keep the corners, each in one undo step. Mask (`object.maskImage`) draws +its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the result. These rules are VectorCraft's own. ```json @@ -8773,7 +8775,9 @@ every object in the layers each time the list is read. A `dcsTransparency` that `links.goTo {id}` selects an image (`onCanvas: true`); for an object outside the layer tree it clears the selection and returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file -(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. +(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD +or PSB file written as stored (PNG, or TIFF for a CMYK file) keeps the clip group of the clipping path that file +names, and the file written keeps the path for Place, Relink and Update Links. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ec79a36837..f8e37693f4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1069,7 +1069,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Relink, Embed, Unembed, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links puts a changed file's pixels between its corners; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_an_embedded_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). From ea7731f6c2421aac785e420e129599f4749770d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 22:12:45 -0800 Subject: [PATCH 002/126] Links: Relink warns when preserve is not applied to a distorted image Relink with `preserve` on an image changed by Perspective Distort or Free Distort keeps the image's corners and now adds a `warnings` entry naming the images the value was not applied to. The params text of Update Links now says how it handles a distorted image's corners and clipping path, and the docs/mcp.md paragraph is rewrapped. docs/mcp.md says that Open also reads a PNG or TIFF written by Unembed with its clip group. New tests cover Update Links and Relink of a distorted image with a PSD or DCS clipping path, Relink with scope all of a distorted image in an opacity mask, and Open of a file written by Unembed. --- crates/engine/src/cmd/fileio/load.rs | 2 +- crates/engine/src/cmd/fileio/tests_psdread.rs | 44 ++++++++++++++++- crates/engine/src/cmd/links.rs | 29 ++++++++++-- crates/engine/src/tests/dcs.rs | 47 +++++++++++++++++++ crates/engine/src/tests/links.rs | 39 ++++++++++++++- docs/mcp.md | 13 ++--- 6 files changed, 160 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 9de13076ae..8249fe6b71 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -963,7 +963,7 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; /// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported /// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes -/// it) comes with it. +/// it) is read with that path. pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index ad17346d19..2eb7f74d81 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -648,9 +648,45 @@ fn relink_follows_the_clipping_path_of_a_distorted_psd() { assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// Update Links follows the clipping path of a linked PSD file for an image changed by Perspective +/// Distort or Free Distort: the file's new clipping path is drawn through the image's corners, and +/// a file without one leaves a plain group. +#[test] +fn update_links_follows_the_clipping_path_of_a_distorted_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-update-distorted"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone(); + let corners = node(&s).image_corners().unwrap(); + let map = node(&s).image_map().unwrap(); + let squared: Vec<[f64; 2]> = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]] + .iter() + .map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()) + .map(|p| [p.x, p.y]) + .collect(); + std::fs::write(&cut, red_psd(&square_resources())).unwrap(); + s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let near = anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && even_odd && held == image, "the file's new clipping path: {anchors:?} vs {squared:?}"); + assert_eq!(node(&s).image_corners().unwrap(), corners); + std::fs::write(&cut, red_psd(&[])).unwrap(); + s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + match s.doc().unwrap().doc.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + assert_eq!(node(&s).image_corners().unwrap(), corners); +} + /// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, for a /// plain image and for one changed by Perspective Distort or Free Distort, and so do reading the -/// written file again and placing it. +/// written file again, placing it and opening it. #[test] fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); @@ -693,6 +729,12 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { let placed = NodeId(r["ids"][0].as_u64().unwrap()); let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); assert!(even_odd && anchors.len() == before.0.len(), "{kind}, place: {anchors:?} vs {:?}", before.0); + // Opening it gives a document of the image in that clip group. + s.execute("document.open", &json!({"path": path})).unwrap(); + let d = &s.doc().unwrap().doc; + let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object"); + let (anchors, even_odd, _) = clip_group(d, top); + assert!(even_odd && anchors.len() == before.0.len(), "{kind}, open: {anchors:?} vs {:?}", before.0); } } } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 233994d655..45bbc4e5e6 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Update Links", [], None, - "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", + "{ids?: [image or placed document ids] (default: the linked images whose file was modified or is showing its preview, and placed documents whose file was modified)} read their linked files again; each keeps its bounds. Images and placed documents inside symbols, graph designs, patterns, opacity masks and the art of stored brushes have ids of their own, as links.list gives them; those that show the same content as one read again are read again too. An image changed by Perspective Distort or Free Distort keeps its corners, with the file's pixels between them, and its Placement Options do not apply; the clipping path its file names is drawn through the corners, and a clip group of the old file's clipping path gets the new one, or becomes a plain group when the file names none. One undo step → {updated: [ids], missing: [ids], warnings?: [a DCS file's spot plate whose ink a swatch of the document already names, as file.place warns]}", has_doc, update ), @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say; the clipping path its file names is drawn through the corners. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and one naming the distorted images that preserve was not applied to)}", has_doc, relink ), @@ -634,8 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). A PNG or TIFF written from a PSD or PSB file's image (by Unembed) -/// comes with the clipping path it keeps ([`fileio::raster_image`]). +/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image +/// is read with the clipping path it keeps ([`fileio::raster_image`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; @@ -2255,8 +2255,10 @@ fn relink(s: &mut Session, p: &Value) -> Result { } } let relinked: Vec = reads.iter().flat_map(|(ids, _)| ids_json(ids)).collect(); + let unpreserved = preserve.and_then(|_| unpreserved_note(&doc, &reads)); drop(doc); - let warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); + let mut warnings = spot_swatch_notes(&s.doc()?.doc, reads.iter().map(|(_, read)| read)); + warnings.extend(unpreserved); if !reads.is_empty() { s.edit("Relink", |d, _| editing_brush_art(d, |d| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, preserve, None))))?; } @@ -2279,6 +2281,23 @@ fn relink(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The warning that Relink's `preserve` was not applied to the images of `reads` changed by +/// Perspective Distort or Free Distort, which keep their corners, naming them; `None` when there +/// are none. +fn unpreserved_note(doc: &Document, reads: &[(Vec, Read)]) -> Option { + let ids: Vec = reads + .iter() + .filter(|(_, read)| matches!(read, Read::Image(_))) + .flat_map(|(ids, _)| ids) + .filter(|id| stored(doc, **id).is_some_and(Node::is_distorted_image)) + .map(|id| id.0.to_string()) + .collect(); + let images = if ids.len() == 1 { "image" } else { "images" }; + (!ids.is_empty()).then(|| { + format!("preserve was not applied to {images} {}: an image changed by Perspective Distort or Free Distort keeps its corners", ids.join(", ")) + }) +} + /// `links.relink {scope: "missingInFolder"}`: the other missing links of `st` (not `given`; only /// images when `images_only`, as copy takes), each added to `files` with the file of its name in /// the folder of the first file there; names not there go to `not_found`. diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 43bdf180a7..6d23bd23d0 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -220,6 +220,53 @@ fn update_link_takes_the_files_new_clipping_path() { assert!((after - before / 2.0).abs() < 1e-6, "the clipping path follows the file: {before} → {after}"); } +/// For an image changed by Perspective Distort or Free Distort, Update Links and Relink draw the +/// DCS file's new clipping path through the image's corners, and a file without one leaves a plain +/// group. +#[test] +fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_corners() { + let dir = temp_dir("distorted-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = image_of(&s, &r["ids"][0]).id; + s.execute("select.set", &json!({ "ids": [group.0] })).unwrap(); + s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap(); + let node = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node(&s).is_distorted_image()); + let corners = node(&s).image_corners().unwrap(); + // The clip group's path anchors, and points of the 2 × 2 pixels where the corners put them. + let anchors = |s: &Session| { + let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") }; + path.anchors().map(|(_, _, a)| a.p).collect::>() + }; + let on_page = |s: &Session, x: f64| { + let map = node(s).image_map().unwrap(); + [(0.0, 0.0), (x, 0.0), (x, 2.0), (0.0, 2.0)].map(|(px, py)| map.apply(vectorcraft_geom::Point::new(px, py)).unwrap()) + }; + let matches = |found: &[vectorcraft_geom::Point], want: &[vectorcraft_geom::Point]| { + found.len() == want.len() && want.iter().all(|w| found.iter().any(|f| f.distance(*w) < 1e-6)) + }; + assert!(matches(&anchors(&s), &on_page(&s, 1.0)), "the left half: {:?} vs {:?}", anchors(&s), on_page(&s, 1.0)); + // The same file, its composite drawn through the left quarter of the page (same length). + let quarter = String::from_utf8(two_plates()).unwrap().replacen("10 0 lineto 10 10 lineto", " 5 0 lineto 5 10 lineto", 1); + std::fs::write(&path, quarter.as_bytes()).unwrap(); + s.execute("links.update", &json!({ "ids": [id.0] })).unwrap(); + assert!(matches(&anchors(&s), &on_page(&s, 0.5)), "the left quarter: {:?} vs {:?}", anchors(&s), on_page(&s, 0.5)); + assert_eq!(node(&s).image_corners().unwrap(), corners); + // Relink to a file whose composite has no clipping path. + let unclipped = String::from_utf8(two_plates()).unwrap().replacen("closepath clip newpath", "closepath newpath ", 1); + let other = write(&dir, "other.eps", unclipped.as_bytes()); + s.execute("links.relink", &json!({ "ids": [id.0], "path": other })).unwrap(); + match &s.doc().unwrap().doc.node(group).unwrap().kind { + NodeKind::Group { children, clip: false } => assert_eq!(children.iter().map(|c| c.id).collect::>(), [id]), + other => panic!("a plain group of the image: {other:?}"), + } + assert_eq!(node(&s).image_corners().unwrap(), corners); +} + #[test] fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { let dir = temp_dir("update-gained-clip"); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index efaf396a4e..e045ea62fd 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -693,6 +693,7 @@ fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() { let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap(); let relinked = r["relinked"].as_array().unwrap(); assert!(relinked.len() == 2 && relinked.contains(&json!(id.0)), "the image and the symbol's: {r}"); + assert!(r.get("warnings").is_none(), "no preserve was given: {r}"); let n = s.doc().unwrap().doc.node(id).unwrap().clone(); assert_eq!((n.is_distorted_image(), n.image_corners().unwrap()), (true, before)); assert_eq!((image(&s, id).width, image(&s, id).height), (60, 20)); @@ -700,6 +701,40 @@ fn relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols() { assert_eq!(in_symbol(&s), [(Some(symbol_quad), (60, 20))], "the symbol's image keeps its corners"); } +/// Relink with scope `all` puts the new file's pixels between the corners of a distorted image in +/// an opacity mask's art. +#[test] +fn relink_of_all_instances_keeps_the_corners_of_a_distorted_image_in_an_opacity_mask() { + let dir = Folder::new("distorted-relink-mask"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + let masked = super::rect(&mut s, 10.0, 10.0, 60.0, 60.0); + let mask = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[10, 10], [60, 15], [58, 50], [5, 45]]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked.0, mask.0]})).unwrap(); + // The image in the art of `masked`'s opacity mask: (id, corners, pixel size). + let in_mask = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.visit_stored(|n, place| { + if let NodeKind::Image(im) = &n.kind + && place.mask_of == Some(masked) + { + out.push((n.id, n.image_quad(), (im.width, im.height))); + } + }); + out + }; + let [(mask_id, Some(quad), (20, 10))] = in_mask(&s)[..] else { panic!("one distorted image in the mask: {:?}", in_mask(&s)) }; + let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "scope": "all"})).unwrap(); + let relinked = r["relinked"].as_array().unwrap(); + assert!(relinked.len() == 2 && relinked.contains(&json!(mask_id.0)), "the image and the mask's: {r}"); + assert_eq!(in_mask(&s), [(mask_id, Some(quad), (60, 20))], "the mask's image keeps its corners"); +} + /// Relink, Embed and Unembed keep a distorted image's corners, each in one undo step: Relink puts /// the new file's pixels between them whatever `preserve` and the Placement Options say, Embed /// keeps the pixels in the document, and Unembed links the image to the file it writes. @@ -727,7 +762,9 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() { let undo = undo_len(&s); let r = s.execute("links.relink", &json!({"ids": [id.0], "path": other, "preserve": "fileDimensions"})).unwrap(); - assert_eq!(r["relinked"], json!([id.0]), "{r}"); + // The given preserve is reported as not applied. + let warning = format!("preserve was not applied to image {}: an image changed by Perspective Distort or Free Distort keeps its corners", id.0); + assert_eq!(r, json!({"relinked": [id.0], "notFound": [], "warnings": [warning]})); assert_eq!(undo_len(&s), undo + 1); assert!(distorted(&s)); assert_eq!(corners(&s), before); diff --git a/docs/mcp.md b/docs/mcp.md index 4a56181924..cb77529181 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6666,11 +6666,12 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak (`object.createObjectMosaic`), Create Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with `replace`) refuse a distorted image with an error that names the distortion. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or -Relink's `preserve`. The clipping path a PSD, PSB or DCS file names is drawn through the corners: a clip group of the -old file's clipping path takes the new file's, or becomes a plain group when the new file names none. Embed -(`links.embed`) and Unembed (`links.unembed`) keep the corners, each in one undo step. Mask (`object.maskImage`) draws -its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the -result. These rules are VectorCraft's own. +Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS +file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping +path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep +the corners, each in one undo step. Mask (`object.maskImage`) draws its clipping path through the image's corners. +Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the result. These rules +are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} @@ -8777,7 +8778,7 @@ returns `{id, onCanvas: false, owner}`, and the panel says the link has no place file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD or PSB file written as stored (PNG, or TIFF for a CMYK file) keeps the clip group of the clipping path that file -names, and the file written keeps the path for Place, Relink and Update Links. +names, and the file written keeps the path: Open, Place, Relink and Update Links read the file with its clip group. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo From eb349d534d4a766cfb9b04f341259512ce281660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 06:17:24 -0800 Subject: [PATCH 003/126] Links: leave reading a PNG's kept clipping path to its own fix The loader change that read the clipping path a PNG or TIFF keeps also changed File > Open and File > Place of plain images. It is now #8561, with its tests, params text and docs, and this branch reads files as main does. For a distorted image, Relink and Update Links now read the new file's clipping path from the PNG or TIFF it is stored as when the reader gives none, as they already do for the old file. Unembed of a distorted image from a PSD or PSB file, with or without a folder, therefore keeps the clip group of that file's clipping path, and so does a later Relink to the written file. - Test: tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd (RGB file kept as PNG, CMYK file kept as TIFF, path and folder). - Docs: docs/mcp.md, links.unembed params text, the progress-doc line. --- crates/engine/src/cmd/fileio/load.rs | 9 ++-- crates/engine/src/cmd/fileio/tests_psdread.rs | 48 ++++++++----------- crates/engine/src/cmd/links.rs | 12 ++--- docs/mcp.md | 11 ++--- docs/target-app-parity.md | 2 +- 5 files changed, 35 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 8249fe6b71..4e59e378a5 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -962,8 +962,7 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; /// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported -/// clipping path ([`image_clip`]), and a PNG or TIFF that keeps such a path (as Unembed writes -/// it) is read with that path. +/// clipping path ([`image_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { @@ -1140,15 +1139,13 @@ pub fn texture_image(bytes: &[u8]) -> Result { texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) } -/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a -/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]). +/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed. fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result { if width == 0 || height == 0 { return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 2eb7f74d81..4e43565b56 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -684,29 +684,34 @@ fn update_links_follows_the_clipping_path_of_a_distorted_psd() { assert_eq!(node(&s).image_corners().unwrap(), corners); } -/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, for a -/// plain image and for one changed by Perspective Distort or Free Distort, and so do reading the -/// written file again, placing it and opening it. +/// Unembed of a distorted image from a PSD file, with a path and with a folder, keeps the clip +/// group of the clipping path that file names, drawn through its corners, and so does relinking it +/// to the file written. #[test] -fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { - let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); +fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-distorted-clip"); // An RGB file is kept as a PNG, a CMYK one as a TIFF. let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; - for ((kind, file), distort) in files.iter().flat_map(|f| [(f, false), (f, true)]) { + for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) { let data = vectorcraft_format::base64_encode(file); let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); - if distort { - s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); - s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); - } + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); let before = clip_group(&s.doc().unwrap().doc, group); // Without an extension the image is written in the format it is stored in. - let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}-{distort}"))})).unwrap(); - let path = r["path"].as_str().unwrap().to_string(); + let path = if folder { + let out = dir.join(format!("folder-{kind}")); + std::fs::create_dir_all(&out).unwrap(); + let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + r["unembedded"][0]["path"].as_str().unwrap().to_string() + } else { + let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap(); + r["path"].as_str().unwrap().to_string() + }; let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); for step in ["unembed", "relink"] { @@ -716,25 +721,12 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; assert!(im.link.is_some(), "linked to the file written"); - assert_eq!(d.node(image).unwrap().is_distorted_image(), distort); - // A distorted image's clipping path is drawn through its corners again, within rounding. + assert!(d.node(image).unwrap().is_distorted_image()); + // The clipping path is drawn through the corners again, within rounding. let (anchors, even_odd, held) = clip_group(d, group); let near = anchors.len() == before.0.len() && anchors.iter().zip(&before.0).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); - assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, distorted: {distort}: {anchors:?} vs {:?}", before.0); - } - // Placing the written file gives the same clip group as placing the PSD file did. - if !distort { - let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap(); - let placed = NodeId(r["ids"][0].as_u64().unwrap()); - let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); - assert!(even_odd && anchors.len() == before.0.len(), "{kind}, place: {anchors:?} vs {:?}", before.0); - // Opening it gives a document of the image in that clip group. - s.execute("document.open", &json!({"path": path})).unwrap(); - let d = &s.doc().unwrap().doc; - let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object"); - let (anchors, even_odd, _) = clip_group(d, top); - assert!(even_odd && anchors.len() == before.0.len(), "{kind}, open: {anchors:?} vs {:?}", before.0); + assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {:?}", before.0); } } } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 45bbc4e5e6..5ebe9c5f54 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners); written as stored, an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path for later reads. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners and, when it came from a PSD or PSB file, the clip group of that file's clipping path, with or without folder). One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -634,8 +634,7 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image -/// is read with the clipping path it keeps ([`fileio::raster_image`]). +/// can't be read ([`readable`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; @@ -1223,8 +1222,9 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ /// transform still gives it its old size. Its Placement Options do not apply. The result is what /// happens to its clip, as [`clip_to`] decides from the clipping path of the clip group holding /// just it (`held`): the clipping paths of its old file (`old_clip`, in its old pixels) and of the -/// new file are mapped to the page through its corners, anchors and handles alike, as a distort -/// maps a path's. +/// new file (`img.clip`, else the path kept in its stored PNG or TIFF, as Unembed writes it: +/// [`file_clip`]) are mapped to the page through its corners, anchors and handles alike, as a +/// distort maps a path's. fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, img: &RasterImage, held: Option<(&PathData, FillRule)>) -> ClipTo { let old = old_clip.filter(|_| held.is_some()).and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); if let NodeKind::Image(im) = &mut n.kind { @@ -1233,7 +1233,7 @@ fn refill_distorted(n: &mut Node, old_clip: Option<&FileClip>, link: &LinkInfo, } (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); } - let file = img.clip.as_ref().and_then(|(path, rule)| Some((warped(path, &n.image_map()?)?, *rule))); + let file = img.clip.clone().or_else(|| file_clip(&img.blob)).and_then(|(path, rule)| Some((warped(&path, &n.image_map()?)?, rule))); placed_clip_to(old.as_ref(), None, file, held) } diff --git a/docs/mcp.md b/docs/mcp.md index cb77529181..f80563dc27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6669,9 +6669,10 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep -the corners, each in one undo step. Mask (`object.maskImage`) draws its clipping path through the image's corners. -Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the result. These rules -are VectorCraft's own. +the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file keeps the clip group of that +file's clipping path, and so does Relink to the PNG or TIFF it wrote. Mask (`object.maskImage`) draws its clipping +path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a +plain image of the result. These rules are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} @@ -8776,9 +8777,7 @@ every object in the layers each time the list is read. A `dcsTransparency` that `links.goTo {id}` selects an image (`onCanvas: true`); for an object outside the layer tree it clears the selection and returns `{id, onCanvas: false, owner}`, and the panel says the link has no place on the canvas. `links.embed {ids?}` keeps linked files' pixels in the document (an image whose file is missing stays linked: relink it first); `links.unembed {id, path}` writes an embedded image to a file -(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD -or PSB file written as stored (PNG, or TIFF for a CMYK file) keeps the clip group of the clipping path that file -names, and the file written keeps the path: Open, Place, Relink and Update Links read the file with its clip group. +(another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8e37693f4..0cb9fc915b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1069,7 +1069,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`). - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_an_embedded_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles, alone or with other objects, and draw its pixels in perspective between them on the canvas, in print and in every export, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image; Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). From ef2dcb9df1ff85af13e1fbe735be6af068ee7c09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 07:14:51 -0800 Subject: [PATCH 004/126] Links: Unembed keeps a distorted image's clip group only when written as stored The links.unembed params text and docs/mcp.md now say that a distorted image from a PSD or PSB file keeps its clip group when Unembed writes it in the format it is stored in (PNG, or TIFF for a CMYK file), and that Relink and Update Links to the written file keep it too. A path that converts the image writes no clipping path, and the clip group becomes a plain group. - Test: tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd adds an Update Links step on the written file and an Unembed to a .jpg path. --- crates/engine/src/cmd/fileio/tests_psdread.rs | 21 ++++++++++++++++++- crates/engine/src/cmd/links.rs | 2 +- docs/mcp.md | 9 ++++---- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 4e43565b56..a1c376e938 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -714,10 +714,14 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { }; let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); - for step in ["unembed", "relink"] { + for step in ["unembed", "relink", "update"] { if step == "relink" { s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); } + if step == "update" { + let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + assert_eq!(r["updated"], json!([image.0]), "{kind}: {r}"); + } let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; assert!(im.link.is_some(), "linked to the file written"); @@ -729,6 +733,21 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {:?}", before.0); } } + // A path that converts the image writes a file without the clipping path: the clip group + // becomes a plain group of the image, as Relink to any file without one leaves it. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources())); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + s.execute("links.unembed", &json!({"id": image.0, "path": dir.join("converted.jpg")})).unwrap(); + match s.doc().unwrap().doc.node(group).map(|n| &n.kind) { + Some(NodeKind::Group { children, clip: false }) => assert_eq!(children.iter().map(|c| c.id).collect::>(), [image]), + other => panic!("a plain group of the image: {other:?}"), + } + assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image()); } /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 5ebe9c5f54..d83e1178fd 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners and, when it came from a PSD or PSB file, the clip group of that file's clipping path, with or without folder). One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds (an image changed by Perspective Distort or Free Distort keeps its corners; written as stored (here and with folder), such an image from a PSD or PSB file also keeps the clip group of the clipping path that file names, and the file written keeps the path, so Relink and Update Links to it keep the clip group; a path that converts the image writes no clipping path, and the clip group becomes a plain group). One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds (a distorted image its corners). One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), diff --git a/docs/mcp.md b/docs/mcp.md index f80563dc27..5144c4698c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6669,10 +6669,11 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep -the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file keeps the clip group of that -file's clipping path, and so does Relink to the PNG or TIFF it wrote. Mask (`object.maskImage`) draws its clipping -path through the image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a -plain image of the result. These rules are VectorCraft's own. +the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file, written as stored (PNG, or +TIFF for a CMYK file), keeps the clip group of that file's clipping path, and so do Relink and Update Links to the +file it wrote; a path that converts the image writes no clipping path, and the clip group becomes a plain group. Mask +(`object.maskImage`) draws its clipping path through the image's corners. Rasterize (`object.rasterize`) draws the +image between its corners and makes a plain image of the result. These rules are VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} From e3ccd346add9c2bb196d9181b27d4e4eeb50a575 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:40:51 -0800 Subject: [PATCH 005/126] Selection: widget drags read the release point and a tool switch cancels them A drag of a corner, pie or blend widget, an Objects on Path widget, a bracket of type on a path or a 9-slice guide released away from its last drag event now drags there before it ends, so the release keeps what a drag to that point would show. The Objects on Path tool reads the release the same way. Switching tools during a drag of an Objects on Path widget, a bracket, a repeat control or a 9-slice guide now cancels it, as Escape does, in the Selection tool and the Objects on Path tool. Before, the preview stayed open after the tool was gone. --- crates/tools/src/blendwidget.rs | 12 ++- crates/tools/src/lib.rs | 20 +++++ crates/tools/src/mirror.rs | 16 ++++ crates/tools/src/nineslice.rs | 9 ++ crates/tools/src/objects_on_path.rs | 132 ++++++++++++++++++++++++++-- crates/tools/src/pie.rs | 10 +++ crates/tools/src/repeat_grid.rs | 11 +++ crates/tools/src/repeat_radial.rs | 11 +++ crates/tools/src/select.rs | 62 +++++++++---- crates/tools/src/select/tests.rs | 22 +++++ 10 files changed, 282 insertions(+), 23 deletions(-) diff --git a/crates/tools/src/blendwidget.rs b/crates/tools/src/blendwidget.rs index e09df663bb..3f53287625 100644 --- a/crates/tools/src/blendwidget.rs +++ b/crates/tools/src/blendwidget.rs @@ -512,7 +512,7 @@ mod tests { assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 0.0}))], "clamped at 0"); let a = t.pointer(&c, &ev(PointerKind::Drag, at + Vec2::new(500.0, 0.0))); assert_eq!(a, vec![Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 100.0}))], "clamped at 100"); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at)), vec![Action::Commit]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at + Vec2::new(500.0, 0.0))), vec![Action::Commit]); // A click that doesn't move sends nothing. assert!(t.pointer(&c, &ev(PointerKind::Down, at)).is_empty()); assert!(t.pointer(&c, &ev(PointerKind::Up, at)).is_empty()); @@ -546,6 +546,16 @@ mod tests { assert_eq!(a[1], Action::Preview("object.blend.setEasing".into(), json!({"id": id.0, "ramp": 50.0}))); } + /// A drag with the Selection tool reads where it is released, and a tool switch cancels it. + #[test] + fn a_drag_reads_its_release() { + let (d, _, s) = blend_doc(&[(100.0, 200.0), (300.0, 200.0)], eased()); + let p = paint(); + let c = cx(&d, &s, &p); + let at = Point::new(200.0, 216.0); + check_widget_release_and_tool_switch(&c, at, at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 0.0)); + } + /// Switching away from the Selection or Blend tool during a drag cancels it, and after a press /// that has not moved there is nothing to put back. #[test] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 0b7bef755f..781d86da41 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -600,6 +600,26 @@ pub(crate) mod testutil { PaintDefaults::default() } + /// With the Selection tool, a widget pressed at `at` and dragged to `q`, then released at `r`, is + /// dragged to `r` before the drag ends: the release keeps what a drag to `r` shows. Switching + /// tools during the drag cancels it, and the release after it commits nothing. + pub fn check_widget_release_and_tool_switch(cx: &ToolContext, at: Point, q: Point, r: Point) { + let pressed = || { + let mut t = crate::select::SelectionTool::default(); + t.pointer(cx, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(!t.pointer(cx, &PointerEvent::new(PointerKind::Drag, q.x, q.y)).is_empty(), "the drag to {q:?} changes the widget"); + t + }; + let mut want = pressed().pointer(cx, &PointerEvent::new(PointerKind::Drag, r.x, r.y)); + assert!(!want.is_empty(), "the drag to {r:?} changes the widget"); + want.push(Action::Commit); + assert_eq!(pressed().pointer(cx, &PointerEvent::new(PointerKind::Up, r.x, r.y)), want, "released at {r:?}"); + let mut t = pressed(); + assert_eq!(t.deactivate(cx), vec![Action::Cancel], "a tool switch cancels the drag"); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(cx, &PointerEvent::new(PointerKind::Up, q.x, q.y)).is_empty(), "the release commits nothing"); + } + /// An 800 × 600 window on a view at 100% turned `deg` degrees clockwise (Rotate View): at 90° /// one pixel right on screen is one point up the page. pub fn turned_view(deg: f64) -> Option { diff --git a/crates/tools/src/mirror.rs b/crates/tools/src/mirror.rs index 5560fbc321..fac52cca3a 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -184,4 +184,20 @@ mod tests { spec.kind = RepeatKind::Mirror { angle: f64::NAN, center: Point::ZERO }; assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none()); } + + /// With the Selection tool, a drag of the axis reads where it is released, and a tool switch + /// cancels it. + #[test] + fn an_axis_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0)); + let mut selection = Selection::default(); + selection.set([id]); + let paint = paint(); + let cx = cx(&doc, &selection, &paint); + let at = MirrorAxis::of(&doc, &selection, 1.0).unwrap().center; + crate::testutil::check_widget_release_and_tool_switch(&cx, at, at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 0.0)); + } } diff --git a/crates/tools/src/nineslice.rs b/crates/tools/src/nineslice.rs index 74f40b6bbf..d21a5f42a2 100644 --- a/crates/tools/src/nineslice.rs +++ b/crates/tools/src/nineslice.rs @@ -238,6 +238,15 @@ mod tests { assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 150.0, 250.0)), vec![Action::Commit]); } + /// A guide drag reads where it is released, and a tool switch cancels it. + #[test] + fn a_guide_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let d = editing(Some(SymbolNineSlice::default())); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&c, Point::new(126.0, 150.0), Point::new(115.0, 150.0), Point::new(105.0, 150.0)); + } + /// Escape during a guide drag cancels it and is the tool's; the release after it commits /// nothing. A double-click on a guide neither edits the art nor leaves the mode. #[test] diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index dbb6f8bfdf..906600f334 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -948,6 +948,9 @@ pub struct ObjectsOnPathTool { member: Option, /// Where the pointer is while no button is down, for the Select/Move widget it is over. pointer: Option, + /// Where the pointer was at the last press or drag: a widget drag released anywhere else is + /// dragged there before it ends. + held_at: Option, /// The reference point of each object attached next (0-8, row by row from the top left). pivot: u8, /// The angle of each object attached next, in degrees counter-clockwise from upright on the path. @@ -956,7 +959,18 @@ pub struct ObjectsOnPathTool { impl Default for ObjectsOnPathTool { fn default() -> Self { - Self { hover: None, press: None, rotating: None, spacing: None, moving: None, member: None, pointer: None, pivot: CENTER, rotate: 0.0 } + Self { + hover: None, + press: None, + rotating: None, + spacing: None, + moving: None, + member: None, + pointer: None, + held_at: None, + pivot: CENTER, + rotate: 0.0, + } } } @@ -967,31 +981,51 @@ impl Tool for ObjectsOnPathTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; + let released_away = ev.kind == PointerKind::Up && self.held_at != Some(p); + if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { + self.held_at = Some(p); + } if let Some(d) = &mut self.rotating { return match ev.kind { PointerKind::Drag => d.drag(cx, p, ev.mods.shift), - PointerKind::Up => self.rotating.take().map(RotateAllDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p, ev.mods.shift) } else { vec![] }; + out.extend(self.rotating.take().map(RotateAllDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } if let Some(d) = &mut self.spacing { return match ev.kind { PointerKind::Drag => d.drag(cx, p, ev.mods.alt), - PointerKind::Up => self.spacing.take().map(SpaceDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p, ev.mods.alt) } else { vec![] }; + out.extend(self.spacing.take().map(SpaceDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } if let Some(d) = &mut self.moving { return match ev.kind { PointerKind::Drag => d.drag(cx, p), - PointerKind::Up => self.moving.take().map(MoveAllDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p) } else { vec![] }; + out.extend(self.moving.take().map(MoveAllDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } if let Some(d) = &mut self.member { return match ev.kind { PointerKind::Drag => d.drag(cx, p), - PointerKind::Up => self.member.take().map(MemberDrag::finish).unwrap_or_default(), + PointerKind::Up => { + let mut out = if released_away { d.drag(cx, p) } else { vec![] }; + out.extend(self.member.take().map(MemberDrag::finish).unwrap_or_default()); + out + } _ => vec![], }; } @@ -1084,6 +1118,11 @@ impl Tool for ObjectsOnPathTool { vec![] } + /// Switching tools while the button is down cancels the click or the drag, as Escape does. + fn deactivate(&mut self, cx: &ToolContext) -> Vec { + self.key(cx, ToolKey::Escape, Mods::default()) + } + fn options(&self) -> Value { json!({ "pivot": self.pivot, "rotate": self.rotate }) } @@ -1508,7 +1547,7 @@ mod tests { assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["spacing"] == "auto" && p["start"] == 0.0), "{id}: {a:?}"); assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 0.0)), "{id}"); assert_eq!(spaced(&t.pointer(&c, &alt(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, 200.0)), "{id}"); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert_eq!(t.pointer(&c, &alt(PointerKind::Up, at.x - 900.0, at.y)), vec![Action::Commit], "{id}"); assert!(!t.busy(), "{id}"); // A click on the widget that does not move changes nothing. assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); @@ -1730,7 +1769,7 @@ mod tests { assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 900.0, at.y))), Some((300.0, None)), "{id}"); assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 880.0, at.y))), Some((280.0, None)), "{id}"); assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, None)), "{id}"); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x - 900.0, at.y)), vec![Action::Commit], "{id}"); assert!(!t.busy(), "{id}"); // A click on the widget that does not move changes nothing. assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); @@ -2007,6 +2046,85 @@ mod tests { } } + /// The release is read where it happens: a release away from the last drag event drags the + /// widget there before the drag ends, with the Selection tool and the Objects on Path tool. + #[test] + fn the_release_position_sets_each_widget() { + let new_tools = || -> [Box; 2] { [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())] }; + let paint = paint(); + let (d, _, sel) = group_doc(0.0); + let c = cx(&d, &sel, &paint); + for mut t in new_tools() { + let (at, q, r) = (around(0.0), around(60.0), around(90.0)); + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &ev(PointerKind::Drag, q.x, q.y)); + let a = t.pointer(&c, &ev(PointerKind::Up, r.x, r.y)); + let (last, shown) = a.split_last().unwrap(); + assert_eq!(last, &Action::Commit, "{}", t.id()); + assert!(previewed(shown).is_some_and(|deg| (deg - 90.0).abs() < 1e-9), "{}: Rotate All {a:?}", t.id()); + } + let at = SpaceWidget::of(&d, &sel, 1.0).unwrap().at; + for mut t in new_tools() { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &ev(PointerKind::Drag, at.x - 100.0, at.y)); + let a = t.pointer(&c, &ev(PointerKind::Up, at.x - 50.0, at.y)); + let (last, shown) = a.split_last().unwrap(); + assert_eq!(last, &Action::Commit, "{}", t.id()); + assert_eq!(spaced(shown), Some((350.0, 0.0)), "{}: Space {a:?}", t.id()); + } + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let c = cx(&d, &sel, &paint); + let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at; + for mut t in new_tools() { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + t.pointer(&c, &ev(PointerKind::Drag, at.x + 80.0, at.y)); + let a = t.pointer(&c, &ev(PointerKind::Up, at.x + 90.0, at.y)); + let (last, shown) = a.split_last().unwrap(); + assert_eq!(last, &Action::Commit, "{}", t.id()); + assert_eq!(moved(shown), Some((140.0, None)), "{}: Move All {a:?}", t.id()); + } + let (d, _, sel, ids) = three_doc(); + let c = cx(&d, &sel, &paint); + for mut t in new_tools() { + t.pointer(&c, &ev(PointerKind::Down, 200.0, 300.0)); + t.pointer(&c, &ev(PointerKind::Drag, 280.0, 310.0)); + let a = t.pointer(&c, &ev(PointerKind::Up, 330.0, 300.0)); + assert_eq!(previewed_target(&a), Some(ids[2].0), "{}: Select/Move {a:?}", t.id()); + assert_eq!(a[1..], [Action::Commit, choose(ids[1])], "{}", t.id()); + } + } + + /// Switching tools during a widget drag cancels it, as Escape does, with the Selection tool and + /// the Objects on Path tool; after a press that has not moved there is nothing to put back. + #[test] + fn a_tool_switch_cancels_a_widget_drag() { + let new_tools = || -> [Box; 2] { [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())] }; + let paint = paint(); + let (d, _, sel) = group_doc(0.0); + let (md, _, msel) = spaced_doc(Some(100.0), 50.0); + let (od, _, osel, _) = three_doc(); + let space = SpaceWidget::of(&d, &sel, 1.0).unwrap().at; + let move_all = MoveAllWidget::of(&md, &msel, 1.0).unwrap().at; + let presses = [ + (cx(&d, &sel, &paint), around(0.0), around(60.0)), + (cx(&d, &sel, &paint), space, space - Vec2::new(100.0, 0.0)), + (cx(&md, &msel, &paint), move_all, move_all + Vec2::new(80.0, 0.0)), + (cx(&od, &osel, &paint), Point::new(200.0, 300.0), Point::new(330.0, 300.0)), + ]; + for (c, at, q) in &presses { + for mut t in new_tools() { + t.pointer(c, &ev(PointerKind::Down, at.x, at.y)); + assert!(!t.pointer(c, &ev(PointerKind::Drag, q.x, q.y)).is_empty(), "{}", t.id()); + assert_eq!(t.deactivate(c), vec![Action::Cancel], "{} at {at:?}", t.id()); + assert!(!t.busy() && !t.transforming(), "{}", t.id()); + assert!(t.pointer(c, &ev(PointerKind::Up, q.x, q.y)).is_empty(), "{}: the release keeps nothing", t.id()); + t.pointer(c, &ev(PointerKind::Down, at.x, at.y)); + assert!(t.deactivate(c).is_empty(), "{}", t.id()); + assert!(!t.busy(), "{}", t.id()); + } + } + } + /// Round a closed path the drag goes on across the first anchor: the first object, dragged back /// past it, takes the last place. #[test] diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index af79c1ce46..edf126b798 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -305,6 +305,16 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::Up, Point::new(100.0, 200.0))).is_empty(), "the release commits nothing"); } + /// A pie widget drag with the Selection tool reads where it is released, and a tool switch + /// cancels it. + #[test] + fn a_pie_widget_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (d, _, s) = doc_with_ellipse((0.0, 360.0)); + let p = paint(); + let c = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&c, Point::new(312.0, 150.0), Point::new(200.0, 20.0), Point::new(100.0, 150.0)); + } + /// On a whole ellipse the two widgets sit at the very same point, whatever its size, place or /// angle, so a press there always takes the End widget. #[test] diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index 07187a6a5a..75def8909f 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -369,6 +369,17 @@ mod tests { assert!(GridDrag::hit(&c, g.rows_at, Mods { alt: true, ..Mods::default() }).is_none()); } + /// With the Selection tool, a handle drag reads where it is released, and a tool switch cancels + /// it. + #[test] + fn a_handle_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (doc, selection) = grid(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap(); + crate::testutil::check_widget_release_and_tool_switch(&c, g.rows_at, g.rows_at + Vec2::new(0.0, 240.0), g.rows_at + Vec2::new(0.0, 360.0)); + } + #[test] fn a_bounding_box_handle_wins_where_they_overlap() { let (doc, selection) = grid(); diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 42a9f4395f..6c9ed57d7a 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -533,6 +533,17 @@ mod tests { assert!(RadialDrag::hit(&c, h.instances_at, Mods { alt: true, ..Mods::default() }).is_none()); } + /// With the Selection tool, a handle drag reads where it is released, and a tool switch cancels + /// it. + #[test] + fn a_handle_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let at = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap().instances_at; + crate::testutil::check_widget_release_and_tool_switch(&c, at, at + Vec2::new(0.0, 32.0), at + Vec2::new(0.0, 64.0)); + } + #[test] fn dragging_the_radius_handle_moves_the_circle_in_and_out() { let (doc, selection) = radial(); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index e9c3e2bb03..0a882a6bfa 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -58,6 +58,14 @@ use crate::sidewidget::{self, SideDrag}; use crate::typewidget; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; +/// The release of the widget drag `d`: released away from the last press or drag (`away`), it is +/// dragged there first (`drag`); then it ends (`finish`). +fn released(mut d: D, away: bool, drag: impl FnOnce(&mut D) -> Vec, finish: impl FnOnce(D) -> Vec) -> Vec { + let mut out = if away { drag(&mut d) } else { vec![] }; + out.extend(finish(d)); + out +} + /// Direction is read on screen, even in a turned view. Within three pixels of the press's /// horizontal position, retain the previous rule so hand jitter does not flip it. fn marquee_direction(cx: &ToolContext, start: Point, cur: Point, previous: bool) -> bool { @@ -199,6 +207,9 @@ pub struct SelectionTool { loaded_at_press: Option<(NodeId, bool)>, /// Where the pointer last hovered: the type on a path bracket under it draws thicker. bracket_hover: Option, + /// Where the pointer was at the last press or drag: a widget drag released anywhere else is + /// dragged there before it ends. + held_at: Option, } /// What Distance Guides measure the selection to. @@ -905,15 +916,32 @@ impl Tool for SelectionTool { out } - /// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a - /// polygon's side widget cancels it, as Escape does: its value goes back. + /// Switching tools during a drag of a widget (a blend, corner, pie or side widget, an Objects on + /// Path widget, a bracket of type on a path, a repeat's control or a 9-slice guide) cancels it, + /// as Escape does: its value goes back. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { match std::mem::take(&mut self.state) { State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], State::Corner(c) if c.adjusting() => vec![Action::Cancel], State::Pie(d) if d.adjusting() => vec![Action::Cancel], + State::RotateAll(d) if d.adjusting() => vec![Action::Cancel], + State::Space(d) if d.adjusting() => vec![Action::Cancel], + State::MoveAll(d) if d.adjusting() => vec![Action::Cancel], + State::Member(d) if d.adjusting() => vec![Action::Cancel], + State::Bracket(b) if b.adjusting() => vec![Action::Cancel], State::Sides(d) => d.cancel(), - State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], + State::Mirror(d) => d.cancel(), + State::GridRepeat(d) => d.cancel(), + State::RadialRepeat(d) => d.cancel(), + State::NineSlice(d) => d.cancel(), + State::BlendWidget(_) + | State::Corner(_) + | State::Pie(_) + | State::RotateAll(_) + | State::Space(_) + | State::MoveAll(_) + | State::Member(_) + | State::Bracket(_) => vec![], other => { self.state = other; vec![] @@ -978,6 +1006,10 @@ impl Tool for SelectionTool { /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); + let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos); + if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { + self.held_at = Some(ev.pos); + } let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); self.alt_hover = hovering && ev.mods.alt; @@ -988,7 +1020,7 @@ impl Tool for SelectionTool { return out; } // The edited symbol's 9-slice guides take precedence over every other control and the art. - if let Some(out) = self.nine_slice_guides(cx, ev) { + if let Some(out) = self.nine_slice_guides(cx, ev, released_away) { return out; } // Mirror and grid repeat controls take precedence over art and ruler guides; the mirror @@ -1129,7 +1161,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Corner(c)) => { self.state = State::Idle; - c.finish() + released(c, released_away, |c| c.drag(cx, p), CornerDrag::finish) } (PointerKind::Drag, State::Pie(mut d)) => { let out = d.drag(cx, p); @@ -1138,7 +1170,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Pie(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), PieDrag::finish) } (PointerKind::Drag, State::Sides(mut d)) => { let out = d.drag(cx, p); @@ -1156,7 +1188,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::BlendWidget(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), BlendWidgetDrag::finish) } (PointerKind::Drag, State::RotateAll(mut d)) => { let out = d.drag(cx, p, m.shift); @@ -1165,7 +1197,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::RotateAll(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p, m.shift), RotateAllDrag::finish) } (PointerKind::Drag, State::Space(mut d)) => { let out = d.drag(cx, p, m.alt); @@ -1174,7 +1206,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Space(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p, m.alt), SpaceDrag::finish) } (PointerKind::Drag, State::MoveAll(mut d)) => { let out = d.drag(cx, p); @@ -1183,7 +1215,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::MoveAll(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), MoveAllDrag::finish) } (PointerKind::Drag, State::Member(mut d)) => { let out = d.drag(cx, p); @@ -1192,7 +1224,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Member(d)) => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, p), MemberDrag::finish) } (PointerKind::Drag, State::Bracket(mut b)) => { let out = b.drag(cx, p, m.cmd); @@ -1201,7 +1233,7 @@ impl Tool for SelectionTool { } (PointerKind::Up, State::Bracket(b)) => { self.state = State::Idle; - b.finish() + released(b, released_away, |b| b.drag(cx, p, m.cmd), BracketDrag::finish) } (PointerKind::Up, State::Moving { began, deselect, key, exclude, .. }) => { self.release_move(cx, ev.backquote, began, deselect, key, exclude) @@ -1589,8 +1621,8 @@ impl SelectionTool { } /// A press on a 9-slice guide of the edited symbol starts dragging it; the drag and the - /// release go to it. - fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + /// release go to it, and a release away from the last drag (`released_away`) moves it there. + fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent, released_away: bool) -> Option> { if let State::NineSlice(mut d) = self.state.clone() { return Some(match ev.kind { PointerKind::Drag => { @@ -1600,7 +1632,7 @@ impl SelectionTool { } PointerKind::Up => { self.state = State::Idle; - d.finish() + released(d, released_away, |d| d.drag(cx, ev.pos), crate::nineslice::GuideDrag::finish) } _ => vec![], }); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 5c52201a6f..ecc2297d67 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -448,6 +448,28 @@ fn escape_cancels_a_bracket_drag() { assert!(t.pointer(&cx, &ev(PointerKind::Up, 330.0, 290.0)).is_empty(), "the release commits nothing"); } +/// A bracket drag of type on a path reads where it is released, and a tool switch cancels it. +#[test] +fn a_bracket_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (d, id) = crate::testutil::doc_with_path_type(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&cx, Point::new(280.0, 290.0), Point::new(320.0, 290.0), Point::new(340.0, 290.0)); +} + +/// A corner widget drag reads where it is released, and a tool switch cancels it. +#[test] +fn a_corner_widget_drag_reads_its_release_and_a_tool_switch_cancels_it() { + let (d, id) = doc_with_live_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + check_widget_release_and_tool_switch(&cx, Point::new(190.0, 191.0), Point::new(175.0, 176.0), Point::new(165.0, 166.0)); +} + /// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a /// press there grabs the object by that point. #[test] From fb0a82b09579ba48cfef2bf214eaeb605ce8380f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:44:10 -0800 Subject: [PATCH 006/126] Distort: keep blend steps, saved corners, previews and deep masks right - A blend step whose interpolated corners and nearer key's corners both fail the check is placed as the nearer key is. - Corners an image can't take are dropped when a file is read, so a later transform does not make them its distortion. - The .ai editing data writes a distorted image at any nesting depth, as it does a gradient mesh, so an opacity mask at the limit keeps it. - A linked image's preview keeps the clipping path its file keeps, so a document reopened from its preview still knows the file's clip group and Update Links replaces it instead of nesting a new one. - Docs: `corners` in the plugin API covers only corners that are not a parallelogram; Relink's warning for distorted images needs `preserve`. --- crates/doc/src/blend.rs | 23 +++++- crates/doc/src/image_quad.rs | 5 ++ crates/doc/src/node/wire.rs | 4 +- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/load.rs | 14 ++++ crates/engine/src/cmd/fileio/tests_psdread.rs | 79 +++++++++++++++++-- crates/engine/src/cmd/links.rs | 14 ++-- crates/eps/src/ai_editing/tests.rs | 51 ++++++++++++ crates/eps/src/ai_editing/writer.rs | 5 +- crates/pdf/src/tests/compression.rs | 26 ++++++ docs/mcp.md | 3 +- docs/plugins.md | 7 +- 12 files changed, 208 insertions(+), 25 deletions(-) diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 17b13b139e..45610c6983 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1161,9 +1161,15 @@ impl Lerp { && let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners()) { let near = if t < 0.5 { qa } else { qb }; - if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() { - // The nearer key's corners passed the same check when it was distorted. - let _ = n.set_image_corners(near); + if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() && n.set_image_corners(near).is_err() { + // Corners from a transform that collapses the image fail the check too: the + // step is then placed as the nearer key is. + if let (NodeKind::Image(o), NodeKind::Image(k)) = (&mut n.kind, &base.kind) { + o.xf = k.xf; + } + if n.extras().image_quad != base.extras().image_quad { + n.extras_mut().image_quad = base.extras().image_quad.clone(); + } } } n.extras_mut().mask = None; @@ -2342,6 +2348,17 @@ mod tests { let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap(); assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}"); } + // Toward an image whose transform has no height, neither the step's corners nor the + // nearer key's pass the check: the step is placed as that key is. + let mut flat = image([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let collapsed = Affine::new([-3.0, 0.0, 0.0, 0.0, 100.0, 0.0]); + if let NodeKind::Image(im) = &mut flat.kind { + im.xf = collapsed; + } + let step = Lerp::new(&a, &flat, (None, None)).at(0.5); + let NodeKind::Image(im) = &step.kind else { panic!("an image") }; + assert_eq!(im.xf, collapsed); + assert!(!step.is_distorted_image() && step.extras().image_quad.is_none()); } fn key(x: f64) -> Arc { diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index 9d374ff664..613bc2e750 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -367,6 +367,11 @@ mod tests { assert_eq!(n.image_quad(), None); assert!(distorted_art(&n).is_none()); assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)))); + // Reading the file drops it, so a later transform can't make it a distortion. + let mut back: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap(); + assert!(back.extras().image_quad.is_none()); + back.transform(Affine::scale_non_uniform(1e6, 1.0), false); + assert!(!back.is_distorted_image()); } #[test] diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 932b9563f7..bb8850a230 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -293,7 +293,9 @@ impl From for Node { color_mask: w.color_mask, warp_piece: w.warp_piece, clip_pieces: w.clip_pieces, - image_quad: w.image_quad, + // Corners the image can't take are dropped as they are read: it is placed by its + // transform, and no later transform makes them its distortion. + image_quad: w.image_quad.filter(|q| matches!(&w.kind, NodeKind::Image(im) if crate::image_quad::check_for(im, q).is_ok())), }; Node { id: w.id, diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index cd6ec30f0d..fb1200cf04 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, preview_with_clip, size_note}; mod heifread; mod hpgl; mod jp2read; diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 8249fe6b71..9150039596 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -1214,6 +1214,20 @@ pub(crate) fn image_clip(blob: &ImageBlob) -> Option vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) } +/// `blob` with its preview keeping the clipping path its PNG or TIFF keeps ([`image_clip`]), in a +/// text chunk of the preview PNG as [`png_with_clip`] writes it: a document saved without its +/// linked files holds the preview alone, and the Links commands then still know a clip group of +/// that path as the file's. Unchanged without a preview or a clipping path. +pub(crate) fn preview_with_clip(mut blob: ImageBlob) -> ImageBlob { + let Some(proxy) = blob.proxy.clone().filter(|p| !std::sync::Arc::ptr_eq(p, &blob.bytes) && png_clip(p).is_none()) else { return blob }; + let Some(json) = image_clip(&blob).and_then(|clip| serde_json::to_string(&clip).ok()).filter(|j| j.len() <= MAX_PNG_CLIP) else { + return blob; + }; + let png = vectorcraft_render::encode::png::with_text(proxy.to_vec(), &[(CLIP_KEYWORD, json.into())]); + blob.proxy = Some(std::sync::Arc::new(png)); + blob +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 0bd5058a7b..7a56932aed 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -684,15 +684,68 @@ fn update_links_follows_the_clipping_path_of_a_distorted_psd() { assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// A document saved without its linked files keeps a linked PSD file's image as a preview, smaller +/// than the file. Reopened after the file's clipping path changed, Update Links still knows the +/// clip group of the old clipping path as the file's and gives it the new one, for an image changed +/// by Perspective Distort or Free Distort and for one that is not. +#[test] +fn update_links_after_reopening_from_the_preview_replaces_the_files_clipping_path() { + let big = |resources: &[u8]| psd(1, 3, (400, 200), 8, 3, &[], resources, &[], &raw(&[&[255; 80000], &[0; 80000], &[0; 80000]])); + for distorted in [false, true] { + let dir = vectorcraft_testkit::TempDir::new(if distorted { "psd-preview-distorted" } else { "psd-preview" }); + let cut = write_file(&dir, "cut.psd", &big(&triangle_resources())); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [200, 100]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if distorted { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [400, 30], [360, 200], [20, 180]]})).unwrap(); + } + let node = |s: &Session| s.doc().unwrap().doc.node(image).unwrap().clone(); + let corners = node(&s).image_corners().unwrap(); + let doc_path = dir.join("poster.vectorcraft").to_string_lossy().into_owned(); + s.execute("document.save", &json!({"path": doc_path})).unwrap(); + std::fs::write(&cut, big(&square_resources())).unwrap(); + s.execute("document.open", &json!({"path": doc_path})).unwrap(); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(d.images[&im.key].is_proxy(), "the saved preview shows"); + let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); + assert_eq!(r["updated"], json!([image.0]), "{r}"); + let map = node(&s).image_map().unwrap(); + let squared: Vec<[f64; 2]> = [[100.0, 50.0], [300.0, 50.0], [300.0, 150.0], [100.0, 150.0]] + .iter() + .map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()) + .map(|p| [p.x, p.y]) + .collect(); + let (anchors, even_odd, held) = clip_group(&s.doc().unwrap().doc, group); + let near = + anchors.len() == squared.len() && anchors.iter().zip(&squared).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && even_odd && held == image, "distorted: {distorted}: {anchors:?} vs {squared:?}"); + assert_eq!(node(&s).image_corners().unwrap(), corners); + } +} + /// Unembed of a distorted image from a PSD file, with a path and with a folder, keeps the clip /// group of the clipping path that file names, drawn through its corners, and so does relinking it -/// to the file written. +/// to the file written. Update Links reads the clipping path the file on disk keeps then, and all +/// four corners stay where they were. #[test] fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { let dir = vectorcraft_testkit::TempDir::new("psd-unembed-distorted-clip"); // An RGB file is kept as a PNG, a CMYK one as a TIFF. - let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); - let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; + let cmyk = |resources: &[u8]| psd(1, 4, (100, 50), 8, 4, &[], resources, &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); + let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk(&triangle_resources()))]; + // The file Unembed writes, as stored, for the same kind of file clipped to the square. + let squared_file = |kind: &str| { + let file = if kind == "rgb" { red_psd(&square_resources()) } else { cmyk(&square_resources()) }; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "square.psd", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap(); + let r = s.execute("links.unembed", &json!({"id": r["image"]})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() + }; for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) { let data = vectorcraft_format::base64_encode(file); let mut s = Session::new(); @@ -702,6 +755,7 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); let before = clip_group(&s.doc().unwrap().doc, group); + let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap(); // Without an extension the image is written in the format it is stored in. let path = if folder { let out = dir.join(format!("folder-{kind}")); @@ -715,22 +769,31 @@ fn unembed_keeps_the_clipping_path_of_a_distorted_psd() { let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); for step in ["unembed", "relink", "update"] { + let mut want = before.0.clone(); if step == "relink" { s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); } if step == "update" { + // The file on disk now keeps the square: Update Links reads it from there. + std::fs::write(&path, squared_file(kind)).unwrap(); let r = s.execute("links.update", &json!({"ids": [image.0]})).unwrap(); assert_eq!(r["updated"], json!([image.0]), "{kind}: {r}"); + let map = s.doc().unwrap().doc.node(image).unwrap().image_map().unwrap(); + want = [[25.0, 12.5], [75.0, 12.5], [75.0, 37.5], [25.0, 37.5]] + .iter() + .map(|[x, y]| map.apply(vectorcraft_geom::Point::new(*x, *y)).unwrap()) + .map(|p| [p.x, p.y]) + .collect(); } let d = &s.doc().unwrap().doc; let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; assert!(im.link.is_some(), "linked to the file written"); - assert!(d.node(image).unwrap().is_distorted_image()); - // The clipping path is drawn through the corners again, within rounding. + assert_eq!(d.node(image).unwrap().image_corners().unwrap(), corners, "{kind}, {step}, folder: {folder}"); + // The clipping path is drawn through the corners, within rounding. let (anchors, even_odd, held) = clip_group(d, group); - let near = anchors.len() == before.0.len() - && anchors.iter().zip(&before.0).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); - assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {:?}", before.0); + let near = + anchors.len() == want.len() && anchors.iter().zip(&want).all(|(p, q)| (p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6); + assert!(near && (even_odd, held) == (before.1, before.2), "{kind}, {step}, folder: {folder}: {anchors:?} vs {want:?}"); } } // A path that converts the image writes a file without the clipping path: the clip group diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9c4f9ea6a5..9d0a0bbcb3 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -72,7 +72,7 @@ pub fn specs() -> Vec { "Relink", [], None, - "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and one naming the distorted images that preserve was not applied to)}", + "{ids?: [image or placed document ids] (default: the selected ones; with folder and nothing selected, every missing link), path | folder, scope?: selected (default: ids) | all (ids and every other object linked to the same file as one of them, in the layers, opacity-mask art, symbols, graph designs, patterns and the art of stored brushes) | missingInFolder (with path: ids, then every other missing link whose file name is in path's folder, each to the file of its name there; names not there are in notFound; with copy, only images are looked for) | each (with paths), paths?: [{ids, path}] (with scope each, in place of ids, path and folder: each link to its own file; an id in two entries is an error), copy?: false (with path or paths, for images of a saved document: copy the file into the document's folder and link to the copy; the names Name.png, Name 2.png … Name 99.png are tried in turn until one is free, which gets the copy, or is a file with the same contents, which is used; an error for a DCS file that reads plate files of its own), preserve?: transforms|bounds|fileDimensions|fit|fill (how the new file takes each image's place this time, as links.placementOptions describes; default: each image's Placement Options; fit keeps the new file's aspect ratio inside the old bounds: Replace)} link images (or placed documents, each showing the same artboard or page of the new file) to the file at path, or each to the file of its link's name in folder; embedded images become linked; each keeps its bounds. An image changed by Perspective Distort or Free Distort keeps its corners, with the new file's pixels between them, whatever preserve or its Placement Options say, and its clipping is handled as links.update handles it. One undo step → {relinked: [ids], notFound: [file names], copied?: [{from, to}], kept?: [{from, to}] (with copy; to is the file name alone when the document's folder is outside the automation read roots), warnings?: (as links.update's, and, when preserve is given, one naming the distorted images it was not applied to)}", has_doc, relink ), @@ -609,13 +609,14 @@ pub(crate) fn kept_unread(bytes: &[u8]) -> bool { /// `blob`, an image [`fileio::raster_image`] read from a file, ready to keep. When `unread` (the /// file is one [`kept_unread`] names), its pixels are decoded once to check that they can be read, /// and a `linked` image's preview is made from that decode ([`ImageBlob::checked_with_proxy`]); -/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). An error when the -/// pixels can't be read. +/// otherwise a `linked` image gets its preview ([`ImageBlob::with_proxy`]). The preview keeps the +/// clipping path the image keeps ([`fileio::preview_with_clip`]). An error when the pixels can't +/// be read. pub(crate) fn readable(blob: ImageBlob, unread: bool, linked: bool) -> Result { if !unread { - return Ok(if linked { blob.with_proxy() } else { blob }); + return Ok(if linked { fileio::preview_with_clip(blob.with_proxy()) } else { blob }); } - blob.checked_with_proxy(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into())) + blob.checked_with_proxy(linked).map(fileio::preview_with_clip).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into())) } /// [`readable`], and the pixels it decoded are kept in the image store the renderers share @@ -626,6 +627,7 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> return readable(blob, unread, linked); } let (blob, pixels) = blob.checked_with_pixels(linked).ok_or_else(|| EngineError::Other("the image's pixels can't be read".into()))?; + let blob = fileio::preview_with_clip(blob); if let Some(pixels) = pixels { vectorcraft_render::keep_decoded_image(&blob, pixels); } @@ -1668,7 +1670,7 @@ fn resolve_links(d: &mut Document, base: LinkBase, update: bool, low_res_proxy_e store_image(d, &g.key, blob, true); } else if let Some(b) = d.images.get(&g.key).filter(|b| b.proxy.is_none()) { // Linked before links kept a preview. - let b = b.clone().with_proxy(); + let b = fileio::preview_with_clip(b.clone().with_proxy()); d.images.insert(g.key.clone(), b); } // Found away from its path, or read again: the link follows. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3c2b229e1f..42c5dacb44 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -9288,6 +9288,57 @@ fn a_masked_copy_nested_too_deep_for_its_mask_keeps_all_of_its_pixels() { assert!(whole >= 2, "the first copy and a copy whose mask is left out: {sizes:?}"); } +/// A distorted image in the art of an opacity mask written at the deepest level a mask takes is +/// written as its pieces, as an undistorted image there is written whole: the mask keeps its art. +#[test] +fn a_distorted_image_in_a_mask_at_the_nesting_limit_keeps_its_pixels() { + // GUARDS: the distorted image was written there as an empty group, so the mask hid the object. + let masks = |distorted: bool| { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut masked = speckled_photo(&mut doc); + let mut art = speckled_photo(&mut doc); + if distorted { + let q = [(40.0, 10.0), (100.0, 10.0), (148.0, 138.0), (20.0, 138.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y)); + art.set_image_corners(q).unwrap(); + } + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(art), clip: false, invert: false, disabled: false, linked: true })); + doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(masked) }); + // Each isolated instance is written as its art, a level deeper: the masked object's mask + // art is at the limit. + for i in 1..writer::MAX_NEST - 1 { + let mut inner = instance(&mut doc, &format!("S{}", i - 1), Affine::IDENTITY); + inner.isolate = true; + doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) }); + } + let mut outer = instance(&mut doc, &format!("S{}", writer::MAX_NEST - 2), Affine::IDENTITY); + outer.isolate = true; + doc.insert(Some(layer), usize::MAX, outer).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(!out.warnings.iter().any(|w| w == writer::DEEP_MASKS), "{:?}", out.warnings); + // Each mask read back, by whether its art holds an image. + let back = read_back(&doc); + let mut found = vec![]; + let mut look = |n: &Node| { + if let Some(m) = n.extras().mask.as_ref() { + let mut image = false; + m.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_))); + found.push(image); + } + }; + for l in &back.layers { + l.walk(&mut look); + } + for s in &back.symbols { + s.art.walk(&mut look); + } + found + }; + let (plain, distorted) = (masks(false), masks(true)); + assert!(!plain.is_empty() && plain.iter().all(|i| *i), "{plain:?}"); + assert_eq!(distorted, plain); +} + /// [`warped_photo`] linked to `/Users/someone/Job/art/photo.png`, in folder `art` next to the /// document's. fn linked_warped_photo(doc: &mut Document, effects: Vec) -> Node { diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index d80c77c122..511f19a308 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -958,8 +958,9 @@ impl<'a> Writer<'a> { self.warn(w); } let moved = bounds && self.wrap_on_bounds(n, state); - // A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth. - if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) { + // A gradient mesh's drawn look is paths, and a distorted image's is clipped copies of its + // image, which hold nothing: they are written at any depth. + if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) || n.is_distorted_image() { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); self.nest += 1; self.drawn += 1; diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 74ca9191cc..8c0be940a7 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -182,6 +182,32 @@ fn a_distorted_image_is_written_with_its_corners_on_its_quad() { assert_eq!(seen, [true; 4]); } +/// A distorted image's own fill that Convert to Shape gives a shape is written with it. +#[test] +fn a_distorted_image_keeps_its_own_shaped_fill() { + use vectorcraft_doc::{AppearanceItem, Effect, FillLayer, color::Color, color::Paint}; + let mut d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y)); + let n = d.node_mut(id).unwrap(); + n.set_image_corners(q).unwrap(); + let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0))); + fill.effects = vec![Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true }]; + n.appearance.items.push(AppearanceItem::Fill(fill)); + let bytes = export_with_report(&d, &PdfOptions::default()).unwrap().bytes; + let back = crate::import(&bytes).unwrap(); + let (mut green, mut pieces) = (false, 0); + back.walk(|n| match &n.kind { + NodeKind::Image(_) => pieces += 1, + NodeKind::Path { .. } => { + green |= n.appearance.fill().and_then(|f| f.paint.color()).is_some_and(|c| c.to_rgb()[1] > 0.9 && c.to_rgb()[0] < 0.1) + } + _ => {} + }); + assert!(pieces > 2, "{pieces}"); + assert!(green, "the fill is written"); +} + #[test] fn jpeg_zip_and_automatic_compression() { let png = doc(encoded(colour(), ImageFormat::Png), "image/png"); diff --git a/docs/mcp.md b/docs/mcp.md index b72d8f660a..2a177704cc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6951,7 +6951,8 @@ Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.mak (`object.createObjectMosaic`), Create Gradient Mesh (`object.mesh.create`) and Place with Replace (`file.place` with `replace`) refuse a distorted image with an error that names the distortion. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or -Relink's `preserve`; Relink then adds a `warnings` entry naming those images. The clipping path a PSD, PSB or DCS +Relink's `preserve`. When `preserve` is given, Relink adds a `warnings` entry naming those images; without it, Relink +adds none for them. The clipping path a PSD, PSB or DCS file names is drawn through the corners: the clip group of the old file's clipping path gets the new file's clipping path, or becomes a plain group when the new file names none. Embed (`links.embed`) and Unembed (`links.unembed`) keep the corners, each in one undo step. Unembed of a distorted image from a PSD or PSB file, written as stored (PNG, or diff --git a/docs/plugins.md b/docs/plugins.md index 92e5ae47db..5f7eb3338a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -678,9 +678,10 @@ every attribute: of JSON: type whose runs and paragraphs don't fit what the type before it in paint order left comes with `truncated: true` too. - An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or - `"unknown"`, read from the image itself. An image changed by Perspective Distort or Free Distort also has `corners`, - its pixel rectangle's corners on the page (top left, top right, bottom right, bottom left), and its `transform` is the - affine placement that matches it at its middle. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 + `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape + other than a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right, bottom + right, bottom left), and its `transform` is the affine placement that matches it at its middle. Corners that make a + parallelogram are described by `transform` alone. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 pixels fit) has them in `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top, and `pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile, as sRGB. The pixels of all the images in one input take at most 16 MiB in base64, and an image the host starts to decode takes its size From ac8cdf071defffff436b5c04bbc5778dfbe5e584 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:00:12 -0800 Subject: [PATCH 007/126] Preflight: measure a distorted image's resolution as Image Info does Production Preflight measured a distorted image's effective resolution from its transform alone, so an image enlarged by Perspective Distort or Free Distort could pass the minimum. It now measures it at its middle, with the placement Image Info reports. --- crates/engine/src/cmd/preflight.rs | 4 +++- crates/engine/tests/preflight.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs index ebfaf5deeb..a564b29335 100644 --- a/crates/engine/src/cmd/preflight.rs +++ b/crates/engine/src/cmd/preflight.rs @@ -89,11 +89,13 @@ fn check(s: &mut Session, p: &Value) -> Result { continue; }; let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n)); + // A distorted image is measured at its middle, as Link Info measures it. + let xf = doc.node(source).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf); let ppi = context .pages .iter() .filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0)) - .map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf)) + .map(|(_, to_page)| super::place::effective_ppi(*to_page * xf)) .reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]); let Some(ppi) = ppi else { resolution_unchecked += 1; diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/preflight.rs index 08b7cf153b..e656596d71 100644 --- a/crates/engine/tests/preflight.rs +++ b/crates/engine/tests/preflight.rs @@ -112,6 +112,26 @@ fn preflight_resolution_follows_placed_size_and_both_axes() { assert!(codes(&screen).is_empty(), "{screen}"); } +/// A distorted image's resolution is measured at its middle, as Image Info measures it. +#[test] +fn preflight_resolution_of_a_distorted_image_is_image_infos() { + let dir = Folder::new("preflight-resolution-distorted"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone(); + s.execute("select.set", &json!({ "ids": [id] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap(); + assert!(codes(&s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap()).is_empty()); + // The top stays 24 pt wide; the bottom is 120 pt wide. + s.execute("object.distort", &json!({ "corners": [[188, 188], [212, 188], [260, 212], [140, 212]] })).unwrap(); + assert!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().is_distorted_image()); + let info = s.execute("image.info", &json!({ "id": id })).unwrap(); + let r = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap(); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").expect("a low resolution finding"); + assert_eq!(f["effectivePpi"], info["ppi"], "{info}"); +} + #[test] fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() { let dir = Folder::new("preflight-resolution-boundary"); From 67fa32374d7fb90a400c731604d66bf66c48077a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 20:24:23 -0800 Subject: [PATCH 008/126] Retype: near matches within a tolerance, and words outlined as one compound path type.retype takes a tolerance (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, with its contours paired with the glyph's by length. It becomes the closest glyph when the leftover distance, relative to the shape's size, is at most the tolerance, and the glyph's outline and the shape's each lie within three times the tolerance of the other. Simplified outlines, curves split in two and contours in another order or direction match this way. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph is a near match. Each entry of fonts in the result has a score from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours, a contour with the contours inside it, and matched in runs of up to three groups, longest first among those that leave the rest matchable, so an i's stem and dot become one i. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The compound becomes type only when every glyph matches; otherwise it stays and is reported once. Exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. A compound path of more than 256 groups or 512 contours is matched whole only, and so are the shapes after the first 16,384 contours one command groups. Near matching compares a shape with at most 256 glyphs, in at most 50 million point comparisons per shape and 2 billion per command, and looks glyphs up for at most 1,024 distinct shapes and runs per command, whole shapes first. At most 262,144 glyphs are drawn to check and 32,768 indexed for near matching, shared equally among the faces; a face's glyphs closest to the selected shapes are indexed first. The tolerance, the score and the splitting rules are VectorCraft's own. Part of #4934 --- crates/engine/src/cmd/retype.rs | 325 ++++++++-- crates/engine/src/cmd/retype_tests.rs | 473 ++++++++++++++ crates/text/src/retype.rs | 899 ++++++++++++++++++++++++-- docs/gaps.md | 2 +- docs/mcp.md | 31 +- docs/target-app-parity.md | 6 +- docs/type-parity.md | 2 +- 7 files changed, 1655 insertions(+), 83 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index cb548bd46e..253edcd3a3 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -11,8 +11,14 @@ //! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched //! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object //! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as -//! they are and are reported. Near matches (another version of the font, simplified outlines, -//! merged glyphs) and images are phase 2. +//! they are and are reported. +//! +//! With a `tolerance`, a shape that matches no glyph exactly may still nearly match one: another +//! version of the font, or the outline simplified or built another way +//! ([`RetypeIndex::near_matches`]); each line reports how closely its glyphs fit. A compound path +//! holding several glyphs (a word outlined as one path) is split into its glyphs +//! ([`vectorcraft_text::retype::clusters`]), and becomes type only when every one of them does. +//! The tolerance, the score and the splitting rules are VectorCraft's own. Images are phase 2. use std::f64::consts::{PI, TAU}; use std::sync::Arc; @@ -39,7 +45,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's size, is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions; with a tolerance, within it); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -180,6 +186,9 @@ struct Line { parent: Option, opacity: f32, blend: vectorcraft_color::BlendMode, + /// The tolerance near matches were taken with (0: exact only): a near-matched glyph may differ + /// that much in size, turn and place from the rest of its line ([`Self::slack_for`]). + slack: f64, } impl Line { @@ -187,6 +196,12 @@ impl Line { Vec2::new(self.angle.cos(), self.angle.sin()) } + /// The slack glyph `m` of this line is allowed: [`Self::slack`] when `m` or the line's first + /// glyph, whose size and turn the line takes, is a near match, else 0. + fn slack_for(&self, m: &GlyphMatch) -> f64 { + if m.exact && self.matches.first().is_none_or(|f| f.exact) { 0.0 } else { self.slack } + } + /// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same /// font, size and turn, on its baseline, after its end)? fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool { @@ -194,15 +209,16 @@ impl Line { let d = m.origin - self.origin; let dir = self.dir(); let across = d.cross(dir).abs(); + let slack = self.slack_for(m); pc.parent == self.parent && pc.appearance == self.appearance && pc.opacity == self.opacity && pc.blend == self.blend && m.face.id() == self.face.id() // One size and turn for the whole line: the type sets every glyph at the first one's. - && (m.scale - self.scale).abs() <= self.scale * 1e-4 + && (m.scale - self.scale).abs() <= self.scale * slack.max(1e-4) // Wrapped: type turned 180° has angles near +π and −π. - && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < slack.max(1e-5) && across < size * 0.05 && (m.origin - self.end).dot(dir) > -size * 0.25 } @@ -241,6 +257,7 @@ impl Line { parent: self.parent, opacity: self.opacity, blend: self.blend, + slack: self.slack, }; for (id, m) in ids.iter().zip(ms).skip(1) { l.push(*id, m); @@ -287,9 +304,9 @@ impl Line { fn first_mismatch(&self, t: &TextObject) -> Option { let lay = vectorcraft_text::layout(FontDb::global(), t); let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); - let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01); for (k, m) in self.matches.iter().enumerate() { let Some(g) = drawn.next() else { return Some(k) }; + let tol = (self.scale * self.face.units_per_em() * (0.01 + self.slack_for(m))).max(0.01); let at = t.xf * (g.xf * Point::ORIGIN); if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { return Some(k); @@ -419,11 +436,13 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { parent: l.parent, opacity: l.opacity, blend: l.blend, + slack: l.slack, } } -/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). -fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`), +/// with near matches taken at tolerance `slack`. +fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option { let m = cands.first()?; let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Some(Line { @@ -440,9 +459,183 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { parent: pc.parent, opacity: pc.opacity, blend: pc.blend, + slack, }) } +/// The lines, by index, to drop so that no shape of several glyphs becomes type in part: each line +/// is given by the shapes it sets, one per glyph, and `glyphs_of` says how many glyphs a shape +/// is. A line setting a glyph of a shape not all of whose glyphs are set goes, and then so do the +/// lines setting the other glyphs of the shapes it held. +fn partial_lines(lines: &[Vec], glyphs_of: &std::collections::HashMap) -> std::collections::HashSet { + let mut dropped = std::collections::HashSet::new(); + loop { + let mut set: std::collections::HashMap = std::collections::HashMap::new(); + for (_, l) in lines.iter().enumerate().filter(|(i, _)| !dropped.contains(i)) { + for id in l { + *set.entry(*id).or_default() += 1; + } + } + let partial: std::collections::HashSet = + set.iter().filter(|(id, n)| glyphs_of.get(*id).is_some_and(|want| *n < want)).map(|(id, _)| *id).collect(); + let before = dropped.len(); + for (i, l) in lines.iter().enumerate() { + if l.iter().any(|id| partial.contains(id)) { + dropped.insert(i); + } + } + if dropped.len() == before { + return dropped; + } + } +} + +/// Glyph runs longer than this (in contour groups) are not tried when a shape is split. +const MAX_RUN: usize = 3; + +/// A shape of more contour groups than this is not split: it is matched whole only. +const MAX_SPLIT_GROUPS: usize = 256; + +/// A shape of more contours than this is not split either, and its contours are not grouped. +const MAX_SPLIT_CONTOURS: usize = 512; + +/// Contours of all the selected shapes one command groups, at most: the shapes past them are +/// matched whole only. +const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384; + +/// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than +/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours, and for more contours than +/// `budget` holds. A path of two or more contours takes them from `budget` when it is grouped. +fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { + // Grouping compares every contour with every other: count them first. + let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); + if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget { + return vec![]; + } + *budget -= n; + let groups = vectorcraft_text::retype::clusters(path); + if (2..=MAX_SPLIT_GROUPS).contains(&groups.len()) { groups } else { vec![] } +} + +/// The parts of shape `path` to match: the whole shape, or, when it is no glyph and holds several +/// contour `groups` ([`split_groups`]), runs of up to [`MAX_RUN`] groups in order, the longest that matches first (an i before a dotless i and a dot) among the runs after +/// which the rest of the groups can still be matched. Each part with its candidates; empty when +/// the shape matches nothing and its groups cannot all be matched. `find(path, part, near)` gives +/// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make +/// Compound Path may have turned the other way round, and its `near` flag allows near matches. +/// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then +/// its groups nearly. +fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bool) -> Vec) -> Vec> { + let whole = find(path, false, false); + if !whole.is_empty() { + return vec![whole]; + } + let exact = split_parts(groups, &|run| find(run, true, false)); + if !exact.is_empty() { + return exact; + } + let whole = find(path, false, true); + if !whole.is_empty() { + return vec![whole]; + } + split_parts(groups, &|run| find(run, true, true)) +} + +/// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for +/// no groups and when the groups cannot all be matched. +fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec) -> Vec> { + if groups.is_empty() { + return vec![]; + } + let g = groups.len(); + // From the last group back: the run that starts at each group, the longest that matches and + // leaves a rest that can all be matched, with its candidates. Runs past such a start are + // never tried for one whose rest cannot be matched. + let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); + for i in (0..g).rev() { + for n in (1..=MAX_RUN.min(g - i)).rev() { + let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); + if !rest_ok { + continue; + } + let Some(run) = groups.get(i..i + n) else { continue }; + let cands = find(&joined(run)); + if !cands.is_empty() { + if let Some(c) = chosen.get_mut(i) { + *c = Some((n, cands)); + } + break; + } + } + } + let mut out = vec![]; + let mut i = 0; + while i < g { + let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; + out.push(cands); + i += n; + } + out +} + +/// Contour groups joined into one path. +fn joined(run: &[BezPath]) -> BezPath { + let mut p = BezPath::new(); + for g in run { + p.extend(g.iter()); + } + p +} + +/// Every run of contour `groups` ([`split_groups`]) [`parts`] may try. +fn runs(groups: &[BezPath]) -> Vec { + let mut out = vec![]; + for i in 0..groups.len() { + for n in 1..=MAX_RUN.min(groups.len() - i) { + if let Some(run) = groups.get(i..i + n) { + out.push(joined(run)); + } + } + } + out +} + +/// The keys the index looks glyphs up by for the `shapes` (each with its contour groups) and +/// every run of their groups: their exact [`shape_key`](vectorcraft_text::retype::shape_key)s and, +/// with a `tolerance` above 0, at most [`MAX_NEAR_KEYS`](vectorcraft_text::retype::MAX_NEAR_KEYS) +/// distinct [`near_key`](vectorcraft_text::retype::near_key)s: every whole shape's first, in the +/// order the shapes come, then the runs of their groups. Paths past that many near keys are not +/// looked up for near matches. +fn lookup_keys<'a>( + shapes: impl IntoIterator, + tolerance: f64, +) -> (std::collections::BTreeSet, Vec) { + use vectorcraft_text::retype::{MAX_NEAR_KEYS, near_key, shape_key}; + let mut wanted = std::collections::BTreeSet::new(); + let mut near_wanted = vec![]; + let mut add = |run: &BezPath| { + wanted.extend(shape_key(run)); + if tolerance > 0.0 + && near_wanted.len() < MAX_NEAR_KEYS + && let Some(k) = near_key(run) + && !near_wanted.contains(&k) + { + near_wanted.push(k); + } + }; + let shapes: Vec<(&BezPath, &[BezPath])> = shapes.into_iter().collect(); + // The whole shapes first, then the runs of their groups. + for (path, _) in &shapes { + add(path); + } + for (_, groups) in &shapes { + for run in runs(groups) { + add(&run); + } + } + (wanted, near_wanted) +} + fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; let fonts: Vec = match p.get("fonts") { @@ -452,6 +645,13 @@ fn retype(s: &mut Session, p: &Value) -> Result { } Some(_) => return Err(bad(C, "fonts must be a list of family names")), }; + let tolerance = match p.get("tolerance") { + None | Some(Value::Null) => 0.0, + Some(v) => match v.as_f64() { + Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, + _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), + }, + }; let roots = selected_roots(s)?; let db = FontDb::global(); let system_layout = s.doc()?.doc.setup.system_layout; @@ -478,17 +678,31 @@ fn retype(s: &mut Session, p: &Value) -> Result { if pieces.is_empty() { return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); } - // Only glyphs with a selected shape's key (segments per contour) can match one: the others are - // not sampled. - let wanted: std::collections::BTreeSet = - pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + // Only glyphs with a selected shape's key (segments per contour) can match one exactly, and + // only glyphs with as many contours and a close area-to-length ratio nearly: the others are + // not sampled. A shape of several glyphs is looked up by the runs of its groups too. + let mut budget = MAX_SPLIT_TOTAL_CONTOURS; + let groups: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { split_groups(&pc.path, &mut budget) }).collect(); + let (wanted, near_wanted) = + lookup_keys(pieces.iter().zip(&groups).filter(|(pc, _)| !pc.keeps_outline).map(|(pc, g)| (&pc.path, g.as_slice())), tolerance); // Nothing to match (every shape stays an outline): no font is read. - let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) }; - let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); + let index = if wanted.is_empty() && near_wanted.is_empty() { + RetypeIndex::default() + } else { + RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) + }; + // Exact matches first; near ones, when allowed, only for a path with none. + let find = |path: &BezPath, part: bool, near: bool| { + let exact = if part { index.matches_either_way(path) } else { index.all_matches(path) }; + if exact.is_empty() && near { index.near_matches(path, tolerance) } else { exact } + }; + // Each shape's parts (one, unless it holds several glyphs), each with its candidates. + let found: Vec>> = + pieces.iter().zip(&groups).map(|(pc, g)| if pc.keeps_outline { vec![] } else { parts(&pc.path, g, &find) }).collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; - for ms in &found { + for ms in found.iter().flatten() { // Each shape votes once for each face it fits. let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); faces.sort_unstable(); @@ -505,36 +719,42 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. let mut open = false; - for (pc, ms) in pieces.iter().zip(&found) { + // How many glyphs each shape is: a shape of several becomes type only when all of them do. + let mut glyphs_of: std::collections::HashMap = std::collections::HashMap::new(); + for (pc, parts) in pieces.iter().zip(&found) { if pc.after_barrier { open = false; } - // The shape's candidates in the face most shapes fit (the first such face, as the - // matches come upright and closest first). - let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); - let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); - if cands.is_empty() { + if parts.is_empty() { unmatched.push(pc.id); open = false; continue; } - let joined = match lines.last_mut() { - Some(l) if open => join(l, pc, &cands), - _ => false, - }; - if !joined { - lines.extend(new_line(pc, &cands)); + glyphs_of.insert(pc.id, parts.len()); + for ms in parts { + // The part's candidates in the face most shapes fit (the first such face, as the + // matches come upright and closest first). + let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + let joined = match lines.last_mut() { + Some(l) if open => join(l, pc, &cands), + _ => false, + }; + if !joined { + lines.extend(new_line(pc, &cands, tolerance)); + } + open = true; } - open = true; } // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn - // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is - // what was asked for. Lone means alone on its baseline as the outlines lie, before the - // layout check splits lines (tracking and manual kerning split them glyph by glyph). + // art (a dot, a bar): beside other shapes, the other glyphs of a split compound path + // included, it stays an outline. Selected on its own, it is what was asked for. Lone means + // alone on its baseline as the outlines lie, before the layout check splits lines (tracking + // and manual kerning split them glyph by glyph). let lone_pieces: std::collections::HashSet = lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); let mut lines = verified(lines, system_layout, &mut unmatched); - if pieces.len() > 1 { + if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) { lines.retain(|l| { let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); if lone { @@ -543,6 +763,20 @@ fn retype(s: &mut Session, p: &Value) -> Result { !lone }); } + let dropped = partial_lines(&lines.iter().map(|l| l.pieces.clone()).collect::>(), &glyphs_of); + let mut k = 0; + lines.retain(|l| { + let keep = !dropped.contains(&k); + k += 1; + if !keep { + unmatched.extend(l.pieces.iter().copied()); + } + keep + }); + // A shape of several glyphs is reported once, and not when it became type. + let kept: std::collections::HashSet = lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(); + let mut seen = std::collections::HashSet::new(); + unmatched.retain(|id| !kept.contains(id) && seen.insert(*id)); (lines, unmatched, truncated) }; if lines.is_empty() { @@ -551,6 +785,9 @@ fn retype(s: &mut Session, p: &Value) -> Result { let made = s.edit("Retype", |d, sel| { let mut ids = vec![]; let mut emptied = vec![]; + // Every line's type goes in before the shapes go: a shape of several glyphs is the first + // shape of more than one line. Each goes just before its first shape, so lines from one + // shape keep their order. for l in &lines { let Some(first) = l.pieces.first() else { continue }; let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; @@ -561,14 +798,18 @@ fn retype(s: &mut Session, p: &Value) -> Result { node.opacity = l.opacity; node.blend = l.blend; d.insert(par, idx, node)?; - for pc in &l.pieces { - if let Some((Some(parent), _, _)) = d.position(*pc) { - emptied.push(parent); - } - d.remove(*pc)?; - } ids.push(id); } + let mut removed = std::collections::HashSet::new(); + for pc in lines.iter().flat_map(|l| l.pieces.iter()) { + if !removed.insert(*pc) { + continue; + } + if let Some((Some(parent), _, _)) = d.position(*pc) { + emptied.push(parent); + } + d.remove(*pc)?; + } // A group left holding only the new type (Create Outlines' group) gives way to it, unless // the group has transparency, effects, a mask or a name of its own, which then keep // applying to the type inside it. A group left empty goes. @@ -611,7 +852,13 @@ fn retype(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": made.iter().map(|i| i.0).collect::>(), "texts": lines.iter().map(|l| l.text.clone()).collect::>(), - "fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::>(), + "fonts": lines + .iter() + .map(|l| { + let score = l.matches.iter().map(GlyphMatch::score).fold(1.0, f64::min); + json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em(), "score": (score * 1000.0).round() / 1000.0}) + }) + .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, })) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index d691ab34fa..5c043a9e6f 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -537,3 +537,476 @@ fn a_long_tracked_line_is_checked_in_time() { assert_eq!(r["unmatched"], json!([])); eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); } + +/// Every path in the document flattened into lines `tol` from its curves, each contour started at +/// its second point and run backwards: outlines simplified and built nothing like the font's. +fn simplify_every_path(s: &mut Session, tol: f64) { + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. }) { + ids.push(n.id); + } + }); + simplify_paths(s, &ids, tol); +} + +/// [`simplify_every_path`] for the paths `ids` only. +fn simplify_paths(s: &mut Session, ids: &[NodeId], tol: f64) { + s.edit("test", |d, _| { + for id in ids { + let data = d.node_mut(*id).unwrap().path_data_mut().unwrap(); + let mut contours: Vec> = vec![]; + kurbo::flatten(data.to_bezpath().iter(), tol, |el| match el { + kurbo::PathEl::MoveTo(q) => contours.push(vec![q]), + kurbo::PathEl::LineTo(q) => contours.last_mut().unwrap().push(q), + _ => {} + }); + let mut out = kurbo::BezPath::new(); + for mut c in contours { + if c.len() > 1 && c.first() == c.last() { + c.pop(); + } + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + *data = vectorcraft_geom::PathData::from_bezpath(&out); + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + simplify_every_path(&mut s, 0.05); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "no exact match: {e}"); + for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true)] { + let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); + assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}"); + } + assert!(s.doc().unwrap().doc == before, "nothing changes"); + let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap(); + assert_eq!(r["texts"], json!(["Rag"]), "{r}"); + assert_eq!(r["unmatched"], json!([])); + assert_eq!((r["fonts"][0]["family"].as_str(), r["fonts"][0]["style"].as_str()), (Some("Source Sans 3"), Some("Regular"))); + let score = r["fonts"][0]["score"].as_f64().unwrap(); + assert!(score > 0.5 && score < 1.0, "a near match scores below an exact one: {score}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(near(t.first_style().size, 40.0, 0.4), "size {}", t.first_style().size); + let o = t.xf.translation(); + assert!(near(o.x, 40.0, 0.4) && near(o.y, 100.0, 0.4), "baseline start {o:?}"); +} + +#[test] +fn exact_matches_score_one() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap(); + assert_eq!(r["texts"], json!(["Rag"]), "{r}"); + assert_eq!(r["fonts"][0]["score"], json!(1.0)); +} + +#[test] +fn exact_matches_with_a_small_leftover_still_score_one() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Rag", "size": 40})); + // Each glyph stretched 0.1% across its own centre: still within the exact matcher's reach, with + // a leftover distance above 0. + let mut ids = vec![]; + s.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. }) { + ids.push(n.id); + } + }); + s.edit("test", |d, _| { + for id in &ids { + let data = d.node_mut(*id).unwrap().path_data_mut().unwrap(); + let p = data.to_bezpath(); + let c = kurbo::Shape::bounding_box(&p).center(); + let xf = kurbo::Affine::translate(c.to_vec2()) * kurbo::Affine::scale_non_uniform(1.001, 1.0) * kurbo::Affine::translate(-c.to_vec2()); + *data = vectorcraft_geom::PathData::from_bezpath(&(xf * p)); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + // Each glyph's size now differs a little, so each is its own line. + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "Rag", "{r}"); + for f in r["fonts"].as_array().unwrap() { + assert_eq!(f["score"], json!(1.0), "{r}"); + } +} + +#[test] +fn exact_glyphs_of_another_size_are_another_line_even_with_a_tolerance() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tia", "size": 40})); + // The a (two contours, so not a lone one-contour glyph) made 4% larger about where it starts + // on the baseline: still exactly the glyph. + let a = *children_of(&s, g).last().unwrap(); + // The a's paths (a compound path's, or its own). + let paths: Vec = match s.doc().unwrap().doc.node(NodeId(a)).unwrap().children() { + Some(c) => c.iter().map(|c| c.id.0).collect(), + None => vec![a], + }; + s.edit("test", |d, _| { + let x0 = paths + .iter() + .map(|id| kurbo::Shape::bounding_box(&d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap().to_bezpath()).x0) + .fold(f64::INFINITY, f64::min); + let at = kurbo::Vec2::new(x0, 100.0); + let xf = kurbo::Affine::translate(at) * kurbo::Affine::scale(1.04) * kurbo::Affine::translate(-at); + for id in &paths { + let data = d.node_mut(NodeId(*id)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath())); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + assert_eq!(r["texts"], json!(["Ti", "a"]), "{r}"); + let sizes: Vec = r["fonts"].as_array().unwrap().iter().map(|f| f["size"].as_f64().unwrap()).collect(); + assert!(near(sizes[0], 40.0, 0.01) && near(sizes[1], 41.6, 0.01), "{sizes:?}"); + assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["score"] == json!(1.0)), "{r}"); +} + +#[test] +fn turned_near_matched_round_glyphs_keep_the_line_turn() { + // Round glyphs (o, O, the period) and glyphs that look alike half round (N, x, z) fit + // simplified outlines at more than one turn: each takes the turn of its line. + for (text, rotation) in [("no.", 90), ("no.", 180), ("zoo", 135), ("NOON", 180), ("xoxo", 200), ("on", 120)] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": text, "size": 40, "rotation": rotation})); + simplify_every_path(&mut s, 0.05); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.02})).unwrap(); + assert_eq!(r["texts"], json!([text]), "turned {rotation}: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + +#[test] +fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() { + // The m (one path) of simplified outlines moved along the baseline by `shift` of the font + // size (40), retyped with a tolerance of 0.03: it may sit 1% + 3% of the size from where the + // type draws it. + let run = |shift: f64| { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + simplify_every_path(&mut s, 0.05); + let m = *children_of(&s, g).last().unwrap(); + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * shift, 0.0)) * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.03})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), "Tim", "{r}"); + texts.len() + }; + assert_eq!(run(0.02), 1, "within the tolerance: one line"); + assert!(run(0.06) > 1, "past it: the line splits where the m was moved"); +} + +#[test] +fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + let m = *children_of(&s, g).last().unwrap(); + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + assert_eq!(r["texts"], json!(["Ti", "m"]), "exact glyphs keep the exact limits: {r}"); +} + +#[test] +fn an_exact_glyph_after_a_near_one_keeps_the_exact_limits() { + // T exact, o simplified (a near match), m exact moved by 3% of the size along the baseline. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tom", "size": 40})); + let kids = children_of(&s, g); + let o: Vec = match s.doc().unwrap().doc.node(NodeId(kids[1])).unwrap().children() { + Some(c) => c.iter().map(|c| c.id).collect(), + None => vec![NodeId(kids[1])], + }; + simplify_paths(&mut s, &o, 0.05); + let m = kids[2]; + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(kurbo::Affine::translate((40.0 * 0.03, 0.0)) * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + assert_eq!(r["texts"], json!(["To", "m"]), "the near o does not loosen the m's limits: {r}"); +} + +/// The outlines of `text` made into one compound path: the compound's id. +fn one_compound(s: &mut Session, text: &str) -> u64 { + let g = outlined(s, json!({"x": 40, "y": 100, "text": text, "size": 40})); + let glyphs = children_of(s, g); + s.execute("select.set", &json!({"ids": glyphs})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap() +} + +#[test] +fn a_word_outlined_as_one_compound_path_splits_into_its_glyphs() { + let mut s = session(); + let c = one_compound(&mut s, "Tim"); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Tim"]), "the i's stem and dot are one glyph: {r}"); + assert_eq!(r["unmatched"], json!([])); + assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type"); +} + +#[test] +fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { + let mut s = session(); + // An A and, far below it, a period, made into one compound path and selected alone: the + // period, alone on its baseline beside the A, is a dot as much as a period, so it stays an + // outline, and so does the A in the same compound. + let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40})); + let mut ids = children_of(&s, t); + ids.extend(children_of(&s, dot)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = match s.execute("type.retype", &json!({})) { + Ok(r) => panic!("the period became type: {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("(1 checked)"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn lines_from_one_compound_path_keep_their_order() { + let mut s = session(); + // Two lines of outlines made into one compound path. + let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + let low = outlined(&mut s, json!({"x": 40, "y": 220, "text": "Ham", "size": 40})); + let mut glyphs = children_of(&s, top); + glyphs.extend(children_of(&s, low)); + s.execute("select.set", &json!({"ids": glyphs})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(ids.len(), 2, "{r}"); + let texts: Vec = ids.iter().map(|id| text_of(&s, *id).plain_text()).collect(); + let d = &s.doc().unwrap().doc; + let at: Vec = ids.iter().map(|id| d.position(NodeId(*id)).unwrap().1).collect(); + // The lines stack in the order of the compound's contours: the first line behind the second. + let first = texts.iter().position(|t| t == "Tim").unwrap(); + let second = texts.iter().position(|t| t == "Ham").unwrap(); + assert!(at[first] < at[second], "{texts:?} at {at:?}"); +} + +#[test] +fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ti", "size": 40})); + let mut ids = children_of(&s, g); + // A shape no glyph is, beside the letters, in the same compound. + ids.push(s.execute("shape.star", &json!({"cx": 140, "cy": 85, "radius1": 12, "radius2": 5, "points": 7})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("(1 checked)"), "reported once: {e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { + let mut s = session(); + // An A (two contours), and far below it a period: a lone one-contour glyph beside other + // shapes stays an outline, so the A, in the same compound, must stay too. + let t = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let dot = outlined(&mut s, json!({"x": 40, "y": 300, "text": ".", "size": 40})); + let paths = |s: &Session, id: u64| match s.doc().unwrap().doc.node(NodeId(id)).unwrap().children() { + Some(c) => c.iter().map(|c| c.id.0).collect(), + None => vec![id], + }; + let mut ids: Vec = paths(&s, t); + ids.extend(paths(&s, dot)); + assert_eq!(ids.len(), 2, "one path each"); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c, r]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = match s.execute("type.retype", &json!({})) { + Ok(r) => panic!("the A became type without its period: {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("(2 checked)"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { + use kurbo::Shape; + // Three groups A, B and C side by side. A and B together are a glyph, but then C alone is + // none; A alone and B and C together are glyphs, so the split is A, BC. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 140) => vec!["AB"], + (true, 0, 40) => vec!["A"], + (true, 100, 240) => vec!["BC"], + _ => vec![], + } + }; + let groups = all_groups(&p); + assert_eq!(super::parts(&p, &groups, &find), vec![vec!["A"], vec!["BC"]]); + // With no way to match every group, nothing. + let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] } + }; + assert!(super::parts(&p, &groups, &none).is_empty()); +} + +/// `path`'s contour groups, with no limit on the contours grouped. +fn all_groups(path: &kurbo::BezPath) -> Vec { + let mut budget = usize::MAX; + super::split_groups(path, &mut budget) +} + +#[test] +fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { + use kurbo::Shape; + // Two groups side by side, each exactly a glyph (two periods), and the whole only nearly one + // (a dieresis): the parts win. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, near, b.x0.round() as i64, b.x1.round() as i64) { + (false, true, 0, 140) => vec!["dieresis"], + (true, _, 0, 40) | (true, _, 100, 140) => vec!["period"], + _ => vec![], + } + }; + let groups = all_groups(&p); + assert_eq!(super::parts(&p, &groups, &find), vec![vec!["period"], vec!["period"]]); + // When the parts match only nearly too, the whole near match comes first. + let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, near, b.x0.round() as i64, b.x1.round() as i64) { + (false, true, 0, 140) => vec!["dieresis"], + (true, true, 0, 40) | (true, true, 100, 140) => vec!["period"], + _ => vec![], + } + }; + assert_eq!(super::parts(&p, &groups, &near_only), vec![vec!["dieresis"]]); +} + +#[test] +fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() { + use std::collections::HashMap; + // Shapes 1 and 2 are two glyphs each, shape 3 one. Line 0 sets one glyph of 1 and one of 2; + // line 1 sets the other glyph of 2 and shape 3. Shape 1's other glyph is set nowhere. + let (a, b, c) = (NodeId(1), NodeId(2), NodeId(3)); + let glyphs_of: HashMap = [(a, 2), (b, 2), (c, 1)].into(); + let lines = vec![vec![a, b], vec![b, c]]; + let dropped = super::partial_lines(&lines, &glyphs_of); + assert!(dropped.contains(&0), "shape 1 is set only in part: {dropped:?}"); + assert!(dropped.contains(&1), "then shape 2 is too: {dropped:?}"); + // Every glyph set: nothing goes. + let whole = vec![vec![a, b], vec![a, b, c]]; + assert!(super::partial_lines(&whole, &glyphs_of).is_empty()); +} + +#[test] +fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() { + use kurbo::Shape; + use vectorcraft_text::retype::MAX_NEAR_KEYS; + // A compound path of `n` rectangles side by side, each of another width: every run of up to + // three of them has its own near key. + let row = |n: usize| { + let mut p = kurbo::BezPath::new(); + for i in 0..n { + let x = i as f64 * 100.0; + p.extend(kurbo::Rect::new(x, 0.0, x + 10.0 + i as f64 * 0.37, 40.0).path_elements(0.1)); + } + p + }; + // Each shape with its contour groups, as the command looks them up. + let with_groups = |shapes: &[kurbo::BezPath]| -> Vec<(kurbo::BezPath, Vec)> { + let mut budget = super::MAX_SPLIT_TOTAL_CONTOURS; + shapes.iter().map(|p| (p.clone(), super::split_groups(p, &mut budget))).collect() + }; + let keys_of = |shapes: &[(kurbo::BezPath, Vec)], tolerance: f64| { + super::lookup_keys(shapes.iter().map(|(p, g)| (p, g.as_slice())), tolerance) + }; + let few = with_groups(&[row(20)]); + assert_eq!(super::runs(&few[0].1).len(), 20 + 19 + 18, "every run of 1 to 3 groups"); + let (_, keys) = keys_of(&few, 0.01); + assert!(keys.len() > 20, "{}", keys.len()); + assert!(keys_of(&few, 0.0).1.is_empty(), "no near keys without a tolerance"); + // Past 256 groups the shape is matched whole only, and past 512 contours its contours are not + // grouped at all. + assert!(all_groups(&row(300)).is_empty()); + assert_eq!(all_groups(&row(256)).len(), 256); + let mut nested = kurbo::BezPath::new(); + for i in 0..200 { + // Each square with two squares inside it: 200 groups of 3 contours. + let x = i as f64 * 100.0; + nested.extend(kurbo::Rect::new(x, 0.0, x + 90.0, 90.0).path_elements(0.1)); + nested.extend(kurbo::Rect::new(x + 10.0, 10.0, x + 40.0, 40.0).path_elements(0.1)); + nested.extend(kurbo::Rect::new(x + 50.0, 50.0, x + 80.0, 80.0).path_elements(0.1)); + } + assert!(all_groups(&nested).is_empty(), "600 contours"); + assert_eq!(vectorcraft_text::retype::clusters(&nested).len(), 200, "which would make 200 groups"); + // Many shapes with many runs each: the near keys stop at the cap. + let mut shapes: Vec = (0..8).map(|k| kurbo::Affine::scale_non_uniform(1.0, 1.0 + k as f64 * 0.5) * row(200)).collect(); + let (_, keys) = keys_of(&with_groups(&shapes), 0.01); + assert_eq!(keys.len(), MAX_NEAR_KEYS); + // A plain shape selected after them still gets its own near key: whole shapes come first. + let plain = kurbo::Circle::new((0.0, 0.0), 30.0).to_path(0.1); + let key = vectorcraft_text::retype::near_key(&plain).unwrap(); + shapes.push(plain); + let (_, keys) = keys_of(&with_groups(&shapes), 0.01); + assert!(keys.contains(&key)); + // One command groups at most MAX_SPLIT_TOTAL_CONTOURS contours: the shapes after them are + // matched whole only. + let full = vec![row(256); super::MAX_SPLIT_TOTAL_CONTOURS / 256 + 1]; + let split: Vec = with_groups(&full).iter().map(|(_, g)| g.len()).collect(); + assert!(split[..split.len() - 1].iter().all(|n| *n == 256), "{split:?}"); + assert_eq!(split.last(), Some(&0)); +} diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index d7c7be71d6..9fd06a8f95 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -8,13 +8,22 @@ //! best similarity transform (a Procrustes fit) leaves a tiny leftover distance, and the whole //! outline, turned onto the shape, must then lie on it. That holds for outlines made from a font //! the app has (Create Outlines' output, and other apps' that keep each glyph's contours whole and -//! in the font's order). Near matches (other versions of a font, hinted or simplified outlines, -//! faux styles, glyphs merged into one path) are left unmatched; fuzzy identification is phase 2. +//! in the font's order). +//! +//! Near matches ([`RetypeIndex::near_matches`]) take a tolerance: the shape and the glyph are +//! both read at equal steps of length from any start and in either direction, their contours paired +//! by length, so outlines built another way (a simplified outline, a curve split in two, contours +//! in another order or direction) still fit, and [`GlyphMatch::score`] says how closely. +//! [`clusters`] splits a path holding several glyphs (a word outlined as one compound path) into +//! the contour groups that can each be a glyph. Glyphs fused into one contour are not split. use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; -use kurbo::{Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape}; +use kurbo::{ + Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveNearest, PathEl, PathSeg, Point, QuadBez, Shape, +}; use crate::{FontDb, FontFace}; @@ -42,10 +51,38 @@ const OUTLINE_TOLERANCE: f64 = 5e-3; const MAX_OUTLINE_POINTS: usize = 8192; /// Points along an outline past which the whole-outline check gives up (and so rejects). const MAX_CHECKED_POINTS: usize = 65_536; -/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]). +/// The most glyphs one shape is reported to be ([`RetypeIndex::matches`]), and the most of one face +/// [`RetypeIndex::near_matches`] reports. pub const MAX_CANDIDATES: usize = 16; /// How far apart two shapes' spread-to-length ratios may be and still be compared. const INVARIANT_SLACK: f64 = 0.02; +/// The largest tolerance [`RetypeIndex::near_matches`] takes, and the leftover distance at which +/// [`GlyphMatch::score`] reaches 0. +pub const MAX_TOLERANCE: f64 = 0.05; +/// Points sampled along each contour of a shape for near matching, per point of a glyph's. +const NEAR_OVERSAMPLE: usize = 4; +/// Shapes (and glyphs) with more contours than this are not near matched. +const MAX_NEAR_CONTOURS: usize = 8; +/// How far apart two shapes' spread-to-length ratios may be and still be near matched. +const NEAR_INVARIANT_SLACK: f64 = 0.1; +/// How far apart two shapes' area-to-squared-length ratios may be and still be near matched. +const NEAR_COMPACT_SLACK: f64 = 0.15; +/// Glyphs drawn to check whether they could near match a shape, at most. +const MAX_NEAR_CHECKS: usize = 262_144; +/// Glyphs indexed for near matching, at most. +const MAX_NEAR_GLYPHS: usize = 32_768; +/// Near keys [`RetypeIndex::build_near`] looks glyphs up by, at most: past them, the rest are left +/// out. +pub const MAX_NEAR_KEYS: usize = 1024; +/// Point comparisons near matching makes in all, over every shape of one index: past them, shapes +/// are not near matched. +const NEAR_WORK: u64 = 2_000_000_000; +/// Point comparisons near matching makes for one shape, at most. +const NEAR_SHAPE_WORK: u64 = 50_000_000; +/// Glyphs one shape is near matched against, at most: those closest to it in proportion. +const NEAR_FITS: usize = 256; +/// Contours [`clusters`] reads, at most: past it, none. +const MAX_CLUSTER_CONTOURS: usize = 1024; /// One glyph an outlined shape matched. #[derive(Clone)] @@ -62,6 +99,9 @@ pub struct GlyphMatch { pub origin: Point, /// The leftover distance, relative to the shape's spread. pub residual: f64, + /// Whether the shape is exactly the glyph ([`RetypeIndex::matches`]) rather than nearly + /// ([`RetypeIndex::near_matches`]). + pub exact: bool, /// How many contours the glyph has. pub contours: usize, /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). @@ -80,6 +120,18 @@ pub struct Pose { } impl GlyphMatch { + /// How closely the glyph fits the shape: 1 for an exact match, and for a near one from 1 down + /// to 0 at a leftover distance of [`MAX_TOLERANCE`] or more. + pub fn score(&self) -> f64 { + if self.exact { + return 1.0; + } + if !self.residual.is_finite() { + return 0.0; + } + (1.0 - self.residual / MAX_TOLERANCE).clamp(0.0, 1.0) + } + /// This match in each pose it fits: its own first, then [`Self::alts`]. pub fn poses(&self) -> impl Iterator + '_ { let own = Pose { scale: self.scale, angle: self.angle, origin: self.origin }; @@ -102,6 +154,8 @@ struct Signature { spread: f64, /// `spread` / the total contour length: unchanged by scale, turn and move. invariant: f64, + /// Each contour's length. + lens: Vec, } struct Entry { @@ -120,6 +174,8 @@ pub struct RetypeIndex { entries: Vec, /// Entry indices by contour count, sorted by invariant. buckets: HashMap>, + /// The point comparisons [`Self::near_matches`] may still make, over every shape. + near_work: AtomicU64, } impl RetypeIndex { @@ -128,6 +184,32 @@ impl RetypeIndex { /// they are not sampled. Outlines are read past the shared outline cache, which keeps the /// canvas's glyphs. pub fn build(db: &FontDb, faces: impl IntoIterator>, keys: &BTreeSet) -> Self { + Self::build_near(db, faces, keys, &[]) + } + + /// [`Self::build`], also indexing for [`Self::near_matches`] the glyphs that could near match + /// a shape with one of the [`near_key`]s in `near` (the first [`MAX_NEAR_KEYS`]): the same + /// number of contours (at most 8) and a close area-to-length ratio. At most 262,144 glyphs are + /// drawn to check that, and at most 32,768 indexed for it, each face taking an equal share of + /// both; of a face's glyphs, those closest in that ratio are indexed. + pub fn build_near(db: &FontDb, faces: impl IntoIterator>, keys: &BTreeSet, near: &[NearKey]) -> Self { + Self::build_near_within(db, faces, keys, near, MAX_NEAR_GLYPHS) + } + + /// [`Self::build_near`] indexing at most `near_glyphs` glyphs for near matching. + fn build_near_within( + db: &FontDb, + faces: impl IntoIterator>, + keys: &BTreeSet, + near: &[NearKey], + near_glyphs: usize, + ) -> Self { + let near: Vec = near + .iter() + .copied() + .filter(|k| k.contours <= MAX_NEAR_CONTOURS && k.compact.is_finite() && k.compact > 0.0) + .take(MAX_NEAR_KEYS) + .collect(); let mut kept: Vec> = vec![]; for f in faces { if kept.len() >= MAX_FACES { @@ -137,17 +219,50 @@ impl RetypeIndex { kept.push(f); } } + // Each face gets an equal share of the near checks and entries, so a face with many glyphs + // (a CJK face) does not use them up before the faces after it. + let share = |cap: usize| cap / kept.len().max(1); let mut entries = vec![]; 'faces: for (fi, face) in kept.iter().enumerate() { - for &(gid, ch, key) in face_keys(db, face).iter() { + let mut face_checks = 0usize; + // The face's glyphs that could near match, with how far their key is from the closest + // wanted one: the closest share of them are indexed, whatever their glyph order. + let keep = share(near_glyphs); + let mut close: Vec<(f64, u32, char, BezPath)> = vec![]; + let trim = |close: &mut Vec<(f64, u32, char, BezPath)>| { + close.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + close.truncate(keep); + }; + for &(gid, ch, key, count) in face_keys(db, face).iter() { // The budget holds inside a face too: no glyph is sampled past it. if entries.len() >= MAX_GLYPHS { break 'faces; } - if !keys.contains(&key) { + if keys.contains(&key) { + let outline = db.outline_uncached(face, gid); + if let Some(sig) = signatures(&outline, false).into_iter().next() { + entries.push(Entry { face: fi, gid, ch, sig, outline }); + } continue; } + let count = usize::from(count); + if keep == 0 || face_checks >= share(MAX_NEAR_CHECKS) || !near.iter().any(|k| k.contours == count) { + continue; + } + face_checks += 1; let outline = db.outline_uncached(face, gid); + let Some(g) = near_key(&outline) else { continue }; + let Some(d) = near.iter().filter(|k| k.close_to(&g)).map(|k| k.apart(&g)).min_by(f64::total_cmp) else { continue }; + close.push((d, gid, ch, outline)); + if close.len() >= keep.saturating_mul(2) { + trim(&mut close); + } + } + trim(&mut close); + for (_, gid, ch, outline) in close { + if entries.len() >= MAX_GLYPHS { + break 'faces; + } if let Some(sig) = signatures(&outline, false).into_iter().next() { entries.push(Entry { face: fi, gid, ch, sig, outline }); } @@ -163,7 +278,7 @@ impl RetypeIndex { x.total_cmp(&y) }); } - RetypeIndex { faces: kept, entries, buckets } + RetypeIndex { faces: kept, entries, buckets, near_work: AtomicU64::new(NEAR_WORK) } } /// The faces indexed. @@ -195,7 +310,23 @@ impl RetypeIndex { /// Every glyph `shape` fits exactly, in every face, in the order of [`RetypeIndex::matches`], /// which returns the first [`MAX_CANDIDATES`] of them. pub fn all_matches(&self, shape: &BezPath) -> Vec { - let variants = signatures(shape, true); + self.matches_read(shape, shape) + } + + /// [`Self::all_matches`], and when the shape fits no glyph as it is, its contours read the + /// other way round: for a part of a compound path, which Make Compound Path may have turned so + /// it cuts a hole in the paths behind it. + pub fn matches_either_way(&self, shape: &BezPath) -> Vec { + let found = self.matches_read(shape, shape); + if !found.is_empty() { + return found; + } + self.matches_read(shape, &shape.reverse_subpaths()) + } + + /// [`Self::all_matches`] of `shape`, its contours read as in `reading` (the same outline). + fn matches_read(&self, shape: &BezPath, reading: &BezPath) -> Vec { + let variants = signatures(reading, true); let Some(first) = variants.first() else { return vec![] }; let Some(list) = self.buckets.get(&first.contours) else { return vec![] }; let lo = first.invariant * (1.0 - INVARIANT_SLACK); @@ -246,6 +377,7 @@ impl RetypeIndex { angle: pose.angle, origin: pose.origin, residual, + exact: true, contours: e.sig.contours, alts: rest.iter().map(|(p, _)| *p).collect(), }; @@ -257,6 +389,441 @@ impl RetypeIndex { }); out.into_iter().map(|(_, m)| m).collect() } + + /// The glyphs `shape` (in document space) nearly is: every glyph of the index with as many + /// contours whose best fit leaves a leftover distance of at most `tolerance` (relative to the + /// shape's spread, at most [`MAX_TOLERANCE`]) and whose whole outline, turned onto the shape, + /// lies within three times the tolerance of it (at least 0.5%). The shape and the glyph are + /// read from any start, in either direction, with their contours paired by length, so the + /// shape need not be built as the glyph is. Upright ones first, then the closest; the other + /// turns a glyph fits in (at most 7) are kept in [`GlyphMatch::alts`]; at most + /// [`MAX_CANDIDATES`] for each face. Empty for a tolerance of 0 or less, and for shapes of more + /// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion + /// (the spread-to-length ratio, and the share of the length each contour has), closest first, + /// in at most 50 million point comparisons, and the index's calls make at most 2 billion in + /// all; once they are spent, the glyphs not yet compared are left out. + pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { + // NaN too. + if tolerance.is_nan() || tolerance <= 0.0 { + return vec![]; + } + let tolerance = tolerance.min(MAX_TOLERANCE); + let Some(s) = near_signature(shape) else { return vec![] }; + let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; + let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); + let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); + let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + let tol = s.spread * OUTLINE_TOLERANCE.max(3.0 * tolerance); + let mut shape_flat: Option> = None; + let mut out: Vec<(usize, GlyphMatch)> = vec![]; + // The glyphs closest to the shape in proportion, at most NEAR_FITS, closest first: their + // spread-to-length ratio, and the share of the length each contour has, longest first. + let shares = |sig: &Signature| { + let total: f64 = sig.lens.iter().sum(); + let mut v: Vec = sig.lens.iter().map(|l| l / total).collect(); + v.sort_by(|a, b| b.total_cmp(a)); + v + }; + let own = shares(&s); + let apart = |e: &Entry| { + let d = (e.sig.invariant - s.invariant).abs() / s.invariant + shares(&e.sig).iter().zip(&own).map(|(a, b)| (a - b).abs()).sum::(); + if d.is_finite() { d } else { f64::INFINITY } + }; + let mut near: Vec<(f64, &Entry)> = + list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi).map(|e| (apart(e), e)).collect(); + near.sort_by(|a, b| a.0.total_cmp(&b.0)); + near.truncate(NEAR_FITS); + let total = self.near_work.load(Ordering::Relaxed); + let mut work = total.min(NEAR_SHAPE_WORK); + let given = work; + for (_, e) in near { + if work == 0 { + break; + } + let Some(face) = self.faces.get(e.face) else { continue }; + let fits = near_fit(&e.sig, &s, tolerance, &mut work); + let flat = shape_flat.get_or_insert_with(|| Flat::new(shape, tol)); + let Some(flat) = flat.as_ref() else { break }; + // Every turn the glyph fits the shape at, nearest upright first: the first is its + // pose, the others its alternatives (a glyph that looks alike turned). + let mut poses = + fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES); + let Some((pose, residual)) = poses.next() else { continue }; + let m = GlyphMatch { + face: face.clone(), + gid: e.gid, + ch: e.ch, + scale: pose.scale, + angle: pose.angle, + origin: pose.origin, + residual, + exact: false, + contours: e.sig.contours, + alts: poses.map(|(p, _)| p).collect(), + }; + out.push((e.face, m)); + } + self.near_work.store(total.saturating_sub(given - work), Ordering::Relaxed); + let upright = |m: &GlyphMatch| wrapped(m.angle).abs() >= 1e-3; + out.sort_by(|a, b| { + upright(&a.1).cmp(&upright(&b.1)).then(a.1.residual.total_cmp(&b.1.residual)).then(a.0.cmp(&b.0)).then(a.1.ch.cmp(&b.1.ch)) + }); + keep_per_face(&mut out); + out.into_iter().map(|(_, m)| m).collect() + } +} + +/// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives. +const MAX_NEAR_POSES: usize = 8; + +/// `out` (each match with its face's index) without the matches past the first +/// [`MAX_CANDIDATES`] of each face, so faces drawn alike (copies of one font under other names) +/// do not crowd out the glyphs of the faces after them. +fn keep_per_face(out: &mut Vec<(usize, GlyphMatch)>) { + let mut seen: HashMap = HashMap::new(); + out.retain(|(face, _)| { + let n = seen.entry(*face).or_default(); + *n += 1; + *n <= MAX_CANDIDATES + }); +} + +/// Entry `e`'s pose on near-matching shape `s` at scaled turn `z`, when its whole outline, so +/// placed, lies within `tol` of the shape's (`flat`). +fn near_pose(e: &Entry, s: &Signature, z: (f64, f64), flat: &Flat, tol: f64) -> Option { + let gc = mul(z, e.sig.centre); + let origin = Point::new(s.centre.x - gc.x, s.centre.y - gc.y); + let onto = Affine::new([z.0, z.1, -z.1, z.0, origin.x, origin.y]); + Flat::new(&(onto * e.outline.clone()), tol).is_some_and(|g| g.agrees(flat)).then(|| Pose { scale: z.0.hypot(z.1), angle: z.1.atan2(z.0), origin }) +} + +/// What near matching compares first: a shape's number of contours and its area over its squared +/// length, both unchanged by scale, turn and move, and close for outlines drawn alike. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct NearKey { + pub contours: usize, + pub compact: f64, +} + +impl NearKey { + /// Could shapes with these keys near match? + fn close_to(&self, other: &NearKey) -> bool { + self.contours == other.contours && self.apart(other) <= NEAR_COMPACT_SLACK + } + + /// How far apart the two keys' area-to-squared-length ratios are, relative to the larger. + fn apart(&self, other: &NearKey) -> f64 { + (self.compact - other.compact).abs() / self.compact.max(other.compact) + } +} + +/// `path`'s [`NearKey`]; `None` past the size caps, for an empty shape or one of more than 8 +/// contours. +pub fn near_key(path: &BezPath) -> Option { + let (cs, _, _) = measured(path)?; + if cs.is_empty() || cs.len() > MAX_NEAR_CONTOURS { + return None; + } + let (mut area, mut len) = (0.0, 0.0); + for (c, lens) in &cs { + area += c.iter().map(|s| s.signed_area()).sum::().abs(); + len += lens.iter().sum::(); + } + let compact = area / (len * len); + (compact.is_finite() && compact > 0.0).then_some(NearKey { contours: cs.len(), compact }) +} + +/// `path` read for near matching: points at equal steps of length along each contour from where +/// it starts, [`NEAR_OVERSAMPLE`] times as many as a glyph's. `None` for more than 8 contours. +fn near_signature(path: &BezPath) -> Option { + let (cs, _, accuracy) = measured(path)?; + if cs.is_empty() || cs.len() > MAX_NEAR_CONTOURS { + return None; + } + let starts = vec![vec![0usize]; cs.len()]; + let pick = vec![0usize; cs.len()]; + sample(&cs, &starts, &pick, accuracy, SAMPLES * NEAR_OVERSAMPLE) +} + +/// The scaled turn that best takes glyph `g`'s points onto near-matching shape `s`'s (read by +/// [`near_signature`]), whatever contour each starts at, in either direction and order, and the +/// leftover distance relative to the shape's spread. The longest contours are paired first and give +/// the turns to try (spread over the circle when that pair fits about as well at many). Under each +/// turn, every glyph contour takes the shape contour, start and direction closest to it, and the +/// turn is fitted again over them all, for up to [`REFITS`] rounds. The turns that fit about +/// equally well (a glyph that looks alike turned) and within `limit` are kept, the one nearest +/// upright first ([`fits_within`]). Each point comparison is taken from `work`; none when it runs +/// out before the first turn is fitted, and the turns fitted so far when it runs out after. +fn near_fit(g: &Signature, s: &Signature, limit: f64, work: &mut u64) -> Vec<((f64, f64), f64)> { + fits_within(near_turns(g, s, work).unwrap_or_default(), limit) +} + +/// The turns [`near_fit`] fits, each with its leftover distance. +fn near_turns(g: &Signature, s: &Signature, work: &mut u64) -> Option> { + let nc = g.contours; + let m = SAMPLES * NEAR_OVERSAMPLE; + if nc == 0 || s.contours != nc || g.pts.len() != nc * SAMPLES || s.pts.len() != nc * m || g.lens.len() != nc || s.lens.len() != nc { + return None; + } + // Comparisons the longest pair's every start and direction take, and one round of pairing + // every contour and fitting the turn. + let first_cost = (4 * m * SAMPLES) as u64; + let round_cost = ((nc * (nc + 1) * m + 20 * nc) * SAMPLES) as u64; + let Some(left) = work.checked_sub(first_cost) else { + *work = 0; + return None; + }; + *work = left; + let by_len = |lens: &[f64]| { + let mut o: Vec = (0..lens.len()).collect(); + o.sort_by(|a, b| lens.get(*b).copied().unwrap_or(0.0).total_cmp(&lens.get(*a).copied().unwrap_or(0.0))); + o + }; + let (go, so) = (by_len(&g.lens), by_len(&s.lens)); + let (&ga, &sa) = (go.first()?, so.first()?); + let gpts = |c: usize| g.pts.get(c * SAMPLES..(c + 1) * SAMPLES); + let spts = |c: usize| s.pts.get(c * m..(c + 1) * m); + // The point of shape contour `b` matched to glyph sample j, from start k (in samples, and + // between two samples read on the line joining them), forward or back. + let at = |b: &[Point], k: f64, j: usize, back: bool| { + let step = (j * NEAR_OVERSAMPLE) as f64; + let x = (if back { k - step } else { k + step }).rem_euclid(m as f64); + let i = (x.floor() as usize).min(m - 1); + let (p, q) = (b.get(i).copied().unwrap_or(Point::ZERO), b.get((i + 1) % m).copied().unwrap_or(Point::ZERO)); + p.lerp(q, x - i as f64) + }; + // The fit of glyph contour `a` onto shape contour `b` from start k: Σ b·conj(a) and Σ|a|². + let sums = |a: &[Point], b: &[Point], k: f64, back: bool| { + let (mut re, mut im, mut aa) = (0.0, 0.0, 0.0); + for (j, p) in a.iter().enumerate() { + let q = at(b, k, j, back); + re += q.x * p.x + q.y * p.y; + im += q.y * p.x - q.x * p.y; + aa += p.x * p.x + p.y * p.y; + } + (re, im, aa) + }; + let sse = |a: &[Point], b: &[Point], k: f64, back: bool, z: (f64, f64)| { + a.iter().enumerate().map(|(j, p)| at(b, k, j, back).distance_squared(mul(z, *p))).sum::() + }; + // Every start and direction of the longest pair, with its own best turn. + let (a0, b0) = (gpts(ga)?, spts(sa)?); + let mut firsts: Vec<(f64, (f64, f64))> = vec![]; + for back in [false, true] { + for k in 0..m { + let (re, im, aa) = sums(a0, b0, k as f64, back); + if aa <= 0.0 || !aa.is_finite() { + return None; + } + let z = (re / aa, im / aa); + firsts.push((sse(a0, b0, k as f64, back, z), z)); + } + } + firsts.sort_by(|a, b| a.0.total_cmp(&b.0)); + let best = firsts.first()?.0; + // The turns that fit the longest pair about as well as the best. A longest contour that is + // nearly round fits at every angle, and only the other contours tell the turns apart, so + // besides the turns nearest upright, the best in each of TURN_BINS equal ranges of angle is + // tried, at most MAX_TURNS of them, evenly by angle. + const TURN_BINS: usize = 64; + const MAX_TURNS: usize = 24; + let window = best * 1.5 + 1e-12 * s.spread * s.spread; + let mut bins: Vec> = vec![None; TURN_BINS]; + for &(e, z) in firsts.iter().take_while(|(e, _)| *e <= window) { + let ang = z.1.atan2(z.0); + if !ang.is_finite() { + continue; + } + let b = (((ang + std::f64::consts::PI) / std::f64::consts::TAU * TURN_BINS as f64) as usize).min(TURN_BINS - 1); + if let Some(slot) = bins.get_mut(b) + && slot.is_none_or(|(old, _)| e < old) + { + *slot = Some((e, z)); + } + } + // First the best turn and up to five others nearest upright, told apart by their angle, then + // the spread ones. + let mut turns: Vec<(f64, f64)> = firsts.first().map(|f| f.1).into_iter().collect(); + let mut upright: Vec<(f64, f64)> = firsts.iter().take_while(|(e, _)| *e <= window).map(|(_, z)| *z).collect(); + upright.sort_by(|a, b| wrapped(a.1.atan2(a.0)).abs().total_cmp(&wrapped(b.1.atan2(b.0)).abs())); + for z in upright { + if turns.len() >= 6 { + break; + } + let ang = z.1.atan2(z.0); + if turns.iter().all(|t| wrapped(t.1.atan2(t.0) - ang).abs() > 0.05) { + turns.push(z); + } + } + // One contour: every start of it was tried above, and its own fit is final. + if nc > 1 { + let spread: Vec<(f64, f64)> = bins.into_iter().flatten().map(|(_, z)| z).collect(); + let step = spread.len().div_ceil(MAX_TURNS).max(1); + turns.extend(spread.into_iter().step_by(step)); + } + let rounds = if nc > 1 { REFITS } else { 1 }; + let n = (nc * SAMPLES) as f64; + // Each glyph contour, longest first, takes the shape contour, start and direction that fit it + // best under turn `z`; then the turn is fitted over every pair. The new turn and the leftover + // distance; `None` inside for a fit with nothing to go on, and `None` for malformed readings. + let pair_and_fit = |z: (f64, f64)| -> Option> { + let mut free: Vec = so.clone(); + let mut pairs: Vec<(usize, usize, f64, bool)> = vec![]; + for &gc in &go { + let a = gpts(gc)?; + let mut pick: Option<(f64, usize, f64, bool)> = None; + for (fi, &sc) in free.iter().enumerate() { + let b = spts(sc)?; + for back in [false, true] { + for k in 0..m { + let e = sse(a, b, k as f64, back, z); + if pick.is_none_or(|p| e < p.0) { + pick = Some((e, fi, k as f64, back)); + } + } + } + } + let (mut e, fi, mut k, back) = pick?; + let sc = free.remove(fi); + // The start between samples: the shape's samples need not fall where the glyph's do. + let b = spts(sc)?; + let k0 = k; + for d in 1..16 { + let kd = k0 - 0.5 + d as f64 / 16.0; + let ed = sse(a, b, kd, back, z); + if ed < e { + (e, k) = (ed, kd); + } + } + pairs.push((gc, sc, k, back)); + } + let (mut re, mut im, mut aa) = (0.0, 0.0, 0.0); + for &(gc, sc, k, back) in &pairs { + let (r, i, a) = sums(gpts(gc)?, spts(sc)?, k, back); + re += r; + im += i; + aa += a; + } + if aa <= 0.0 || !aa.is_finite() { + return Some(None); + } + let z = (re / aa, im / aa); + let mut total = 0.0; + for &(gc, sc, k, back) in &pairs { + total += sse(gpts(gc)?, spts(sc)?, k, back, z); + } + let rel = (total / n).sqrt() / s.spread; + Some(rel.is_finite().then_some((z, rel))) + }; + let mut results: Vec<((f64, f64), f64)> = vec![]; + 'turns: for z0 in turns { + // Each glyph contour is paired under the turn, the turn is fitted again over the pairs, + // and the contours are paired again under the new turn, until it settles: a turn that + // starts a little off (a round longest contour) moves onto the one the other contours set. + let mut z = z0; + let mut fitted: Option<((f64, f64), f64)> = None; + for _ in 0..rounds { + let Some(left) = work.checked_sub(round_cost) else { + *work = 0; + results.extend(fitted); + break 'turns; + }; + *work = left; + let Some((nz, rel)) = pair_and_fit(z)? else { break }; + let settled = (nz.0 - z.0).hypot(nz.1 - z.1) <= 1e-6 * z.0.hypot(z.1); + if fitted.is_none_or(|f| rel <= f.1) { + fitted = Some((nz, rel)); + } + z = nz; + if settled { + break; + } + } + results.extend(fitted); + } + Some(results) +} + +/// Of fitted turns and their leftover distances, those that fit about as well as the best (within +/// 1.5 times its distance) and within `limit`, nearest upright first, one per turn (turns less +/// than 0.001 apart are one); the best one alone when none is within `limit`. +fn fits_within(results: Vec<((f64, f64), f64)>, limit: f64) -> Vec<((f64, f64), f64)> { + let best = results.iter().map(|r| r.1).fold(f64::INFINITY, f64::min); + let cap = (best * 1.5 + 1e-9).min(limit.max(best)); + let turn = |r: &((f64, f64), f64)| r.0.1.atan2(r.0.0); + let mut kept: Vec<((f64, f64), f64)> = results.into_iter().filter(|r| r.1 <= cap).collect(); + kept.sort_by(|a, b| wrapped(turn(a)).abs().total_cmp(&wrapped(turn(b)).abs()).then(a.1.total_cmp(&b.1))); + let mut out: Vec<((f64, f64), f64)> = vec![]; + for r in kept { + if out.iter().all(|o| wrapped(turn(o) - turn(&r)).abs() >= 1e-3) { + out.push(r); + } + } + out +} + +/// Rounds of pairing and fitting [`near_fit`] gives each turn, at most. +const REFITS: usize = 4; + +/// `path`'s contours in groups that can each be one glyph: a contour with the contours that lie +/// inside it (a letter's counters, and what lies inside those), in the order the outer contours +/// come. A path of several glyphs (a word outlined as one compound path) gives one group per glyph +/// part (an i gives two: its stem and its dot). Empty past 1,024 contours. +pub fn clusters(path: &BezPath) -> Vec { + let mut subs: Vec = vec![]; + for el in path.elements() { + match el { + PathEl::MoveTo(_) => { + if subs.len() >= MAX_CLUSTER_CONTOURS { + return vec![]; + } + subs.push(BezPath::new()); + if let Some(s) = subs.last_mut() { + s.push(*el); + } + } + _ => match subs.last_mut() { + Some(s) => s.push(*el), + None => return vec![], + }, + } + } + let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); + let starts: Vec> = subs.iter().map(|s| s.elements().first().and_then(|e| e.end_point())).collect(); + // Each contour's container: the smallest contour around it. + let parent: Vec> = (0..subs.len()) + .map(|i| { + let (Some(bi), Some(Some(p))) = (boxes.get(i), starts.get(i)) else { return None }; + (0..subs.len()) + .filter(|&j| j != i) + .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) + .filter(|(_, bj, sj)| { + bj.area() > bi.area() && bj.x0 <= bi.x0 && bj.y0 <= bi.y0 && bj.x1 >= bi.x1 && bj.y1 >= bi.y1 && sj.winding(*p) != 0 + }) + .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) + .map(|(j, _, _)| j) + }) + .collect(); + let root = |mut i: usize| { + // Containers are strictly larger, so the chain ends; the bound keeps it so. + for _ in 0..subs.len() { + match parent.get(i).copied().flatten() { + Some(p) => i = p, + None => break, + } + } + i + }; + let mut groups: Vec<(usize, BezPath)> = vec![]; + for (i, s) in subs.iter().enumerate() { + let r = root(i); + match groups.iter_mut().find(|(g, _)| *g == r) { + Some((_, p)) => p.extend(s.iter()), + None => groups.push((r, s.clone())), + } + } + groups.sort_by_key(|(r, _)| *r); + groups.into_iter().map(|(_, p)| p).collect() } /// `a` wrapped into −π..π. @@ -264,11 +831,11 @@ fn wrapped(a: f64) -> f64 { (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI } -/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`]), one per glyph -/// under the lowest character that maps to it. -type FaceKeys = Arc>; +/// A face's glyphs as the index looks them up: (glyph, character, [`shape_key`], contours), one per +/// glyph under the lowest character that maps to it. +type FaceKeys = Arc>; -/// How many glyph keys [`face_keys`] keeps in all (16 bytes each). +/// How many glyph keys [`face_keys`] keeps in all (24 bytes each). const KEPT_KEYS: usize = 1 << 20; /// The faces' keys [`face_keys`] keeps, for the database generation they were read in. @@ -306,7 +873,14 @@ fn face_keys(db: &FontDb, face: &FontFace) -> FaceKeys { } let mut gids: Vec<(u32, char)> = by_gid.into_iter().collect(); gids.sort_unstable(); - let keys: FaceKeys = Arc::new(gids.into_iter().filter_map(|(gid, ch)| Some((gid, ch, shape_key(&db.outline_uncached(face, gid))?))).collect()); + let keys: FaceKeys = Arc::new( + gids.into_iter() + .filter_map(|(gid, ch)| { + let (key, count) = key_and_count(&db.outline_uncached(face, gid))?; + Some((gid, ch, key, u16::try_from(count).ok()?)) + }) + .collect(), + ); let mut k = kept.lock().unwrap_or_else(|e| e.into_inner()); if k.generation != generation { return keys; @@ -580,6 +1154,11 @@ fn contours(path: &BezPath) -> Option>> { /// each of its contours has, in order, as [`contours`] reads them, hashed. Glyphs whose key no /// selected shape has are not sampled. `None` past the size caps or for an empty shape. pub fn shape_key(path: &BezPath) -> Option { + key_and_count(path).map(|(k, _)| k) +} + +/// [`shape_key`] and the number of contours it counts. +fn key_and_count(path: &BezPath) -> Option<(u64, usize)> { let cs = contours(path)?; if cs.is_empty() { return None; @@ -592,32 +1171,14 @@ pub fn shape_key(path: &BezPath) -> Option { h = h.wrapping_mul(0x0000_0100_0000_01b3); } } - Some(h) + Some((h, cs.len())) } /// `path` read for matching: one reading per choice of starting corners (the corner of each contour /// farthest from the centre of all the shape's corners; every tied corner when `all_ties`, else the /// first), at most [`MAX_VARIANTS`] tried. Empty for a shape with nothing to match. fn signatures(path: &BezPath, all_ties: bool) -> Vec { - let bounds = path.bounding_box(); - let size = bounds.width().hypot(bounds.height()); - if !size.is_finite() || size <= 0.0 { - return vec![]; - } - let accuracy = size * 1e-6; - let Some(cs) = contours(path) else { return vec![] }; - // Each contour with length, with its segments' lengths. - let cs: Vec<(Vec, Vec)> = cs - .into_iter() - .map(|c| { - let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); - (c, lens) - }) - .filter(|(_, lens)| { - let len: f64 = lens.iter().sum(); - len.is_finite() && len > size * 1e-9 - }) - .collect(); + let Some((cs, size, accuracy)) = measured(path) else { return vec![] }; let corners: Vec = cs.iter().flat_map(|(c, _)| c.iter().map(|s| s.start())).collect(); if corners.is_empty() { return vec![]; @@ -644,7 +1205,7 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { break; } tried += 1; - if let Some(sig) = sample(&cs, &starts, &pick, accuracy) { + if let Some(sig) = sample(&cs, &starts, &pick, accuracy, SAMPLES) { out.push(sig); } // The next choice of tied corners (a counter in mixed radix). @@ -662,19 +1223,47 @@ fn signatures(path: &BezPath, all_ties: bool) -> Vec { out } -/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`. -fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize], accuracy: f64) -> Option { - let mut pts = Vec::with_capacity(cs.len() * SAMPLES); +/// `path`'s contours as [`contours`] reads them, each with its segments' lengths, leaving out +/// contours of no length, the shape's size (its bounding box's diagonal) and the accuracy lengths +/// are measured to (a millionth of the size). `None` past the size caps and for a shape of no size. +#[allow(clippy::type_complexity)] +fn measured(path: &BezPath) -> Option<(Vec<(Vec, Vec)>, f64, f64)> { + let bounds = path.bounding_box(); + let size = bounds.width().hypot(bounds.height()); + if !size.is_finite() || size <= 0.0 { + return None; + } + let accuracy = size * 1e-6; + let cs = contours(path)? + .into_iter() + .map(|c| { + let lens: Vec = c.iter().map(|s| s.arclen(accuracy)).collect(); + (c, lens) + }) + .filter(|(_, lens)| { + let len: f64 = lens.iter().sum(); + len.is_finite() && len > size * 1e-9 + }) + .collect(); + Some((cs, size, accuracy)) +} + +/// One reading of the contours `cs`, contour `i` starting at segment `starts[i][pick[i]]`, `n` +/// points along each. +fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize], accuracy: f64, n: usize) -> Option { + let mut pts = Vec::with_capacity(cs.len() * n); + let mut lens_out = Vec::with_capacity(cs.len()); let mut total = 0.0; for (((c, lens), s), p) in cs.iter().zip(starts).zip(pick) { let from = *s.get(*p)?; let m = c.len(); let len: f64 = lens.iter().sum(); total += len; + lens_out.push(len); let (mut k, mut before) = (0usize, 0.0); let at_k = |k: usize| (from + k) % m; - for j in 0..SAMPLES { - let at = len * j as f64 / SAMPLES as f64; + for j in 0..n { + let at = len * j as f64 / n as f64; while k + 1 < m && before + lens.get(at_k(k)).copied().unwrap_or(0.0) < at { before += lens.get(at_k(k)).copied().unwrap_or(0.0); k += 1; @@ -696,7 +1285,7 @@ fn sample(cs: &[(Vec, Vec)], starts: &[Vec], pick: &[usize] if !spread.is_finite() || spread <= 0.0 || !total.is_finite() || total <= 0.0 { return None; } - Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total }) + Some(Signature { contours: cs.len(), pts, centre, spread, invariant: spread / total, lens: lens_out }) } /// The first reading of `path` (for tests). @@ -899,6 +1488,236 @@ mod tests { assert!(t0.elapsed() < std::time::Duration::from_secs(5), "{:?}", t0.elapsed()); } + /// `p` flattened into lines `tol` from its curves, each contour started at its second point and + /// run backwards: a simplified outline built nothing like the original. + fn simplified(p: &BezPath, tol: f64) -> BezPath { + let mut contours: Vec> = vec![]; + kurbo::flatten(p.iter(), tol, |el| match el { + PathEl::MoveTo(q) => contours.push(vec![q]), + PathEl::LineTo(q) => { + if let Some(c) = contours.last_mut() { + c.push(q); + } + } + _ => {} + }); + let mut out = BezPath::new(); + for mut c in contours { + c.rotate_left(1); + c.reverse(); + out.move_to(c[0]); + for q in &c[1..] { + out.line_to(*q); + } + out.close_path(); + } + out + } + + fn near_residual(glyph: &BezPath, shape: &BezPath) -> f64 { + near_fit_all(&signature(glyph).unwrap(), &near_signature(shape).unwrap()).map_or(f64::INFINITY, |(_, r)| r) + } + + /// [`near_fit`]'s first fit, with no limit on its work. + fn near_fit_all(g: &Signature, s: &Signature) -> Option<((f64, f64), f64)> { + let mut work = u64::MAX; + near_fit(g, s, MAX_TOLERANCE, &mut work).into_iter().next() + } + + /// [`fits_within`]'s first fit. + fn nearest_upright(results: Vec<((f64, f64), f64)>, limit: f64) -> Option<((f64, f64), f64)> { + fits_within(results, limit).into_iter().next() + } + + #[test] + fn a_simplified_outline_near_matches_and_another_shape_does_not() { + let xf = Affine::translate((300.0, 200.0)) * Affine::rotate(0.4) * Affine::scale(0.024); + let shape = xf * simplified(&letter(), 2.0); + assert_ne!(shape_key(&shape), shape_key(&letter()), "built another way: the exact index never samples it"); + assert!(best_fit(&letter(), &shape) > TOLERANCE, "no exact match"); + let r = near_residual(&letter(), &shape); + assert!(r < 0.005, "near match {r}"); + let (z, _) = near_fit_all(&signature(&letter()).unwrap(), &near_signature(&shape).unwrap()).unwrap(); + // With too little work left, no fit, and nothing left after. + let mut work = 1000; + assert!(near_fit(&signature(&letter()).unwrap(), &near_signature(&shape).unwrap(), MAX_TOLERANCE, &mut work).is_empty()); + assert_eq!(work, 0); + assert!((z.0.hypot(z.1) - 0.024).abs() < 0.024 * 0.01 && (z.1.atan2(z.0) - 0.4).abs() < 0.01, "{z:?}"); + let (a, b) = (near_key(&letter()).unwrap(), near_key(&shape).unwrap()); + assert!(a.close_to(&b), "{a:?} {b:?}"); + // The exact reading of the letter itself near matches it too, with next to nothing left over. + assert!(near_residual(&letter(), &letter()) < 1e-3); + // A box is not near a circle. + let mut o = BezPath::new(); + o.extend(kurbo::Circle::new((200.0, -350.0), 300.0).path_elements(0.1)); + let mut box_ = BezPath::new(); + box_.extend(kurbo::Rect::new(0.0, -700.0, 600.0, 0.0).path_elements(0.1)); + assert!(near_residual(&o, &box_) > MAX_TOLERANCE); + assert!(!near_key(&o).unwrap().close_to(&near_key(&box_).unwrap())); + } + + #[test] + fn a_turned_round_glyph_near_matches_upright() { + // A circle fits at every turn: the turn kept is the upright one. + let mut o = BezPath::new(); + o.extend(kurbo::Circle::new((0.0, 0.0), 300.0).path_elements(0.1)); + let (z, r) = near_fit_all(&signature(&o).unwrap(), &near_signature(&simplified(&o, 1.0)).unwrap()).unwrap(); + assert!(r < 0.005, "{r}"); + assert!(z.1.atan2(z.0).abs() < 0.06, "{z:?}"); + } + + #[test] + fn the_upright_turn_is_kept_only_within_the_limit() { + let turned = |a: f64, r: f64| ((a.cos(), a.sin()), r); + // The best fit is turned a quarter round; an upright one fits nearly as well. + let fits = || vec![turned(std::f64::consts::FRAC_PI_2, 0.010), turned(0.0, 0.014)]; + let angle = |f: Option<((f64, f64), f64)>| f.map(|((c, s), _)| s.atan2(c)); + assert_eq!(angle(nearest_upright(fits(), 0.02)), Some(0.0), "both within the limit: the upright one"); + let kept = nearest_upright(fits(), 0.012).unwrap(); + assert!((kept.1 - 0.010).abs() < 1e-12, "only the best is within the limit: the best {kept:?}"); + let kept = nearest_upright(fits(), 0.005).unwrap(); + assert!((kept.1 - 0.010).abs() < 1e-12, "none within the limit: the best {kept:?}"); + assert!(nearest_upright(vec![], 0.05).is_none()); + // Every turn within the limit is kept, upright first, once each. + let all = fits_within( + vec![turned(std::f64::consts::PI, 0.011), turned(std::f64::consts::FRAC_PI_2, 0.010), turned(0.0, 0.014), turned(1e-4, 0.0141)], + 0.02, + ); + let angles: Vec = all.iter().map(|((c, s), _)| s.atan2(*c)).collect(); + assert_eq!(angles.len(), 3, "{angles:?}"); + assert!(angles[0] == 0.0 && (angles[1] - std::f64::consts::FRAC_PI_2).abs() < 1e-12, "{angles:?}"); + } + + #[test] + fn a_curve_split_in_two_still_near_matches() { + // letter() with its cubic split at its middle: exactly another shape, nearly the same. + let (a, b) = kurbo::CubicBez::new((0.0, -700.0), (300.0, -700.0), (450.0, -600.0), (450.0, -480.0)).subdivide(); + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((0.0, -700.0)); + p.curve_to(a.p1, a.p2, a.p3); + p.curve_to(b.p1, b.p2, b.p3); + p.quad_to((450.0, -300.0), (120.0, -300.0)); + p.line_to((120.0, 0.0)); + p.close_path(); + p.move_to((120.0, -600.0)); + p.line_to((120.0, -400.0)); + p.quad_to((330.0, -400.0), (330.0, -500.0)); + p.quad_to((330.0, -600.0), (120.0, -600.0)); + p.close_path(); + assert_ne!(shape_key(&p), shape_key(&letter())); + let shape = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * p; + assert!(near_residual(&letter(), &shape) < 0.005); + } + + #[test] + fn contours_in_another_order_still_near_match() { + // letter() with its counter first, simplified. + let l = letter(); + let els = l.elements(); + let second = els.iter().rposition(|e| matches!(e, PathEl::MoveTo(_))).unwrap(); + let mut back = BezPath::new(); + back.extend(els[second..].iter().copied()); + back.extend(els[..second].iter().copied()); + let shape = Affine::translate((40.0, 90.0)) * Affine::rotate(0.3) * Affine::scale(0.03) * simplified(&back, 2.0); + assert!(near_residual(&letter(), &shape) < 0.005); + } + + #[test] + fn copies_of_a_font_do_not_crowd_out_the_faces_after_them() { + use crate::test_fonts::{HEIGHT_FAMILY, HEIGHT_OUTSIDE_FAMILY, HEIGHTLESS_FAMILY, NUMBERLESS_FAMILY}; + // Source Sans 3 Regular and four copies of it under other names: each face has several + // glyphs drawn as the period (. · ∙ ․), more than MAX_CANDIDATES in all. + let db = FontDb::with_font_dirs(vec![]); + for bytes in [ + crate::test_fonts::height_font(true), + crate::test_fonts::height_font(false), + crate::test_fonts::height_outside_font(), + crate::test_fonts::numberless_font(), + ] { + db.add_font(bytes.unwrap()); + } + let faces: Vec> = ["Source Sans 3", HEIGHT_FAMILY, HEIGHTLESS_FAMILY, HEIGHT_OUTSIDE_FAMILY, NUMBERLESS_FAMILY] + .iter() + .map(|f| db.face(f, "Regular").unwrap()) + .collect(); + let gid = faces[0].mapped_chars().iter().find(|(c, _)| *c == '.').map(|(_, g)| *g).unwrap(); + let period = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * db.outline_uncached(&faces[0], gid); + let has_every_period = |found: &[GlyphMatch]| faces.iter().all(|f| found.iter().any(|m| m.ch == '.' && m.face.id() == f.id())); + let keys: BTreeSet = shape_key(&period).into_iter().collect(); + let index = RetypeIndex::build(&db, faces.clone(), &keys); + // The parts of a split compound path are looked up in every face, as whole shapes are. + let found = index.matches_either_way(&period); + assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "exact: {} matches", found.len()); + let simple = simplified(&period, 0.05); + let index = RetypeIndex::build_near(&db, faces.clone(), &BTreeSet::new(), &[near_key(&simple).unwrap()]); + let found = index.near_matches(&simple, 0.02); + assert!(found.len() > MAX_CANDIDATES && has_every_period(&found), "near: {} matches", found.len()); + } + + #[test] + fn a_face_past_its_near_share_keeps_the_glyphs_closest_to_the_shapes() { + // One glyph of the face is indexed for near matching: the one closest to a simplified o, + // whatever comes before the o in glyph order. + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * simplified(&db.outline_uncached(&face, gid), 4.0); + let key = near_key(&shape).unwrap(); + let index = RetypeIndex::build_near_within(db, [face], &BTreeSet::new(), &[key], 1); + assert_eq!(index.len(), 1); + let found: Vec = index.near_matches(&shape, 0.02).iter().map(|m| m.ch).collect(); + // The Latin o or the Greek omicron, drawn the same. + assert!(found.iter().any(|c| matches!(c, 'o' | 'ο')), "{found:?}"); + } + + #[test] + fn a_round_glyph_with_an_off_centre_counter_near_matches_at_its_turn() { + // A round outer contour fits the shape at every turn; only the counter, off the centre, + // tells the turn, which is far from upright. + let polygon = |cx: f64, cy: f64, r: f64, n: usize, back: bool| { + let mut p = BezPath::new(); + for i in 0..n { + let a = std::f64::consts::TAU * i as f64 / n as f64 * if back { -1.0 } else { 1.0 }; + let q = Point::new(cx + r * a.cos(), cy + r * a.sin()); + if i == 0 { p.move_to(q) } else { p.line_to(q) } + } + p.close_path(); + p + }; + // The outer contour has 720 corners: as round as the samples can tell. + let mut g = polygon(0.0, 0.0, 300.0, 720, false); + g.extend(polygon(120.0, 40.0, 80.0, 24, true).iter()); + let xf = Affine::translate((500.0, 400.0)) * Affine::rotate(2.0) * Affine::scale(0.05); + let shape = xf * simplified(&g, 1.0); + let (z, r) = near_fit_all(&signature(&g).unwrap(), &near_signature(&shape).unwrap()).unwrap(); + assert!(r < 0.01, "{r}"); + assert!(wrapped(z.1.atan2(z.0) - 2.0).abs() < 0.02, "{z:?}"); + } + + #[test] + fn clusters_split_a_word_into_its_glyph_parts() { + let mut word = letter(); + word.extend((Affine::translate((600.0, 0.0)) * letter()).iter()); + // An i: a stem and a dot beside it. + word.extend(kurbo::Rect::new(1200.0, -500.0, 1260.0, 0.0).path_elements(0.1)); + word.extend(kurbo::Circle::new((1230.0, -600.0), 40.0).path_elements(0.1)); + let parts = clusters(&word); + assert_eq!(parts.len(), 4, "two letters (each with its counter), a stem and a dot"); + assert_eq!(shape_key(&parts[0]), shape_key(&letter())); + assert_eq!(shape_key(&parts[1]), shape_key(&letter())); + assert_eq!(parts[2].elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(), 1); + // A counter written before its outer contour still goes with it, in the outer's place. + let mut back = BezPath::new(); + let l = letter(); + let els = l.elements(); + let second = els.iter().rposition(|e| matches!(e, PathEl::MoveTo(_))).unwrap(); + back.extend(els[second..].iter().copied()); + back.extend(els[..second].iter().copied()); + assert_eq!(clusters(&back).len(), 1); + assert!(clusters(&BezPath::new()).is_empty()); + } + #[test] fn the_same_corners_joined_another_way_are_another_outline() { let poly = |pts: &[(f64, f64)]| { diff --git a/docs/gaps.md b/docs/gaps.md index 288296debf..c94e0fbc56 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -500,7 +500,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** CJK vertical composition (custom mojikumi sets and the Mojikumi Settings dialog, kinsoku settings #633, manual tate-chu-yoko), Middle Eastern features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935), - Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, and the Retype panel lists the exactly matching fonts; near matches, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). + Touch Type, Retype beyond exact matches of available fonts (phase 1 is in, #4934, the Retype panel lists the exactly matching fonts, and `type.retype` takes near matches within a tolerance and words outlined as one compound path; glyphs fused into one contour, near matches in the panel's list, installed fonts not yet loaded and text in images remain), Snap to Glyph; optional preservation of font sizes during group scaling (#1034 enhancement). Itemized in [type-parity.md](type-parity.md). - **Impact:** professional typography and Japanese/Chinese publishing. - **Estimate:** 34–47 h (type core 14–19 h blocks beta). diff --git a/docs/mcp.md b/docs/mcp.md index 79f6183e79..570e3bb84c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10944,6 +10944,34 @@ hidden state and stay live on the group; none of them is copied onto the glyph p glyph. `object.expand` outlines type with this command, so Fill and Stroke expand those paths' gradients, patterns and strokes. +`type.retype` (Type › Retype) turns outlined glyphs back into point text. By default a shape must be exactly a glyph of +an available font. With `tolerance` (0 to 0.05), a shape of at most 8 contours that is no glyph exactly becomes the +glyph it is closest to when its leftover distance from that glyph, relative to the shape's size, is at most the +tolerance: an outline simplified, a curve split in two, or contours in another order, start or direction. The tolerance +and this measure are VectorCraft's own. A near-matched glyph may differ from its line by the tolerance in size, turn +and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is +a near match. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 +at a leftover distance of 0.05. A compound path that holds several +glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours +inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the +remaining groups can still all be matched, so an i's stem and dot become one i. A group whose contours run the other +way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come +first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The +compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in +`unmatched`. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours +is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are +matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at +most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left +out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that +limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 +are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes +in proportion are indexed. + +```json +{"name":"run_command","arguments":{"command":"type.retype","params":{"tolerance":0.02}}} +``` + `type.createOutlines` (Type › Create Outlines) and `effect.expandAppearance` (when it outlines type, as Expand Appearance describes) take an outlined frame of threaded text out of its thread with the text it shows, and the other frames keep the text they hold. When the thread's last frame is outlined, the text it has no room for, which its @@ -12101,7 +12129,8 @@ on an open path that are not drawn because they fall before the path's start can `type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path and compound path, inside groups too, with the glyphs of up to 96 loaded fonts, those of the document's live type -first, by the matching `type.retype` uses, and it counts only exact matches. When two versions of a font are loaded, +first, by the matching `type.retype` uses, and it counts only exact matches of whole shapes: it does not split a +compound path into glyphs or take near matches. When two versions of a font are loaded, only the version its family and style name gives is compared, which is the version that choosing the font sets. The fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name. `count` is a whole number from 1 to 96 (default 10); any other value is an error. The reply is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 83bcd03586..c28cbf272f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -3008,7 +3008,11 @@ Check Spelling followed (2026-11-15): Edit › Spelling › Check Spelling… (` ## Retype, phase 1 (2026-11-18) -The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape (phase 2, with the other near matches). Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Near matches, the ranked font list, installed fonts not yet loaded and images remain (phase 2). +The public pages describe Retype finding the fonts that match selected outlined text (or text in an image), from the fonts on the device among others, and applying them to live text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html)). Phase 1 (#4934) is local and exact: Type › Retype (`type.retype`) compares each selected glyph shape with the glyphs of the loaded fonts, the document's fonts and any families named in `fonts`, the same up to uniform scale, rotation and translation, and sets the matched characters as point text in that font and size at the same baseline, one object per line, in one undo step. Shapes that match no font stay and are reported. The search is bounded, not exhaustive: at most 96 faces (named families first, then the document's fonts, then the other loaded faces), the first 65,536 encoded characters of each, and glyphs of plain-shape characters (box drawing, blocks, geometric shapes, private use) are left out; a glyph outside those limits is reported as matching no font. Exact matching also reads a curve an exporter split in two as a different shape; near matching with a tolerance (below) reads it as the glyph. Tested by round trips through Create Outlines (plain, bold and turned, serif, word spaces), a drawn shape and a mixed selection (`crates/engine/src/cmd/retype_tests.rs`). Installed fonts not yet loaded and images remain (phase 2). + +## Retype near matches (2026-11-18) + +The public page orders Retype's matching fonts by how close each is to the text's appearance ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)), so outlines need not be exactly a font's glyphs. `type.retype` takes a `tolerance` (0 to 0.05, default 0 for exact matches only). Above 0, a shape of up to 8 contours that is no glyph exactly is read at equal steps of length from any start and in either direction, its contours paired with the glyph's by length, and it becomes the glyph it is closest to when the leftover distance, relative to the shape's size, is at most the tolerance and the glyph's outline and the shape's each lie within three times the tolerance (relative to the shape's size, and at least 0.5%) of the other. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is a near match. Each line in the result has a `score` from 1 (exact) to 0. A compound path holding several glyphs (a word made into one compound path) is split into groups of contours and matched in runs of up to three groups, and becomes type only when every glyph does; exact matching of those groups also reads contours that run the other way round, as Make Compound Path leaves them. Exact matches of the whole shape come first, then exact matches of its groups, then near matches. The tolerance, the score and the splitting are VectorCraft's own. Tested with outlines flattened into lines, restarted, reversed and simplified, a curve split in two, contours in another order, turned lines of round glyphs, a word made into one compound path, and a compound with a part that is no glyph (`crates/engine/src/cmd/retype_tests.rs`, `crates/text/src/retype.rs`). The Retype panel's list (below) still takes exact matches of whole shapes only. Glyphs fused into one contour, installed fonts not yet loaded and images remain. ## Retype panel (2026-11-18) diff --git a/docs/type-parity.md b/docs/type-parity.md index d97f5bc105..bfd821ee10 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, tracking, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours that are nearly a glyph (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, tracking, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From 61ad1e44895ca2e69dc44027f67291edd3b3a0a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:23:15 -0800 Subject: [PATCH 009/126] Selection: split the release-point tracking out of the pointer handler --- crates/tools/src/select.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 994b21ff21..4fe087f3fd 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -789,6 +789,16 @@ impl SelectionTool { } } + /// Notes where a press or a drag last held the pointer, and says whether a release lands + /// somewhere else. + fn note_held_at(&mut self, ev: &PointerEvent) -> bool { + let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos); + if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { + self.held_at = Some(ev.pos); + } + released_away + } + /// The pointer loaded with the text of area type or type on a path `from` ([`State::Loaded`]): /// a press starts placing it, and its release threads it (`text.thread.add`), into a frame put /// `before` `from` or after it. None when `from` can no longer thread: the press is an @@ -1044,10 +1054,7 @@ impl Tool for SelectionTool { /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); - let released_away = ev.kind == PointerKind::Up && self.held_at != Some(ev.pos); - if matches!(ev.kind, PointerKind::Down | PointerKind::Drag) { - self.held_at = Some(ev.pos); - } + let released_away = self.note_held_at(ev); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); self.alt_hover = hovering && ev.mods.alt; From 62ff5832d4e87f251cb46ed5b90620d4b8e48ff0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 10:52:35 -0800 Subject: [PATCH 010/126] Tests: set the retype tests' type in a bundled font Outlined text without a font took the system's default face, so a near match of round glyphs depended on the machine's installed fonts. The outlined helper now sets such text in Source Sans 3. --- crates/engine/src/cmd/retype_tests.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 5c043a9e6f..48bf680e75 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -10,7 +10,13 @@ fn session() -> Session { } /// Point text, outlined: the id of the outlines' group. -fn outlined(s: &mut Session, p: serde_json::Value) -> u64 { +fn outlined(s: &mut Session, mut p: serde_json::Value) -> u64 { + // A text without a font is set in the system's default face, which differs from machine to + // machine and decides which glyphs a near match can tell apart. + if p.get("font").is_none() { + p["font"] = json!("Source Sans 3"); + p["style"] = json!("Regular"); + } let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [id]})).unwrap(); s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap() From 744f32977a75f5b0da273f9f207d2ea66c71b1be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 11:52:00 -0800 Subject: [PATCH 011/126] Retype: near-only glyphs stay out of exact matching, and a glyph must paint the shape's area Glyphs indexed only for near matching no longer take part in exact matching, so a curve split in two is no exact match at tolerance 0. Each pose of a match reports its own residual. A near match spends its comparison allowance from the shared budget in one step and returns what it leaves, and does no sampling once the budget is spent. A glyph replaces a filled shape only when it paints the area the shape paints under the shape's fill rule. The docs define the tolerance by the outline spread and separate the no-conversion error from the unmatched list. --- crates/engine/src/cmd/retype.rs | 41 ++++-- crates/text/src/retype.rs | 233 ++++++++++++++++++++++++++++++-- docs/mcp.md | 7 +- docs/type-parity.md | 2 +- 4 files changed, 260 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 253edcd3a3..7daa1d424c 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -26,6 +26,7 @@ use std::sync::Arc; use kurbo::{BezPath, Point, Vec2}; use serde_json::{Value, json}; use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::FillRule; use vectorcraft_text::FontDb; use vectorcraft_text::retype::{GlyphMatch, RetypeIndex}; @@ -45,7 +46,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's size, is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions; with a tolerance, within it); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape matches, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -64,6 +65,10 @@ struct Piece { /// art must stay painted after it: the line ends here. after_barrier: bool, path: BezPath, + /// The shape is filled by the nonzero rule, not the even-odd rule. + nonzero: bool, + /// The shape has a visible fill: a shape that only has a stroke paints no area to compare. + filled: bool, appearance: Appearance, /// The shape's own transparency, which the new type takes. opacity: f32, @@ -87,11 +92,13 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t *barrier = true; return; } - let piece = |path: BezPath, after_barrier: bool| Piece { + let piece = |path: BezPath, after_barrier: bool, rule: FillRule| Piece { id: n.id, parent, after_barrier, path, + nonzero: rule == FillRule::NonZero, + filled: n.appearance.fill().is_some_and(|f| f.visible && !f.paint.is_none()), appearance: (*n.appearance).clone(), opacity: n.opacity, blend: n.blend, @@ -104,8 +111,10 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t } } // Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one. - NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))), - NodeKind::Compound { children, .. } => { + NodeKind::Path { path, rule, clipping: false, guide: false, .. } if path.is_closed() => { + out.push(piece(path.to_bezpath(), std::mem::take(barrier), *rule)) + } + NodeKind::Compound { children, rule } => { let mut path = BezPath::new(); for c in children { match &c.kind { @@ -117,7 +126,7 @@ fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, t } } } - out.push(piece(path, std::mem::take(barrier))); + out.push(piece(path, std::mem::take(barrier), *rule)); } // Live type, images, clip groups and the rest stay, and the type after them stays after them. _ => *barrier = true, @@ -692,13 +701,27 @@ fn retype(s: &mut Session, p: &Value) -> Result { RetypeIndex::build_near(db, candidate_faces(db, d, &fonts), &wanted, &near_wanted) }; // Exact matches first; near ones, when allowed, only for a path with none. - let find = |path: &BezPath, part: bool, near: bool| { - let exact = if part { index.matches_either_way(path) } else { index.all_matches(path) }; - if exact.is_empty() && near { index.near_matches(path, tolerance) } else { exact } + // With a visible fill, a glyph is kept only when it paints the area the shape paints under + // the shape's fill rule (`fill` is `Some(nonzero)`). + let find = |path: &BezPath, part: bool, near: bool, fill: Option| { + let painted = |ms: Vec, tol: f64| -> Vec { + match fill { + Some(nonzero) => ms.iter().filter_map(|m| index.painted_agrees(m, path, nonzero, tol)).collect(), + None => ms, + } + }; + let exact = painted(if part { index.matches_either_way(path) } else { index.all_matches(path) }, 0.0); + if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } }; // Each shape's parts (one, unless it holds several glyphs), each with its candidates. let found: Vec>> = - pieces.iter().zip(&groups).map(|(pc, g)| if pc.keeps_outline { vec![] } else { parts(&pc.path, g, &find) }).collect(); + pieces + .iter() + .zip(&groups) + .map(|(pc, g)| { + if pc.keeps_outline { vec![] } else { parts(&pc.path, g, &|p, part, near| find(p, part, near, pc.filled.then_some(pc.nonzero))) } + }) + .collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 9fd06a8f95..27c3b47313 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -106,6 +106,11 @@ pub struct GlyphMatch { pub contours: usize, /// Other poses the glyph fits the shape in equally (a glyph that looks the same turned). pub alts: Vec, + /// The leftover distance of each of [`Self::alts`], in the same order. + pub alt_residuals: Vec, + /// The leftover distance of the glyph's own pose: [`Self::residual`] is the least over all its + /// poses, which orders the matches. + pub pose_residual: f64, } /// Where and how a glyph lies: its size, turn and origin. @@ -134,11 +139,14 @@ impl GlyphMatch { /// This match in each pose it fits: its own first, then [`Self::alts`]. pub fn poses(&self) -> impl Iterator + '_ { - let own = Pose { scale: self.scale, angle: self.angle, origin: self.origin }; - std::iter::once(own).chain(self.alts.iter().copied()).map(move |p| GlyphMatch { + let own = (Pose { scale: self.scale, angle: self.angle, origin: self.origin }, self.pose_residual); + let alts = self.alts.iter().copied().zip(self.alt_residuals.iter().copied().chain(std::iter::repeat(self.residual))); + std::iter::once(own).chain(alts).map(move |(p, residual)| GlyphMatch { scale: p.scale, angle: p.angle, origin: p.origin, + residual, + pose_residual: residual, ..self.clone() }) } @@ -165,6 +173,9 @@ struct Entry { sig: Signature, /// The glyph's outline in font units, for the whole-outline check. outline: BezPath, + /// Whether the glyph was indexed for its exact key: only these take part in exact matching, + /// and the ones indexed only for near matching ([`RetypeIndex::near_matches`]) do not. + exact: bool, } /// The glyphs of a set of faces, ready to match shapes against. @@ -174,6 +185,8 @@ pub struct RetypeIndex { entries: Vec, /// Entry indices by contour count, sorted by invariant. buckets: HashMap>, + /// Entry indices by face id and glyph id. + by_glyph: HashMap<(u32, u32), usize>, /// The point comparisons [`Self::near_matches`] may still make, over every shape. near_work: AtomicU64, } @@ -241,7 +254,7 @@ impl RetypeIndex { if keys.contains(&key) { let outline = db.outline_uncached(face, gid); if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline }); + entries.push(Entry { face: fi, gid, ch, sig, outline, exact: true }); } continue; } @@ -264,7 +277,7 @@ impl RetypeIndex { break 'faces; } if let Some(sig) = signatures(&outline, false).into_iter().next() { - entries.push(Entry { face: fi, gid, ch, sig, outline }); + entries.push(Entry { face: fi, gid, ch, sig, outline, exact: false }); } } } @@ -278,7 +291,39 @@ impl RetypeIndex { x.total_cmp(&y) }); } - RetypeIndex { faces: kept, entries, buckets, near_work: AtomicU64::new(NEAR_WORK) } + let by_glyph = entries.iter().enumerate().filter_map(|(i, e)| Some(((kept.get(e.face)?.id(), e.gid), i))).collect(); + RetypeIndex { faces: kept, entries, buckets, by_glyph, near_work: AtomicU64::new(NEAR_WORK) } + } + + /// `m` kept to the poses in which the glyph paints the area `shape` paints, the shape filled + /// by the nonzero rule when `nonzero` is set and by the even-odd rule otherwise, the glyph + /// filled by the nonzero rule. Two outlines on each other can paint different areas: a ring + /// whose inner contour runs the same way as its outer one, filled by the nonzero rule, has no + /// hole. Probes lie on both sides of the shape's outline, left out where either outline is + /// within reach of them. `tolerance` is the one `m` was found with (0 for an exact match). The + /// first pose that agrees comes first; `None` when none does. + pub fn painted_agrees(&self, m: &GlyphMatch, shape: &BezPath, nonzero: bool, tolerance: f64) -> Option { + let Some(e) = self.by_glyph.get(&(m.face.id(), m.gid)).and_then(|i| self.entries.get(*i)) else { return Some(m.clone()) }; + let bb = shape.bounding_box(); + let tol = bb.width().hypot(bb.height()) * 0.5 * OUTLINE_TOLERANCE.max(3.0 * tolerance.clamp(0.0, MAX_TOLERANCE)); + let mut agreeing = m.poses().filter(|p| { + let onto = Affine::new([ + p.scale * p.angle.cos(), + p.scale * p.angle.sin(), + -p.scale * p.angle.sin(), + p.scale * p.angle.cos(), + p.origin.x, + p.origin.y, + ]); + paints_alike(shape, nonzero, &(onto * e.outline.clone()), tol) + }); + let first = agreeing.next()?; + let rest: Vec = agreeing.collect(); + Some(GlyphMatch { + alts: rest.iter().map(|p| Pose { scale: p.scale, angle: p.angle, origin: p.origin }).collect(), + alt_residuals: rest.iter().map(|p| p.pose_residual).collect(), + ..first + }) } /// The faces indexed. @@ -341,6 +386,9 @@ impl RetypeIndex { if e.sig.invariant > hi { break; } + if !e.exact { + continue; + } let Some(face) = self.faces.get(e.face) else { continue }; // Each reading of the shape (its tied starting corners) that fits the glyph is a pose. let mut poses: Vec<(Pose, f64)> = vec![]; @@ -367,7 +415,7 @@ impl RetypeIndex { } // The upright-most pose first. poses.sort_by(|a, b| wrapped(a.0.angle).abs().total_cmp(&wrapped(b.0.angle).abs())); - let Some(((pose, _), rest)) = poses.split_first() else { continue }; + let Some(((pose, own_residual), rest)) = poses.split_first() else { continue }; let residual = poses.iter().map(|(_, r)| *r).fold(f64::INFINITY, f64::min); let m = GlyphMatch { face: face.clone(), @@ -380,6 +428,8 @@ impl RetypeIndex { exact: true, contours: e.sig.contours, alts: rest.iter().map(|(p, _)| *p).collect(), + alt_residuals: rest.iter().map(|(_, r)| *r).collect(), + pose_residual: *own_residual, }; out.push((e.face, m)); } @@ -408,6 +458,10 @@ impl RetypeIndex { return vec![]; } let tolerance = tolerance.min(MAX_TOLERANCE); + // With no comparisons left, no shape is sampled or ranked. + if self.near_work.load(Ordering::Acquire) == 0 { + return vec![]; + } let Some(s) = near_signature(shape) else { return vec![] }; let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); @@ -433,9 +487,16 @@ impl RetypeIndex { list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi).map(|e| (apart(e), e)).collect(); near.sort_by(|a, b| a.0.total_cmp(&b.0)); near.truncate(NEAR_FITS); - let total = self.near_work.load(Ordering::Relaxed); - let mut work = total.min(NEAR_SHAPE_WORK); - let given = work; + // This call's allowance comes out of the index's budget in one step, so calls that overlap + // never spend the same comparisons; what it leaves unspent goes back afterward. + let mut seen = self.near_work.load(Ordering::Acquire); + let mut work = loop { + let take = seen.min(NEAR_SHAPE_WORK); + match self.near_work.compare_exchange_weak(seen, seen - take, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => break take, + Err(now) => seen = now, + } + }; for (_, e) in near { if work == 0 { break; @@ -449,6 +510,7 @@ impl RetypeIndex { let mut poses = fits.into_iter().filter(|f| f.1 <= tolerance).filter_map(|(z, r)| Some((near_pose(e, &s, z, flat, tol)?, r))).take(MAX_NEAR_POSES); let Some((pose, residual)) = poses.next() else { continue }; + let rest: Vec<(Pose, f64)> = poses.collect(); let m = GlyphMatch { face: face.clone(), gid: e.gid, @@ -459,11 +521,13 @@ impl RetypeIndex { residual, exact: false, contours: e.sig.contours, - alts: poses.map(|(p, _)| p).collect(), + alts: rest.iter().map(|(p, _)| *p).collect(), + alt_residuals: rest.iter().map(|(_, r)| *r).collect(), + pose_residual: residual, }; out.push((e.face, m)); } - self.near_work.store(total.saturating_sub(given - work), Ordering::Relaxed); + self.near_work.fetch_add(work, Ordering::AcqRel); let upright = |m: &GlyphMatch| wrapped(m.angle).abs() >= 1e-3; out.sort_by(|a, b| { upright(&a.1).cmp(&upright(&b.1)).then(a.1.residual.total_cmp(&b.1.residual)).then(a.0.cmp(&b.0)).then(a.1.ch.cmp(&b.1.ch)) @@ -1049,6 +1113,42 @@ impl Flat { } } +/// Shape segments [`paints_alike`] probes beside, at most. +const MAX_FILL_PROBES: usize = 512; + +/// Do `shape` (filled by the nonzero rule when `nonzero` is set, else by the even-odd rule) and +/// `glyph` (filled by the nonzero rule), whose outlines lie within `tol` of each other, paint the +/// same area? Each probe lies `1.5 tol` or `3 tol` to a side of the middle of a segment of the shape's +/// outline; one within `tol` of either outline is skipped, so a region narrower than that is not +/// probed. `true` when an outline is too large to probe. +fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bool { + let (Some(fs), Some(fg)) = (Flat::new(shape, tol), Flat::new(glyph, tol)) else { return true }; + let step = fs.segs.len().div_ceil(MAX_FILL_PROBES).max(1); + for (s, e) in fs.segs.iter().step_by(step) { + let d = *e - *s; + let len = d.hypot(); + if len <= 0.0 || !len.is_finite() { + continue; + } + let mid = s.midpoint(*e); + // The nearer probes reach counters and gaps too narrow for the farther ones. + for reach in [1.5, 3.0] { + let side = kurbo::Vec2::new(-d.y, d.x) * (reach * tol / len); + for q in [mid + side, mid - side] { + if fs.near(q) || fg.near(q) { + continue; + } + let w = shape.winding(q); + let painted = if nonzero { w != 0 } else { w.rem_euclid(2) == 1 }; + if painted != (glyph.winding(q) != 0) { + return false; + } + } + } + } + true +} + /// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within /// `tol` of the other? `false` when either is too large to check. #[cfg(test)] @@ -1671,6 +1771,117 @@ mod tests { assert!(found.iter().any(|c| matches!(c, 'o' | 'ο')), "{found:?}"); } + /// `p` with its first curve split in two at its middle: the same outline with another key. + fn first_curve_split(p: &BezPath) -> BezPath { + let mut out = BezPath::new(); + let (mut last, mut done) = (Point::ZERO, false); + for el in p.elements() { + match *el { + PathEl::CurveTo(a, b, c) if !done => { + let (x, y) = kurbo::CubicBez::new(last, a, b, c).subdivide(); + out.curve_to(x.p1, x.p2, x.p3); + out.curve_to(y.p1, y.p2, y.p3); + done = true; + last = c; + } + PathEl::QuadTo(a, c) if !done => { + let (x, y) = kurbo::QuadBez::new(last, a, c).subdivide(); + out.quad_to(x.p1, x.p2); + out.quad_to(y.p1, y.p2); + done = true; + last = c; + } + e => { + out.push(e); + if let PathEl::MoveTo(q) | PathEl::LineTo(q) | PathEl::QuadTo(_, q) | PathEl::CurveTo(_, _, q) = e { + last = q; + } + } + } + } + out + } + + #[test] + fn a_glyph_indexed_only_for_near_matching_is_no_exact_match() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let split = first_curve_split(&db.outline_uncached(&face, gid)); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * split; + assert_ne!(shape_key(&shape), shape_key(&(Affine::scale(0.04) * db.outline_uncached(&face, gid))), "another key"); + let keys: BTreeSet = shape_key(&shape).into_iter().collect(); + let index = RetypeIndex::build_near(db, [face], &keys, &[near_key(&shape).unwrap()]); + assert!(index.all_matches(&shape).is_empty(), "exact matching sees only the glyphs of the exact keys"); + assert!(index.matches_either_way(&shape).is_empty()); + assert!(index.near_matches(&shape, 0.02).iter().any(|m| m.ch == 'o')); + } + + #[test] + fn each_pose_of_a_match_reports_its_own_residual() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let turn = std::f64::consts::FRAC_PI_2; + let m = GlyphMatch { + face, + gid: 1, + ch: 'o', + scale: 1.0, + angle: 0.0, + origin: Point::ZERO, + residual: 0.010, + exact: false, + contours: 1, + alts: vec![Pose { scale: 1.0, angle: turn, origin: Point::ZERO }], + alt_residuals: vec![0.010], + pose_residual: 0.014, + }; + let seen: Vec<(f64, f64)> = m.poses().map(|p| (p.angle, p.residual)).collect(); + assert_eq!(seen, vec![(0.0, 0.014), (turn, 0.010)]); + } + + #[test] + fn a_ring_whose_contours_run_one_way_paints_no_hole() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let ring = db.outline_uncached(&face, gid); + let els = ring.elements(); + let second = els.iter().rposition(|e| matches!(e, PathEl::MoveTo(_))).unwrap(); + let (mut outer, mut inner) = (BezPath::new(), BezPath::new()); + outer.extend(els[..second].iter().copied()); + inner.extend(els[second..].iter().copied()); + let mut same_way = outer.clone(); + same_way.extend(inner.reverse_subpaths().iter()); + let (ring, same_way) = + (Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * ring, Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * same_way); + let keys: BTreeSet = shape_key(&ring).into_iter().collect(); + let index = RetypeIndex::build_near(db, [face], &keys, &[near_key(&same_way).unwrap()]); + // Near matching reads each contour in either direction, so the outline matches the glyph's: + // only what it paints tells them apart. + let found = index.near_matches(&same_way, 0.02); + assert!(found.iter().any(|m| m.ch == 'o'), "the outline matches"); + assert!(found.iter().all(|m| index.painted_agrees(m, &same_way, true, 0.02).is_none()), "nonzero paints the counter"); + assert!(found.iter().any(|m| index.painted_agrees(m, &same_way, false, 0.02).is_some()), "even-odd leaves it empty"); + let found = index.all_matches(&ring); + assert!(found.iter().any(|m| index.painted_agrees(m, &ring, true, 0.0).is_some()), "the glyph's own windings paint a ring"); + } + + #[test] + fn near_matching_with_no_work_left_returns_nothing() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * simplified(&db.outline_uncached(&face, gid), 4.0); + let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]); + assert!(!index.near_matches(&shape, 0.02).is_empty()); + let after = index.near_work.load(Ordering::Acquire); + assert!((NEAR_WORK - NEAR_SHAPE_WORK..NEAR_WORK).contains(&after), "one allowance at most: {after}"); + index.near_work.store(0, Ordering::Release); + assert!(index.near_matches(&shape, 0.02).is_empty()); + assert_eq!(index.near_work.load(Ordering::Acquire), 0); + } + #[test] fn a_round_glyph_with_an_off_centre_counter_near_matches_at_its_turn() { // A round outer contour fits the shape at every turn; only the counter, off the centre, diff --git a/docs/mcp.md b/docs/mcp.md index 570e3bb84c..9fd086b690 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10946,7 +10946,8 @@ glyph. `type.retype` (Type › Retype) turns outlined glyphs back into point text. By default a shape must be exactly a glyph of an available font. With `tolerance` (0 to 0.05), a shape of at most 8 contours that is no glyph exactly becomes the -glyph it is closest to when its leftover distance from that glyph, relative to the shape's size, is at most the +glyph it is closest to when its leftover distance from that glyph, relative to the shape's outline spread (the root +mean square distance of its sampled outline points from their center), is at most the tolerance: an outline simplified, a curve split in two, or contours in another order, start or direction. The tolerance and this measure are VectorCraft's own. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is @@ -10958,7 +10959,9 @@ remaining groups can still all be matched, so an i's stem and dot become one i. way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in -`unmatched`. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours +`unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A +glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule +whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left diff --git a/docs/type-parity.md b/docs/type-parity.md index bfd821ee10..b84bdc34e1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours that are nearly a glyph (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, tracking, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, tracking, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From bba03f1e2b308ad2a237ac53e35c84e73e50956c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 12:05:41 -0800 Subject: [PATCH 012/126] Retype: an explicit null for fonts or tolerance is an invalid parameter --- crates/engine/src/cmd/retype.rs | 4 ++-- crates/engine/src/cmd/retype_tests.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 7daa1d424c..d7381200f9 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -648,14 +648,14 @@ fn lookup_keys<'a>( fn retype(s: &mut Session, p: &Value) -> Result { const C: &str = "type.retype"; let fonts: Vec = match p.get("fonts") { - None | Some(Value::Null) => vec![], + None => vec![], Some(Value::Array(a)) => { a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? } Some(_) => return Err(bad(C, "fonts must be a list of family names")), }; let tolerance = match p.get("tolerance") { - None | Some(Value::Null) => 0.0, + None => 0.0, Some(v) => match v.as_f64() { Some(t) if (0.0..=vectorcraft_text::retype::MAX_TOLERANCE).contains(&t) => t, _ => return Err(bad(C, "tolerance must be a number from 0 to 0.05")), diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 48bf680e75..0a99f20924 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -90,7 +90,7 @@ fn a_drawn_shape_is_reported_and_left_alone() { let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40})); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let before = s.doc().unwrap().doc.clone(); - for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] { + for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"}), json!(null)] { let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string(); assert!(e.contains("fonts must be a list of family names"), "{e}"); } @@ -596,7 +596,7 @@ fn simplified_outlines_retype_only_with_a_tolerance_and_report_their_score() { let before = s.doc().unwrap().doc.clone(); let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); assert!(e.contains("no selected shape matches"), "no exact match: {e}"); - for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true)] { + for bad in [json!(-0.01), json!(0.06), json!("0.02"), json!(true), json!(null)] { let e = s.execute("type.retype", &json!({"tolerance": bad})).unwrap_err().to_string(); assert!(e.contains("tolerance must be a number from 0 to 0.05"), "{e}"); } From 782b6782ffb9609728b7d116540f992716e91401 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 13:29:45 -0800 Subject: [PATCH 013/126] Retype: a split compound must paint what the compound paints, and counters too narrow to probe stay outlines The parts of a split compound path are set as separate glyphs, so an overlap that the compound's fill rule leaves unpainted would come out painted. A split whose parts paint differently from the compound, whose combined outline is too large to probe, or whose parts' boxes overlap in a strip too thin to probe, stays an outline. A counter narrower than three times the outline tolerance cannot be checked by the fill probes, so the shape stays an outline. The params text says a command errors when no shape becomes type. --- crates/engine/src/cmd/retype.rs | 41 ++++++--- crates/engine/src/cmd/retype_tests.rs | 39 +++++++- crates/text/src/retype.rs | 128 +++++++++++++++++++++++++- docs/mcp.md | 6 +- 4 files changed, 193 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index d7381200f9..a7fbc31754 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape matches, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a contour narrower than three times the outline tolerance, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size, score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -533,13 +533,14 @@ fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { /// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make /// Compound Path may have turned the other way round, and its `near` flag allows near matches. /// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then -/// its groups nearly. -fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bool) -> Vec) -> Vec> { +/// its groups nearly. A split of several parts is kept only when `together` accepts the paths of +/// its runs (the parts, set one beside another, paint what the shape paints). +fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bool) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { let whole = find(path, false, false); if !whole.is_empty() { return vec![whole]; } - let exact = split_parts(groups, &|run| find(run, true, false)); + let exact = split_parts(groups, &|run| find(run, true, false), together); if !exact.is_empty() { return exact; } @@ -547,12 +548,13 @@ fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bo if !whole.is_empty() { return vec![whole]; } - split_parts(groups, &|run| find(run, true, true)) + split_parts(groups, &|run| find(run, true, true), together) } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for -/// no groups and when the groups cannot all be matched. -fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec) -> Vec> { +/// no groups, when the groups cannot all be matched and when `together` rejects the runs of a split +/// of several parts. +fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { if groups.is_empty() { return vec![]; } @@ -578,12 +580,17 @@ fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec) -> Vec< } } let mut out = vec![]; + let mut runs = vec![]; let mut i = 0; while i < g { let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; out.push(cands); + runs.push(groups.get(i..i + n).map(joined).unwrap_or_default()); i += n; } + if out.len() > 1 && !together(&runs) { + return vec![]; + } out } @@ -714,14 +721,18 @@ fn retype(s: &mut Session, p: &Value) -> Result { if exact.is_empty() && near { painted(index.near_matches(path, tolerance), tolerance) } else { exact } }; // Each shape's parts (one, unless it holds several glyphs), each with its candidates. - let found: Vec>> = - pieces - .iter() - .zip(&groups) - .map(|(pc, g)| { - if pc.keeps_outline { vec![] } else { parts(&pc.path, g, &|p, part, near| find(p, part, near, pc.filled.then_some(pc.nonzero))) } - }) - .collect(); + let found: Vec>> = pieces + .iter() + .zip(&groups) + .map(|(pc, g)| { + if pc.keeps_outline { + return vec![]; + } + let fill = pc.filled.then_some(pc.nonzero); + let together = |runs: &[BezPath]| fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tolerance)); + parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) + }) + .collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as // the glyphs around it. let mut votes: Vec<(u32, usize)> = vec![]; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 0a99f20924..fc2817fe7c 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -850,6 +850,35 @@ fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { assert!(s.doc().unwrap().doc == before, "nothing changes"); } +#[test] +fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { + let mut s = session(); + // Two o's moved onto each other and made into one compound path: the even-odd rule leaves + // the overlap unpainted, and two glyphs set side by side would paint it. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40})); + let kids = children_of(&s, g); + s.execute("object.move", &json!({"ids": [kids[1]], "dx": -9, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = match s.execute("type.retype", &json!({})) { + Ok(r) => panic!("the overlapping o's became type: {r}"), + Err(e) => e.to_string(), + }; + assert!(e.contains("(1 checked)"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); +} + +#[test] +fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { + let mut s = session(); + let c = one_compound(&mut s, "oo"); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["oo"]), "{r}"); +} + #[test] fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let mut s = session(); @@ -896,13 +925,15 @@ fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { } }; let groups = all_groups(&p); - assert_eq!(super::parts(&p, &groups, &find), vec![vec!["A"], vec!["BC"]]); + assert_eq!(super::parts(&p, &groups, &find, &|_| true), vec![vec!["A"], vec!["BC"]]); + // A split the parts' paint does not allow is dropped. + assert!(super::parts(&p, &groups, &find, &|_| false).is_empty()); // With no way to match every group, nothing. let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { let b = path.bounding_box(); if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] } }; - assert!(super::parts(&p, &groups, &none).is_empty()); + assert!(super::parts(&p, &groups, &none, &|_| true).is_empty()); } /// `path`'s contour groups, with no limit on the contours grouped. @@ -929,7 +960,7 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { } }; let groups = all_groups(&p); - assert_eq!(super::parts(&p, &groups, &find), vec![vec!["period"], vec!["period"]]); + assert_eq!(super::parts(&p, &groups, &find, &|_| true), vec![vec!["period"], vec!["period"]]); // When the parts match only nearly too, the whole near match comes first. let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { let b = path.bounding_box(); @@ -939,7 +970,7 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { _ => vec![], } }; - assert_eq!(super::parts(&p, &groups, &near_only), vec![vec!["dieresis"]]); + assert_eq!(super::parts(&p, &groups, &near_only, &|_| true), vec![vec!["dieresis"]]); } #[test] diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 27c3b47313..8a65126569 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1120,8 +1120,13 @@ const MAX_FILL_PROBES: usize = 512; /// `glyph` (filled by the nonzero rule), whose outlines lie within `tol` of each other, paint the /// same area? Each probe lies `1.5 tol` or `3 tol` to a side of the middle of a segment of the shape's /// outline; one within `tol` of either outline is skipped, so a region narrower than that is not -/// probed. `true` when an outline is too large to probe. +/// probed. `false` when a contour of the shape is narrower than `3 tol` on its shorter side, since +/// the probes cannot then tell whether the area inside it is painted; `true` when an outline is too +/// large to probe. fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bool { + if narrow_contour(shape, 3.0 * tol) { + return false; + } let (Some(fs), Some(fg)) = (Flat::new(shape, tol), Flat::new(glyph, tol)) else { return true }; let step = fs.segs.len().div_ceil(MAX_FILL_PROBES).max(1); for (s, e) in fs.segs.iter().step_by(step) { @@ -1149,6 +1154,81 @@ fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bo true } +/// Does `path` have a contour no wider than `width` on its shorter side that lies inside another +/// contour (a counter)? +fn narrow_contour(path: &BezPath, width: f64) -> bool { + let mut all: Vec = vec![]; + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + all.push(BezPath::new()); + } + if let Some(cur) = all.last_mut() { + cur.push(*el); + } + } + all.iter().enumerate().any(|(i, c)| { + let Some(PathEl::MoveTo(at)) = c.elements().first().copied() else { return false }; + let bb = c.bounding_box(); + bb.width().min(bb.height()) <= width && all.iter().enumerate().any(|(j, o)| j != i && o.winding(at) != 0) + }) +} + +/// Do `parts` (the runs of contours a compound path `shape` is split into, each already checked +/// by [`RetypeIndex::painted_agrees`] on its own) paint together the area `shape` paints, the +/// shape filled by the nonzero rule when `nonzero` is set and by the even-odd rule otherwise? Each +/// part is read by the same rule, and the glyphs that replace them are set one beside another, so +/// an overlap that the shape's rule cancels would come out painted. Probes lie on both sides of +/// every part's outline, as in [`RetypeIndex::painted_agrees`]; `tolerance` is the one the parts +/// were found with (0 for exact matches). `false` when an outline is too large to probe, and when +/// two parts' boxes overlap in a strip no wider than `3 tol`, which the probes cannot see into. +pub fn parts_paint_alike(shape: &BezPath, parts: &[BezPath], nonzero: bool, tolerance: f64) -> bool { + let bb = shape.bounding_box(); + let tol = bb.width().hypot(bb.height()) * 0.5 * OUTLINE_TOLERANCE.max(3.0 * tolerance.clamp(0.0, MAX_TOLERANCE)); + let painted = |p: &BezPath, q: Point| { + let w = p.winding(q); + if nonzero { w != 0 } else { w.rem_euclid(2) == 1 } + }; + let mut flats = vec![]; + for p in parts.iter().chain(std::iter::once(shape)) { + let Some(f) = Flat::new(p, tol) else { return false }; + flats.push(f); + } + // Two parts whose boxes overlap in a strip too thin to probe cannot be told from parts that + // overlap in their paint. + let boxes: Vec = parts.iter().map(Shape::bounding_box).collect(); + for (i, a) in boxes.iter().enumerate() { + for b in boxes.iter().skip(i + 1) { + let both = a.intersect(*b); + if both.area() > 0.0 && both.width().min(both.height()) <= 3.0 * tol { + return false; + } + } + } + for own in flats.iter().take(parts.len()) { + let step = own.segs.len().div_ceil(MAX_FILL_PROBES).max(1); + for (s, e) in own.segs.iter().step_by(step) { + let d = *e - *s; + let len = d.hypot(); + if len <= 0.0 || !len.is_finite() { + continue; + } + let mid = s.midpoint(*e); + for reach in [1.5, 3.0] { + let side = kurbo::Vec2::new(-d.y, d.x) * (reach * tol / len); + for q in [mid + side, mid - side] { + if flats.iter().any(|f| f.near(q)) { + continue; + } + if painted(shape, q) != parts.iter().any(|o| painted(o, q)) { + return false; + } + } + } + } + } + true +} + /// Do outlines `a` and `b` (in one space) lie on each other: every point of each, flattened, within /// `tol` of the other? `false` when either is too large to check. #[cfg(test)] @@ -1867,6 +1947,52 @@ mod tests { assert!(found.iter().any(|m| index.painted_agrees(m, &ring, true, 0.0).is_some()), "the glyph's own windings paint a ring"); } + #[test] + fn a_counter_too_narrow_to_probe_does_not_count_as_agreeing() { + let square = |x0: f64, y0: f64, x1: f64, y1: f64, back: bool| { + let p = kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + if back { p.reverse_subpaths() } else { p } + }; + // A 100 by 100 square with a 10 by 10 counter: the shape's counter runs the way its outer + // contour does (filled by the nonzero rule), the glyph's runs the other way (a hole). + let mut filled = square(0.0, 0.0, 100.0, 100.0, false); + filled.extend(square(45.0, 45.0, 55.0, 55.0, false).iter()); + let mut holed = square(0.0, 0.0, 100.0, 100.0, false); + holed.extend(square(45.0, 45.0, 55.0, 55.0, true).iter()); + let tol = 100.0_f64.hypot(100.0) * 0.5 * 3.0 * MAX_TOLERANCE; + assert!(!paints_alike(&filled, true, &holed, tol), "no probe can see the counter"); + // A counter wide enough to probe is told apart as before. + let mut wide = square(0.0, 0.0, 100.0, 100.0, false); + wide.extend(square(10.0, 10.0, 90.0, 90.0, false).iter()); + let mut wide_hole = square(0.0, 0.0, 100.0, 100.0, false); + wide_hole.extend(square(10.0, 10.0, 90.0, 90.0, true).iter()); + assert!(!paints_alike(&wide, true, &wide_hole, 1.0)); + assert!(paints_alike(&wide_hole, true, &wide_hole, 1.0)); + } + + #[test] + fn parts_that_overlap_under_the_even_odd_rule_do_not_paint_the_shape() { + let square = |x0: f64, y0: f64, x1: f64, y1: f64| kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + let (a, b) = (square(0.0, 0.0, 60.0, 60.0), square(40.0, 0.0, 100.0, 60.0)); + let mut both = a.clone(); + both.extend(b.iter()); + assert!(!parts_paint_alike(&both, &[a.clone(), b.clone()], false, 0.0), "the overlap is a hole in the shape"); + assert!(parts_paint_alike(&both, &[a.clone(), b.clone()], true, 0.0), "the nonzero rule paints it"); + // Windings that cancel under the nonzero rule leave the overlap unpainted too. + let mut turned = a.clone(); + turned.extend(b.reverse_subpaths().iter()); + assert!(!parts_paint_alike(&turned, &[a.clone(), b.reverse_subpaths()], true, 0.0)); + // An overlap too thin for the probes to land in is not taken for none. + let thin = square(59.9, 0.0, 100.0, 60.0); + let mut strip = a.clone(); + strip.extend(thin.iter()); + assert!(!parts_paint_alike(&strip, &[a.clone(), thin], false, 0.0)); + let apart = square(80.0, 0.0, 140.0, 60.0); + let mut aside = a.clone(); + aside.extend(apart.iter()); + assert!(parts_paint_alike(&aside, &[a, apart], false, 0.0)); + } + #[test] fn near_matching_with_no_work_left_returns_nothing() { let db = FontDb::global(); diff --git a/docs/mcp.md b/docs/mcp.md index 9fd086b690..4de3405a7b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10961,7 +10961,11 @@ first, then exact matches of its groups, then near matches of the whole shape, t compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in `unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule -whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours +whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. A shape with a contour narrower than three times the +outline tolerance on its shorter side cannot be checked this way and stays an outline: at `tolerance` 0.05, a +counter 10 units wide in a 100 by 100 shape. The glyphs of a compound path that splits into several are set one beside +another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each +other under the even-odd rule) stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left From 1f5cee040e5180a97ceab8db8e42b5aa35b79726 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 15:48:39 -0800 Subject: [PATCH 014/126] Retype: a long evenly tracked run after irregular gaps keeps its tracking After a split, the tracking of the rest of the line was measured over the whole rest, and each measure took six times the rest's glyphs from a shared budget. A few irregular gaps early in a long line used that budget up, so the evenly tracked run after them was not measured and split into single-glyph objects. The tracking of the rest is now measured from its first 32 glyphs, and the glyphs after them follow at that tracking, so each split costs the same however long the rest is. When the tracking leaves a space under half its advance, the whole rest is still measured while the budget lasts, since only the kerning a space breaks shows where such spaces are. --- crates/engine/src/cmd/retype.rs | 48 +++++++++++++++++++----- crates/engine/src/cmd/retype_tests.rs | 53 +++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 0e31d5632a..5d6c8ab9c4 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -611,6 +611,9 @@ fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option, system_layout: bool, unmatched: &mut Vec) // leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to // rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers // one measure of each whole line, as `retype` gives the first, and the glyph checks' budget. - // The glyphs measured again after splits are limited apart from it, at six times each rest's - // glyphs from half as much again as the glyph checks' budget. + // The glyphs measured again after splits are limited apart from it, at six times the glyphs + // each measure reads from half as much again as the glyph checks' budget. let mut remeasured = budget.saturating_add(budget / 2); let mut track_budget = lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add); @@ -671,20 +674,47 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) // rest takes the tracking its own glyphs are spaced by, while the budget for // measuring it lasts and when type draws its first glyph as it was, followed by the // next two (else that glyph splits off first, and the tracking is measured from the - // next one); past it, an untracked line's rest keeps its text as it is. + // next one); past it, an untracked line's rest keeps its text as it is. The tracking + // is measured from the rest's first [`MEASURE_SPAN`] glyphs at most, and the glyphs + // after them follow at that tracking, so each split costs the same however long the + // rest is, and splits at irregular gaps early in a line leave the budget for a long + // evenly tracked run after them. Some(k) => { let k = k.max(1); - // A measure takes at least six times the rest's glyphs from each budget. - let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6); + let span = (n - k).min(MEASURE_SPAN); + // A measure takes at least six times the glyphs it reads from each budget. + let measurable = n - k >= 3 && remeasured >= span.saturating_mul(6) && track_budget >= span.saturating_mul(6); let first_drawn = measurable && { budget = budget.saturating_sub(3); l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) }; let rest = if first_drawn { - // Rebuilding the rest for the measure takes its glyphs from the budget. - remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); - track_budget = track_budget.saturating_sub(n - k); - l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) + // Rebuilding the glyphs measured takes them from the budget. + remeasured = remeasured.saturating_sub(span.saturating_mul(6)); + track_budget = track_budget.saturating_sub(span); + l.respaced(k, k + span, 0.0).map(|r| { + let mut r = r.tracked(system_layout, &mut track_budget); + // Tracking that leaves a space under half its advance: the gaps alone + // do not show the spaces past the glyphs measured (only the kerning a + // space breaks may), so the whole rest is measured while the budget + // lasts. + let more = n - k - span; + let space = space_advance(&r.face) * r.scale; + if more > 0 + && (space + r.tracking_pt()).abs() < space / 2.0 + && remeasured >= more.saturating_mul(6) + && track_budget >= more.saturating_mul(6) + && let Some(whole) = l.respaced(k, n, 0.0) + { + remeasured = remeasured.saturating_sub(more.saturating_mul(6)); + track_budget = track_budget.saturating_sub(more); + return whole.tracked(system_layout, &mut track_budget); + } + for (id, m) in l.pieces.iter().zip(&l.matches).skip(k + span) { + r.push(*id, m); + } + r + }) } else if l.tracking == 0.0 { l.part(k, n) } else { diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 80361f1e0a..627878a3c2 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1002,6 +1002,59 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); } +#[test] +fn irregular_gaps_before_a_long_tracked_run_do_not_split_the_run() { + // The first eight gaps each take another tracking, and the 92 glyphs after them are tracked + // 300: measuring the rest after each irregular gap must not use up the budget the run needs, + // so the run is one object with its tracking. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap(); + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "i".repeat(100), "{r}"); + assert_eq!(r["unmatched"], json!([])); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().count(), 92, "{texts:?}"); + assert!(run.runs.iter().all(|r| r.style.tracking == 300.0), "{texts:?}"); +} + +#[test] +fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { + // Tracking as tight as a space is wide leaves the space no advance, and only the kerning it + // breaks shows it is there: the word space past the glyphs the rest's tracking is measured + // from is read by that measure too. + let mut s = session(); + let text = format!("{} {}", "AV".repeat(20), "AV".repeat(5)); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap(); + let face = text_of(&s, id).runs[0].style.font_family.clone(); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "AV", "size": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in(&s, pg).into_iter().next().unwrap(); + assert_eq!(pl.face.family, face); + let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0).round(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)]); +} + #[test] fn tightly_tracked_type_keeps_its_tracking() { // Tracking tighter than a space: the space moves the next glyph back. From 8158107e82e561ab31d188ac31f000986571f097 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 16:40:10 -0800 Subject: [PATCH 015/126] Retype: a counter too narrow in any direction, or an outline too large to probe, keeps the shape an outline The fill check rejects a counter whose convex hull is narrower than three times the outline tolerance in some direction, so a turned strip is caught as well as an upright one, and rejects a shape whose outline is too large to flatten. Exact parts of a split compound are checked at tolerance 0 even when near matches are allowed, so a split that only exact matching found is not accepted under the wider tolerance. The tracking sentence in docs/type-parity.md names its three-glyph condition. --- crates/engine/src/cmd/retype.rs | 27 +++-- crates/engine/src/cmd/retype_tests.rs | 73 ++++++++++++- crates/text/src/retype.rs | 147 ++++++++++++++++++++++++-- docs/mcp.md | 6 +- docs/type-parity.md | 2 +- 5 files changed, 231 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 605ddd08ec..c846c34a51 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a contour narrower than three times the outline tolerance, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -1178,14 +1178,20 @@ fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { /// a path's candidates: its `part` flag is set for a part of a split shape, whose contours Make /// Compound Path may have turned the other way round, and its `near` flag allows near matches. /// Exact matches come first: the whole shape, then its groups, then the whole shape nearly, then -/// its groups nearly. A split of several parts is kept only when `together` accepts the paths of -/// its runs (the parts, set one beside another, paint what the shape paints). -fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bool) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { +/// its groups nearly. A split of several parts is kept only when `together(runs, near)` accepts the +/// paths of its runs (the parts, set one beside another, paint what the shape paints); `near` is +/// set when the parts were found by near matching. +fn parts( + path: &BezPath, + groups: &[BezPath], + find: &dyn Fn(&BezPath, bool, bool) -> Vec, + together: &dyn Fn(&[BezPath], bool) -> bool, +) -> Vec> { let whole = find(path, false, false); if !whole.is_empty() { return vec![whole]; } - let exact = split_parts(groups, &|run| find(run, true, false), together); + let exact = split_parts(groups, &|run| find(run, true, false), &|runs| together(runs, false)); if !exact.is_empty() { return exact; } @@ -1193,7 +1199,7 @@ fn parts(path: &BezPath, groups: &[BezPath], find: &dyn Fn(&BezPath, bool, bo if !whole.is_empty() { return vec![whole]; } - split_parts(groups, &|run| find(run, true, true), together) + split_parts(groups, &|run| find(run, true, true), &|runs| together(runs, true)) } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for @@ -1374,7 +1380,14 @@ fn retype(s: &mut Session, p: &Value) -> Result { return vec![]; } let fill = pc.filled.then_some(pc.nonzero); - let together = |runs: &[BezPath]| fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tolerance)); + // Parts that all match exactly are checked at tolerance 0, in the near phase as in + // the exact one; only a part that matches nearly brings the tolerance in. + let together = |runs: &[BezPath], near: bool| { + fill.is_none_or(|nz| { + let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); + vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, if nearly { tolerance } else { 0.0 }) + }) + }; parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) }) .collect(); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 05c8210542..f32b036fde 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1202,6 +1202,50 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { assert!(s.doc().unwrap().doc == before, "nothing changes"); } +#[test] +fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { + // Exact parts the even-odd rule rejects stay rejected when the near phase finds them again. + for dx in [-9.0, -11.0, -12.0, -13.0, -14.0] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "oo", "size": 40})); + let kids = children_of(&s, g); + s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + for tolerance in [0.0, 0.05] { + if let Ok(r) = s.execute("type.retype", &json!({"tolerance": tolerance})) { + panic!("the overlapping o's became type at dx {dx}, tolerance {tolerance}: {r}"); + } + } + } +} + +#[test] +fn exact_parts_of_a_compound_are_checked_at_tolerance_zero() { + let mut s = session(); + // A T and an o whose boxes overlap by 4 units, one painted area apart (the o sits under the + // bar's arm): a strip that the probes of tolerance 0.05 cannot see into but those of an exact + // match can. Both parts match exactly, so asking for near matches does not change the result. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "To", "size": 40})); + let kids = children_of(&s, g); + let (t, o) = (kids[0], kids[1]); + let bounds = |s: &Session, id: u64| s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + let dx = bounds(&s, t).x1 - 4.0 - bounds(&s, o).x0; + s.execute("object.move", &json!({"ids": [o], "dx": dx, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + for params in [json!({}), json!({"tolerance": 0.05})] { + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("type.retype", ¶ms).unwrap(); + assert_eq!(r["unmatched"], json!([]), "{params}: {r}"); + assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "{params}: the compound becomes type"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before, "{params}: undo restores it"); + } +} + #[test] fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { let mut s = session(); @@ -1257,15 +1301,15 @@ fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { } }; let groups = all_groups(&p); - assert_eq!(super::parts(&p, &groups, &find, &|_| true), vec![vec!["A"], vec!["BC"]]); + assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["A"], vec!["BC"]]); // A split the parts' paint does not allow is dropped. - assert!(super::parts(&p, &groups, &find, &|_| false).is_empty()); + assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty()); // With no way to match every group, nothing. let none = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { let b = path.bounding_box(); if part && b.x0.round() as i64 == 0 && b.x1.round() as i64 == 140 { vec!["AB"] } else { vec![] } }; - assert!(super::parts(&p, &groups, &none, &|_| true).is_empty()); + assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty()); } /// `path`'s contour groups, with no limit on the contours grouped. @@ -1292,7 +1336,7 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { } }; let groups = all_groups(&p); - assert_eq!(super::parts(&p, &groups, &find, &|_| true), vec![vec!["period"], vec!["period"]]); + assert_eq!(super::parts(&p, &groups, &find, &|_, _| true), vec![vec!["period"], vec!["period"]]); // When the parts match only nearly too, the whole near match comes first. let near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { let b = path.bounding_box(); @@ -1302,7 +1346,26 @@ fn exact_matches_of_the_parts_come_before_a_near_match_of_the_whole() { _ => vec![], } }; - assert_eq!(super::parts(&p, &groups, &near_only, &|_| true), vec![vec!["dieresis"]]); + assert_eq!(super::parts(&p, &groups, &near_only, &|_, _| true), vec![vec!["dieresis"]]); + // The split's paint check is told whether the parts were found nearly: exact parts are + // checked at tolerance 0 whatever tolerance the command was given. + let seen = std::cell::RefCell::new(vec![]); + let record = |_: &[kurbo::BezPath], near: bool| { + seen.borrow_mut().push(near); + true + }; + assert_eq!(super::parts(&p, &groups, &find, &record), vec![vec!["period"], vec!["period"]]); + assert_eq!(*seen.borrow(), vec![false]); + seen.borrow_mut().clear(); + let split_near_only = |path: &kurbo::BezPath, part: bool, near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, near, b.x0.round() as i64, b.x1.round() as i64) { + (true, true, 0, 40) | (true, true, 100, 140) => vec!["period"], + _ => vec![], + } + }; + assert_eq!(super::parts(&p, &groups, &split_near_only, &record), vec![vec!["period"], vec!["period"]]); + assert_eq!(*seen.borrow(), vec![true]); } #[test] diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 8a65126569..1c9f8795b1 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -1120,14 +1120,14 @@ const MAX_FILL_PROBES: usize = 512; /// `glyph` (filled by the nonzero rule), whose outlines lie within `tol` of each other, paint the /// same area? Each probe lies `1.5 tol` or `3 tol` to a side of the middle of a segment of the shape's /// outline; one within `tol` of either outline is skipped, so a region narrower than that is not -/// probed. `false` when a contour of the shape is narrower than `3 tol` on its shorter side, since -/// the probes cannot then tell whether the area inside it is painted; `true` when an outline is too -/// large to probe. +/// probed. `false` when a counter of the shape (a contour inside another) is narrower than `3 tol` +/// across in some direction, however it is turned, since the probes cannot then tell whether the +/// area inside it is painted, and `false` when an outline is too large to probe. fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bool { if narrow_contour(shape, 3.0 * tol) { return false; } - let (Some(fs), Some(fg)) = (Flat::new(shape, tol), Flat::new(glyph, tol)) else { return true }; + let (Some(fs), Some(fg)) = (Flat::new(shape, tol), Flat::new(glyph, tol)) else { return false }; let step = fs.segs.len().div_ceil(MAX_FILL_PROBES).max(1); for (s, e) in fs.segs.iter().step_by(step) { let d = *e - *s; @@ -1154,9 +1154,74 @@ fn paints_alike(shape: &BezPath, nonzero: bool, glyph: &BezPath, tol: f64) -> bo true } -/// Does `path` have a contour no wider than `width` on its shorter side that lies inside another -/// contour (a counter)? +/// The least width of the convex hull of `path` over every direction it could be measured in, its +/// points flattened to within `tol`; 0 when the hull has fewer than three corners and when the +/// path flattens to more than [`MAX_OUTLINE_POINTS`] points. +fn hull_width(path: &BezPath, tol: f64) -> f64 { + let mut pts: Vec = vec![]; + let mut too_many = false; + kurbo::flatten(path.iter(), tol, |el| { + if let PathEl::MoveTo(q) | PathEl::LineTo(q) = el { + if pts.len() >= MAX_OUTLINE_POINTS { + too_many = true; + } else { + pts.push(q); + } + } + }); + if too_many { + return 0.0; + } + pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + // Points a thousandth of `tol` apart are one point: their chord has no direction to speak of. + let eps = tol * 1e-3; + pts.dedup_by(|b, a| a.distance(*b) <= eps); + let cross = |o: Point, a: Point, b: Point| (a - o).cross(b - o); + let mut hull: Vec = vec![]; + for pass in 0..2 { + let from = hull.len(); + let ordered: Vec = if pass == 0 { pts.clone() } else { pts.iter().rev().copied().collect() }; + for p in ordered { + while hull.len() >= from + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(a, b)| cross(*a, *b, p) <= 0.0) { + hull.pop(); + } + hull.push(p); + } + hull.pop(); + } + if hull.len() < 3 { + return 0.0; + } + // Rotating calipers: the point farthest from each edge only moves forward from one edge to the + // next, so the whole walk visits each hull point a bounded number of times. + let n = hull.len(); + let mut least = f64::INFINITY; + let mut j = 1; + for (i, a) in hull.iter().enumerate() { + let Some(b) = hull.get((i + 1) % n) else { continue }; + let edge = *b - *a; + let len = edge.hypot(); + if len <= 0.0 || !len.is_finite() { + continue; + } + let away = |k: usize| hull.get(k % n).map_or(0.0, |p| (edge.cross(*p - *a) / len).abs()); + let mut steps = 0; + while steps < n && away(j + 1) >= away(j) { + j += 1; + steps += 1; + } + least = least.min(away(j)); + j %= n; + } + if least.is_finite() { least } else { 0.0 } +} + +/// Does `path` have a contour inside another contour (a counter) whose convex hull is no wider +/// than `width` in some direction? fn narrow_contour(path: &BezPath, width: f64) -> bool { + if !width.is_finite() || width <= 0.0 { + return false; + } let mut all: Vec = vec![]; for el in path.elements() { if matches!(el, PathEl::MoveTo(_)) { @@ -1168,8 +1233,7 @@ fn narrow_contour(path: &BezPath, width: f64) -> bool { } all.iter().enumerate().any(|(i, c)| { let Some(PathEl::MoveTo(at)) = c.elements().first().copied() else { return false }; - let bb = c.bounding_box(); - bb.width().min(bb.height()) <= width && all.iter().enumerate().any(|(j, o)| j != i && o.winding(at) != 0) + all.iter().enumerate().any(|(j, o)| j != i && o.winding(at) != 0) && hull_width(c, width / 30.0) <= width }) } @@ -1970,6 +2034,73 @@ mod tests { assert!(paints_alike(&wide_hole, true, &wide_hole, 1.0)); } + #[test] + fn a_counter_turned_too_narrow_to_probe_does_not_count_as_agreeing() { + let square = |x0: f64, y0: f64, x1: f64, y1: f64, back: bool| { + let p = kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); + if back { p.reverse_subpaths() } else { p } + }; + // A 60 by 10 counter turned 45 degrees: its box is about 49.5 square, wider than the + // threshold of about 31.8, but it is 10 across. + let strip = |back: bool| { + let turn = Affine::translate((50.0, 50.0)) * Affine::rotate(std::f64::consts::FRAC_PI_4); + let mut p = kurbo::Rect::new(-30.0, -5.0, 30.0, 5.0).to_path(0.1); + if back { + p = p.reverse_subpaths(); + } + turn * p + }; + let mut filled = square(0.0, 0.0, 100.0, 100.0, false); + filled.extend(strip(false).iter()); + let mut holed = square(0.0, 0.0, 100.0, 100.0, false); + holed.extend(strip(true).iter()); + let tol = 100.0_f64.hypot(100.0) * 0.5 * 3.0 * MAX_TOLERANCE; + assert!(narrow_contour(&filled, 3.0 * tol)); + assert!(!paints_alike(&filled, true, &holed, tol)); + // The same strip with its sides along the axes is told apart as before. + let mut level = square(0.0, 0.0, 100.0, 100.0, false); + level.extend(square(20.0, 45.0, 80.0, 55.0, false).iter()); + assert!(narrow_contour(&level, 3.0 * tol)); + // A counter wider than the threshold in every direction is not narrow. + let mut wide = square(0.0, 0.0, 100.0, 100.0, false); + wide.extend(square(10.0, 10.0, 90.0, 90.0, false).iter()); + assert!(!narrow_contour(&wide, 3.0 * tol)); + } + + #[test] + fn the_hull_width_is_the_least_width_in_any_direction() { + let strip = kurbo::Rect::new(-30.0, -5.0, 30.0, 5.0).to_path(0.1); + for deg in [0.0_f64, 17.0, 45.0, 90.0, 133.0] { + let w = hull_width(&(Affine::rotate(deg.to_radians()) * strip.clone()), 0.01); + assert!((w - 10.0).abs() < 0.05, "{deg} degrees: {w}"); + } + let circle = kurbo::Circle::new((5.0, 7.0), 50.0).to_path(0.1); + assert!((hull_width(&circle, 0.01) - 100.0).abs() < 0.5, "{}", hull_width(&circle, 0.01)); + // A triangle's least width is its shortest height. + let mut tri = BezPath::new(); + tri.move_to((0.0, 0.0)); + tri.line_to((40.0, 0.0)); + tri.line_to((0.0, 30.0)); + tri.close_path(); + assert!((hull_width(&tri, 0.01) - 24.0).abs() < 1e-9); + assert_eq!(hull_width(&BezPath::new(), 0.01), 0.0); + } + + #[test] + fn an_outline_too_large_to_probe_does_not_count_as_agreeing() { + let n = MAX_OUTLINE_POINTS + 64; + let mut many = BezPath::new(); + for i in 0..n { + let a = std::f64::consts::TAU * i as f64 / n as f64; + let p = Point::new(50.0 + 50.0 * a.cos(), 50.0 + 50.0 * a.sin()); + if i == 0 { many.move_to(p) } else { many.line_to(p) } + } + many.close_path(); + assert!(Flat::new(&many, 0.5).is_none(), "too many segments to flatten"); + assert!(!paints_alike(&many, true, &many, 0.5)); + assert!(paints_alike(&kurbo::Circle::new((50.0, 50.0), 50.0).to_path(0.1), true, &kurbo::Circle::new((50.0, 50.0), 50.0).to_path(0.1), 0.5)); + } + #[test] fn parts_that_overlap_under_the_even_odd_rule_do_not_paint_the_shape() { let square = |x0: f64, y0: f64, x1: f64, y1: f64| kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1); diff --git a/docs/mcp.md b/docs/mcp.md index 30b2f3ea56..910853c024 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11332,9 +11332,9 @@ first, then exact matches of its groups, then near matches of the whole shape, t compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in `unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule -whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. A shape with a contour narrower than three times the -outline tolerance on its shorter side cannot be checked this way and stays an outline: at `tolerance` 0.05, a -counter 10 units wide in a 100 by 100 shape. The glyphs of a compound path that splits into several are set one beside +whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it. A shape with a counter narrower than three times the +outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a +counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. The glyphs of a compound path that splits into several are set one beside another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each other under the even-odd rule) stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are diff --git a/docs/type-parity.md b/docs/type-parity.md index d8e2c1e474..33867c2a92 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them); other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From fe7d225d6f5e07ec24664c1049ffbfc9e2f78b83 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:07:50 -0800 Subject: [PATCH 016/126] Retype: a contour reaching outside a concave one is no counter of it, and a rejected split gives way to another A contour counts as lying inside another only when up to eight of its anchor points do. When the paint check rejects the split with the longest runs, the split with the shortest runs is tried before the shape stays an outline. --- crates/engine/src/cmd/retype.rs | 68 ++++++++++++++++----------- crates/engine/src/cmd/retype_tests.rs | 25 ++++++++++ crates/text/src/retype.rs | 48 +++++++++++++++++-- 3 files changed, 110 insertions(+), 31 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index c846c34a51..c9c4281935 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1210,39 +1210,51 @@ fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, togethe return vec![]; } let g = groups.len(); - // From the last group back: the run that starts at each group, the longest that matches and - // leaves a rest that can all be matched, with its candidates. Runs past such a start are - // never tried for one whose rest cannot be matched. - let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); - for i in (0..g).rev() { - for n in (1..=MAX_RUN.min(g - i)).rev() { - let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); - if !rest_ok { - continue; + // The split with the longest runs first; when `together` rejects it, the one with the shortest + // runs, which is the other end of the complete splits. + for longest in [true, false] { + // From the last group back: the run that starts at each group, the longest (or shortest) + // that matches and leaves a rest that can all be matched, with its candidates. Runs past + // such a start are never tried for one whose rest cannot be matched. + let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); + for i in (0..g).rev() { + let mut lens: Vec = (1..=MAX_RUN.min(g - i)).collect(); + if longest { + lens.reverse(); } - let Some(run) = groups.get(i..i + n) else { continue }; - let cands = find(&joined(run)); - if !cands.is_empty() { - if let Some(c) = chosen.get_mut(i) { - *c = Some((n, cands)); + for n in lens { + let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); + if !rest_ok { + continue; + } + let Some(run) = groups.get(i..i + n) else { continue }; + let cands = find(&joined(run)); + if !cands.is_empty() { + if let Some(c) = chosen.get_mut(i) { + *c = Some((n, cands)); + } + break; } - break; } } + let mut out = vec![]; + let mut runs = vec![]; + let mut i = 0; + while i < g { + let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; + out.push(cands); + runs.push(groups.get(i..i + n).map(joined).unwrap_or_default()); + i += n; + } + if out.len() == 1 || together(&runs) { + return out; + } + // Every run a single group: the other order gives the same split. + if out.len() == g { + break; + } } - let mut out = vec![]; - let mut runs = vec![]; - let mut i = 0; - while i < g { - let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; - out.push(cands); - runs.push(groups.get(i..i + n).map(joined).unwrap_or_default()); - i += n; - } - if out.len() > 1 && !together(&runs) { - return vec![]; - } - out + vec![] } /// Contour groups joined into one path. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index f32b036fde..3882c50f5e 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1312,6 +1312,31 @@ fn a_split_takes_a_shorter_run_when_the_longest_leaves_a_group_unmatched() { assert!(super::parts(&p, &groups, &none, &|_, _| true).is_empty()); } +#[test] +fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() { + use kurbo::Shape; + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 140) => vec!["AB"], + (true, 0, 40) => vec!["A"], + (true, 100, 140) => vec!["B"], + (true, 200, 240) => vec!["C"], + _ => vec![], + } + }; + let groups = all_groups(&p); + // The longest runs first (AB, C) are rejected; the three single glyphs are kept. + let singles = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 3; + assert_eq!(super::parts(&p, &groups, &find, &singles), vec![vec!["A"], vec!["B"], vec!["C"]]); + // When no complete split is accepted, nothing. + assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty()); +} + /// `path`'s contour groups, with no limit on the contours grouped. fn all_groups(path: &kurbo::BezPath) -> Vec { let mut budget = usize::MAX; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 1c9f8795b1..6df2f396f2 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -829,6 +829,9 @@ fn fits_within(results: Vec<((f64, f64), f64)>, limit: f64) -> Vec<((f64, f64), /// Rounds of pairing and fitting [`near_fit`] gives each turn, at most. const REFITS: usize = 4; +/// Anchor points of a contour [`clusters`] tests against a candidate container, at most. +const MAX_CONTAINMENT_PROBES: usize = 8; + /// `path`'s contours in groups that can each be one glyph: a contour with the contours that lie /// inside it (a letter's counters, and what lies inside those), in the order the outer contours /// come. A path of several glyphs (a word outlined as one compound path) gives one group per glyph @@ -853,16 +856,33 @@ pub fn clusters(path: &BezPath) -> Vec { } } let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); - let starts: Vec> = subs.iter().map(|s| s.elements().first().and_then(|e| e.end_point())).collect(); + // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in + // another only when every one of them does. + let probes: Vec> = subs + .iter() + .map(|s| { + let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); + let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); + anchors.into_iter().step_by(step).collect() + }) + .collect(); // Each contour's container: the smallest contour around it. let parent: Vec> = (0..subs.len()) .map(|i| { - let (Some(bi), Some(Some(p))) = (boxes.get(i), starts.get(i)) else { return None }; + let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; + if pi.is_empty() { + return None; + } (0..subs.len()) .filter(|&j| j != i) .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) .filter(|(_, bj, sj)| { - bj.area() > bi.area() && bj.x0 <= bi.x0 && bj.y0 <= bi.y0 && bj.x1 >= bi.x1 && bj.y1 >= bi.y1 && sj.winding(*p) != 0 + bj.area() > bi.area() + && bj.x0 <= bi.x0 + && bj.y0 <= bi.y0 + && bj.x1 >= bi.x1 + && bj.y1 >= bi.y1 + && pi.iter().all(|p| sj.winding(*p) != 0) }) .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) .map(|(j, _, _)| j) @@ -2067,6 +2087,28 @@ mod tests { assert!(!narrow_contour(&wide, 3.0 * tol)); } + #[test] + fn a_contour_reaching_outside_a_concave_one_is_no_counter_of_it() { + // An L, and a triangle that starts inside the L and inside its box but reaches outside it. + let mut l = BezPath::new(); + for (i, (x, y)) in [(0.0, 0.0), (100.0, 0.0), (100.0, 20.0), (20.0, 20.0), (20.0, 100.0), (0.0, 100.0)].into_iter().enumerate() { + if i == 0 { l.move_to((x, y)) } else { l.line_to((x, y)) } + } + l.close_path(); + let mut tri = BezPath::new(); + tri.move_to((5.0, 5.0)); + tri.line_to((90.0, 90.0)); + tri.line_to((5.0, 50.0)); + tri.close_path(); + let mut both = l.clone(); + both.extend(tri.iter()); + assert_eq!(clusters(&both).len(), 2); + // A contour wholly inside stays with its container. + let mut inside = l.clone(); + inside.extend(kurbo::Rect::new(5.0, 5.0, 15.0, 15.0).to_path(0.1).iter()); + assert_eq!(clusters(&inside).len(), 1); + } + #[test] fn the_hull_width_is_the_least_width_in_any_direction() { let strip = kurbo::Rect::new(-30.0, -5.0, 30.0, 5.0).to_path(0.1); From 99781bb329ae8661cf4dcc028b0a9c29ac93e133 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:10:00 -0800 Subject: [PATCH 017/126] Links: Relink and folder Unembed no longer refuse a distorted image The refusals that ran before the files were read and before a folder was written stopped Relink and the folder form of Unembed on an image changed by Perspective Distort or Free Distort, which now keep their corners. --- crates/engine/src/cmd/links.rs | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 2af260011a..9d0a0bbcb3 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2136,9 +2136,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { _ => None, }) }; - // Whether the images were found as the missing links (nothing selected, a folder given) rather - // than named or selected. - let mut found_missing = false; let mut ids: Vec = match (&each, ids_param(p, "ids", C)?) { (Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(), (None, Some(ids)) => ids, @@ -2146,7 +2143,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { let selected: Vec = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect(); match folder_param { Some(_) if selected.is_empty() => { - found_missing = true; groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect() } _ => selected, @@ -2159,11 +2155,6 @@ fn relink(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the images to relink, or pass ids")); } - // A named or selected distorted image is refused before a folder is searched, whether or not - // its file is found there. - if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) { - return Err(super::xform::distorted_image_error(C, *id)); - } // All Instances: the other stored objects linked to the same files, each once. if scope == Scope::All { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); @@ -2868,9 +2859,6 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re skipped.push(id); continue; } - if n.is_distorted_image() { - return Err(super::xform::distorted_image_error(C, id)); - } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; embedded.push((id, n.display_name(), blob)); } From 3e8e29891effe556ff9c01827cec675ce96947a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 17:03:41 -0800 Subject: [PATCH 018/126] Retype: a long run after a split keeps its tracking fraction and its spaces The tracking measured over the first glyphs of a rest is read as a whole number, or as none under one unit, only when the difference moves the last glyph of the rest by no more than the tolerance. A rest whose tracking gives a space a negative advance is measured whole, as one with a small advance is. The whole-rest measure takes the budget for every glyph it reads. --- crates/engine/src/cmd/retype.rs | 34 +++++++++--- crates/engine/src/cmd/retype_tests.rs | 74 +++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 5d6c8ab9c4..bba563195d 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -400,6 +400,14 @@ impl Line { /// its characters, spaces included, from `budget` before it runs; without enough left, the /// line stays as it is, or becomes the best tracked reading laid out before the budget ran out. fn tracked(self, system_layout: bool, budget: &mut usize) -> Line { + let reach = self.pieces.len(); + self.tracked_reaching(system_layout, budget, reach) + } + + /// [`Line::tracked`] for a line whose tracking is applied to `reach` glyphs: a measured tracking + /// within 0.05 of a whole number is read as that number only when the difference moves the + /// glyph `reach` places on by no more than the tolerance [`first_mismatch`] allows. + fn tracked_reaching(self, system_layout: bool, budget: &mut usize, reach: usize) -> Line { let size = self.size(); let n = self.pieces.len(); if n < 3 || size <= 0.0 { @@ -506,7 +514,12 @@ impl Line { let mut tries = vec![]; for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() { let Some(measured) = measure(seed) else { continue }; - for t in [round_tracking(measured), measured] { + let rounded = round_tracking(measured); + let drift = (rounded - measured).abs() / 1000.0 * size * reach.saturating_sub(1) as f64; + for t in [rounded, measured] { + if t != measured && drift > (size * 0.01).max(0.01) { + continue; + } if !tries.contains(&t) { tries.push(t); } @@ -554,7 +567,12 @@ impl Line { match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) { // Under a unit of tracking, or a word space the tracked reading drops, where // untracked type draws the line: no tracking. - (None, None) if t.abs() < 1.0 || drops_a_word_space => return self, + (None, None) + if (t.abs() < 1.0 && t.abs() / 1000.0 * size * reach.saturating_sub(1) as f64 <= (size * 0.01).max(0.01)) + || drops_a_word_space => + { + return self; + } (None, _) => return tracked, (Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)), _ => {} @@ -693,7 +711,7 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) remeasured = remeasured.saturating_sub(span.saturating_mul(6)); track_budget = track_budget.saturating_sub(span); l.respaced(k, k + span, 0.0).map(|r| { - let mut r = r.tracked(system_layout, &mut track_budget); + let mut r = r.tracked_reaching(system_layout, &mut track_budget, n - k); // Tracking that leaves a space under half its advance: the gaps alone // do not show the spaces past the glyphs measured (only the kerning a // space breaks may), so the whole rest is measured while the budget @@ -701,13 +719,13 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) let more = n - k - span; let space = space_advance(&r.face) * r.scale; if more > 0 - && (space + r.tracking_pt()).abs() < space / 2.0 - && remeasured >= more.saturating_mul(6) - && track_budget >= more.saturating_mul(6) + && space + r.tracking_pt() < space / 2.0 + && remeasured >= (n - k).saturating_mul(6) + && track_budget >= (n - k).saturating_mul(6) && let Some(whole) = l.respaced(k, n, 0.0) { - remeasured = remeasured.saturating_sub(more.saturating_mul(6)); - track_budget = track_budget.saturating_sub(more); + remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); + track_budget = track_budget.saturating_sub(n - k); return whole.tracked(system_layout, &mut track_budget); } for (id, m) in l.pieces.iter().zip(&l.matches).skip(k + span) { diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 627878a3c2..b78f432634 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1026,6 +1026,80 @@ fn irregular_gaps_before_a_long_tracked_run_do_not_split_the_run() { assert!(run.runs.iter().all(|r| r.style.tracking == 300.0), "{texts:?}"); } +#[test] +fn a_long_run_after_a_split_keeps_the_fraction_of_its_tracking() { + // Tracking 300.04 reads as 300 over the 32 glyphs measured, but 400 glyphs apart the two + // differ by more than the tolerance: the run after the irregular gaps keeps 300.04 and stays + // one object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap(); + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + s.execute("text.setRangeStyle", &json!({"id": id, "start": i, "end": i + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "i".repeat(400), "{r}"); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().count(), 392, "{texts:?}"); + assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); +} + +#[test] +fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() { + // Tracking 0.2 moves none of the 32 glyphs measured by more than the tolerance, but moves the + // glyphs 399 places on: the rest after a split keeps it and stays one object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(400), "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 0.2})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert!(near(l.tracking, 0.2, 0.01), "{}", l.tracking); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let last = out.last().unwrap(); + assert!(last.pieces.len() == 399 && near(last.tracking, 0.2, 0.01), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); +} + +#[test] +fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after_a_split() { + // Tracking tighter than the space is wide, by one half to one and a half spaces more, gives the + // space a negative advance; the word space past the glyphs the tracking is measured from is + // still read. + for (unit, times) in + [("AV", 1.5), ("AV", 1.7), ("TA", 1.5), ("TA", 1.7), ("To", 1.5), ("To", 1.7), ("MM", 1.5), ("MM", 1.7), ("Wo", 1.6), ("Wo", 1.8)] + { + let mut s = session(); + let text = format!("{} {}", unit.repeat(20), unit.repeat(5)); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10})).unwrap()["id"].as_u64().unwrap(); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": unit, "size": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in(&s, pg).into_iter().next().unwrap(); + let tracking = -(super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0 * times).round(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking), "{times}"); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1, "{times}"); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)], "{times}"); + } +} + #[test] fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { // Tracking as tight as a space is wide leaves the space no advance, and only the kerning it From 5f5559b7102356c58aaae13f0835fc1dd29bc348 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 19:46:43 -0800 Subject: [PATCH 019/126] Retype: the glyphs after the measured ones read a word space only where it fits better than the joined pair Past the first 32 glyphs of a rest, a gap now reads as a word space only when spaces fit it better than the joined pair does, as the measured glyphs do. A tracking and kerning that make a kerned pair draw like a space no longer add spaces the source lacks. --- crates/engine/src/cmd/retype.rs | 66 +++++++++++++++++++++++++-- crates/engine/src/cmd/retype_tests.rs | 44 +++++++++++++++++- crates/text/src/test_fonts.rs | 37 +++++++++++++++ 3 files changed, 143 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index bba563195d..aa5198d209 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -247,6 +247,52 @@ impl Line { } fn push(&mut self, id: NodeId, m: &GlyphMatch) { + self.push_joined(id, m, None); + } + + /// For each of `ms`'s glyphs, the distance along the line to the next when untracked type sets + /// them with no spaces (their advances and pair kerning), and when it sets one space between + /// them (the glyph's own advance plus a space where type draws no such layout), taking the + /// characters laid out from `budget`; `None` when the budget is short or type does not draw + /// every glyph without spaces. + fn pair_steps(&self, ms: &[GlyphMatch], system_layout: bool, budget: &mut usize) -> Option> { + *budget = budget.checked_sub(ms.len().saturating_mul(3))?; + let dir = self.dir(); + let mut bare = self.clone(); + bare.tracking = 0.0; + let mut origins = |text: String| -> Vec { + bare.text = text; + let t = bare.probe(system_layout); + let lay = vectorcraft_text::layout(FontDb::global(), &t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() + }; + let joined = origins(ms.iter().map(|m| m.ch).collect()); + if joined.len() != ms.len() { + return None; + } + let spaced = origins(ms.iter().map(|m| m.ch.to_string()).collect::>().join(" ")); + let space = space_advance(&self.face) * self.scale; + let spaced_ok = spaced.len() == ms.len(); + Some( + ms.iter() + .enumerate() + .zip(joined.windows(2)) + .map(|((i, m), p)| { + let own = m.face.advance(m.gid) * m.scale + space; + let apart = match (spaced_ok, spaced.get(i), spaced.get(i + 1)) { + (true, Some(a), Some(b)) => (*b - *a).dot(dir), + _ => own, + }; + ((p[1] - p[0]).dot(dir), apart) + }) + .collect(), + ) + } + + /// [`Line::push`], with `steps` the distances [`Line::pair_steps`] gives for the pair of the + /// line's last glyph and `m`. A gap reads as spaces only when they fit it better than the + /// joined pair does, as when the tracking is measured. + fn push_joined(&mut self, id: NodeId, m: &GlyphMatch, steps: Option<(f64, f64)>) { // A gap, past the tracking, wider than half a space before the glyph is spaces the // outlines left no shape for. Each space takes the tracking too. let dir = self.dir(); @@ -256,7 +302,16 @@ impl Line { let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; if spaces.is_finite() && spaces > 0.5 { let n = (spaces.round() as usize).clamp(1, 64); - self.text.extend(std::iter::repeat_n(' ', n)); + let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir); + let tr = self.tracking_pt(); + let joined_fits = steps.is_some_and(|(joined, apart)| { + let face_space = space_advance(&self.face) * self.scale; + let spaced_err = (d - apart + face_space - tr - n as f64 * (face_space + tr)).abs(); + (d - joined - tr).abs() <= spaced_err + self.size() * 1e-5 + }); + if !joined_fits { + self.text.extend(std::iter::repeat_n(' ', n)); + } } self.text.push(m.ch); self.pieces.push(id); @@ -728,8 +783,13 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) track_budget = track_budget.saturating_sub(n - k); return whole.tracked(system_layout, &mut track_budget); } - for (id, m) in l.pieces.iter().zip(&l.matches).skip(k + span) { - r.push(*id, m); + // The glyphs after those measured follow at that tracking; a gap reads as + // spaces only when they fit it better than the joined pair does, as in + // the glyphs measured, while the budget for laying the pairs out lasts. + let steps = + l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut track_budget)).unwrap_or_default(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(k + span).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); } r }) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index b78f432634..ac55ca6fb8 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -886,13 +886,19 @@ fn slight_tracking_without_spaces_is_kept() { /// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's /// first match), before their tracking is measured and their layout checked. fn lines_in(s: &Session, g: u64) -> Vec { + lines_in_family(s, g, None) +} + +/// [`lines_in`] with the face of the first glyph's match in `family` when given. +fn lines_in_family(s: &Session, g: u64, family: Option<&str>) -> Vec { let d = &s.doc().unwrap().doc; let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces); let db = vectorcraft_text::FontDb::global(); let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted); - let face = index.matches(&pieces[0].path)[0].face.id(); + let first = index.matches(&pieces[0].path); + let face = first.iter().find(|m| family.is_none_or(|f| m.face.family == f)).unwrap_or(&first[0]).face.id(); let mut lines: Vec = vec![]; for pc in &pieces { let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); @@ -1100,6 +1106,42 @@ fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after } } +#[test] +fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_after_a_split() { + // The font adds 120 units to each i before an i. Tracking that leaves a space 120 wide makes the + // gap a kerned pair leaves the same as the gap a word space leaves; the joined reading wins the + // tie, as it does for the glyphs the tracking is measured from. + use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap()); + let mut s = session(); + let text = "i".repeat(60); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap(); + let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0; + let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round(); + assert!(space + tracking >= space / 2.0, "the space must stay at least half its width: {space} {tracking}"); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); + assert_eq!(texts, vec![(&text[1..], tracking)]); +} + #[test] fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { // Tracking as tight as a space is wide leaves the space no advance, and only the kerning it diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..fd2fe20c9d 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1816,6 +1816,43 @@ pub fn pair_kerning_font() -> Option> { Some(builder.build()) } +/// The family of [`positive_kerning_font`]. +pub const POSITIVE_KERNING_FAMILY: &str = "Poskern Sans"; + +/// The units [`positive_kerning_font`] adds to the advance of an i that another i follows. +pub const POSITIVE_KERNING_UNITS: i16 = 120; + +/// The bundled Source Sans 3 Regular as family [`POSITIVE_KERNING_FAMILY`], its `GPOS` replaced by +/// one `kern` pair, i followed by i, that adds [`POSITIVE_KERNING_UNITS`] to the first glyph's +/// advance. `None` when it can't be built. +pub fn positive_kerning_font() -> Option> { + use write_fonts::tables::gpos::{Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let i = GlyphId16::new(u16::try_from(font.charmap().map('i')?.to_u32()).ok()?); + let record = PairValueRecord::new(i, ValueRecord::new().with_x_advance(POSITIVE_KERNING_UNITS), ValueRecord::new()); + let coverage = CoverageFormat1::new(vec![i]); + let pos = PairPos::format_1(coverage.into(), vec![PairSet::new(vec![record])]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0])), vec![]))]); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]); + let lookups = PositionLookupList::new(vec![PositionLookup::Pair(Lookup::new(Default::default(), vec![pos]))]); + let family = POSITIVE_KERNING_FAMILY; + let name = name_table(&[(1, family), (2, "Regular"), (4, "Poskern Sans Regular"), (6, "PoskernSans-Regular")])?; + let mut builder = FontBuilder::new(); + builder.add_table(&Gpos::new(scripts, features, lookups)).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"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`twin_font`]: two versions of one family and style. pub const TWIN_FAMILY: &str = "Twintest Sans"; From 8483baf11fde0a2df80f1f2b32dae292578c530e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:13:02 -0800 Subject: [PATCH 020/126] Retype: the type docs say which two-glyph lines take another line's tracking A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place. A line of one or two glyphs that joins tracked lines in one object takes their tracking. The Retype row in docs/type-parity.md said other lines are set untracked. --- docs/type-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/type-parity.md b/docs/type-parity.md index 33867c2a92..868b944bcd 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them); other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From 90130f37ed321f07d82a556eb3f882608c17262a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:55:39 -0800 Subject: [PATCH 021/126] Shape tools: the Smart Guide label of a hover goes when the pointer leaves the canvas With Smart Guides on, hovering a shape tool over another object's anchor or edge shows the "anchor" or "path" label where the new shape would start. When the pointer then left the canvas, went under a panel or menu, or a middle-button drag started panning, the label stayed on the canvas at the last hover point. The Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment tools now drop it when their hover ends, and so do the Arc, Spiral, Rectangular Grid and Polar Grid tools, as the Scissors tool already does. --- crates/tools/src/draw2/family.rs | 21 +++++++++++++++++++++ crates/tools/src/shape.rs | 4 +++- crates/tools/src/shape/tests.rs | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 87c11abba9..a815c02d2a 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -448,6 +448,10 @@ impl Tool for FamilyTool { _ => self.grid_skew_key(key).is_some(), } } + /// The pointer left the canvas: the Smart Guide of the hover goes. + fn hover_ended(&mut self, _cx: &ToolContext) { + self.snap.clear(); + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { @@ -1254,6 +1258,23 @@ mod tests { assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "align"))); } + /// The "anchor" label a hover shows goes when the pointer leaves the canvas. + #[test] + fn leaving_the_canvas_drops_the_hover_label() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let label = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor")); + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let mut t = FamilyTool::new(id); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0)); + assert!(label(&t.overlays(&cx)), "{id}"); + t.hover_ended(&cx); + assert!(!label(&t.overlays(&cx)), "{id}: {:?}", t.overlays(&cx)); + } + } + /// A grid's Default Size and Reference Point are options for a click's dialog; the drag /// draws the box it is dragged to and leaves them out of its command. #[test] diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 7376efd5b0..b93c94dddc 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -973,9 +973,11 @@ impl Tool for ShapeTool { fn ends_on_escape(&self, _cx: &ToolContext) -> bool { !self.through.is_empty() } - /// The pointer left the canvas: the circle's preview through it goes. + /// The pointer left the canvas: the circle's preview through it and the Smart Guide of the + /// hover go. fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.snap.clear(); } /// An edit, Undo or Redo made outside the tool, or another document, drops the points placed /// for a circle. diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 59ae1d8e83..fa089bf4e7 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -968,6 +968,23 @@ fn corners_snap_to_smart_guides() { assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &cx.segment_measure_label(from, to)))); } +/// The "anchor" label a hover shows goes when the pointer leaves the canvas, for every shape tool. +#[test] +fn leaving_the_canvas_drops_the_hover_label() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let label = |o: &[Overlay]| o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "anchor")); + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star", "lineSegment"] { + let mut t = ShapeTool::new(id); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 98.0, 102.0)); + assert!(label(&t.overlays(&cx)), "{id}"); + t.hover_ended(&cx); + assert!(!label(&t.overlays(&cx)), "{id}: {:?}", t.overlays(&cx)); + } +} + /// Line Segment Tool Options: Length and Angle are options (for a click's dialog), and Fill /// Line makes the drag's line take the current fill. #[test] From dc89097a9675552cb3c6b6006b826f68b6206669 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:44:24 -0800 Subject: [PATCH 022/126] Retype: spaces after the measured glyphs keep the pair check on a short budget Laying out the pairs after the glyphs a split measures is now set aside before the tracking is measured, so a short budget no longer leaves those pairs to the gap alone; without enough for both, the rest is not measured. Past the measured glyphs, the number of word spaces in a gap is the count among the rounded, lower and upper counts of the gap and the count of the measured one-space distance that fits best, so kerning against a space no longer adds a second space. The pair check also runs on a gap under half a space wide, so kerning toward a space no longer drops it. Rounding a measured tracking to a whole number now counts the word spaces as well as the glyphs the tracking moves, so a long spaced run after a split keeps a fractional tracking and stays one object. --- crates/engine/src/cmd/retype.rs | 181 +++++++++++++++----------- crates/engine/src/cmd/retype_tests.rs | 117 +++++++++++++++++ crates/text/src/test_fonts.rs | 58 +++++++++ 3 files changed, 281 insertions(+), 75 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index aa5198d209..251d690b32 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -290,29 +290,41 @@ impl Line { } /// [`Line::push`], with `steps` the distances [`Line::pair_steps`] gives for the pair of the - /// line's last glyph and `m`. A gap reads as spaces only when they fit it better than the - /// joined pair does, as when the tracking is measured. + /// line's last glyph and `m`. With `steps`, a gap reads as spaces only when they fit it better + /// than the joined pair does, as when the tracking is measured, however narrow the gap is. fn push_joined(&mut self, id: NodeId, m: &GlyphMatch, steps: Option<(f64, f64)>) { - // A gap, past the tracking, wider than half a space before the glyph is spaces the - // outlines left no shape for. Each space takes the tracking too. + // Without `steps`, a gap, past the tracking, wider than half a space before the glyph is + // spaces the outlines left no shape for. Each space takes the tracking too. let dir = self.dir(); - let gap = (m.origin - self.end).dot(dir) - self.tracking_pt(); + let tr = self.tracking_pt(); + let gap = (m.origin - self.end).dot(dir) - tr; // Tracking tighter than a space's width gives each space a negative advance. - let space = space_advance(&self.face) * self.scale + self.tracking_pt(); + let face_space = space_advance(&self.face) * self.scale; + let space = face_space + tr; let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; - if spaces.is_finite() && spaces > 0.5 { - let n = (spaces.round() as usize).clamp(1, 64); - let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir); - let tr = self.tracking_pt(); - let joined_fits = steps.is_some_and(|(joined, apart)| { - let face_space = space_advance(&self.face) * self.scale; - let spaced_err = (d - apart + face_space - tr - n as f64 * (face_space + tr)).abs(); - (d - joined - tr).abs() <= spaced_err + self.size() * 1e-5 - }); - if !joined_fits { - self.text.extend(std::iter::repeat_n(' ', n)); + let n = match steps { + Some((joined, apart)) => { + let d = (m.origin - self.matches.last().map_or(self.origin, |p| p.origin)).dot(dir); + // How far `n` spaces set the glyph from where the outlines put it: the pair with one + // space between them is `apart`, and each further space adds a space and the tracking. + let spaced_err = |n: usize| (d - apart + face_space - tr - n as f64 * space).abs(); + // Kerning against a space widens or narrows the gap, so the count the gap gives, the + // counts next to it and the count the measured distance gives are compared; the + // rounded count wins a tie. + let measured = (d - apart + face_space - tr) / space; + let best = [spaces.round(), spaces.floor(), spaces.ceil(), measured.round()] + .into_iter() + .filter(|c| c.is_finite()) + .map(|c| (c.max(1.0) as usize).min(64)) + .min_by(|a, b| spaced_err(*a).total_cmp(&spaced_err(*b))) + .unwrap_or(1); + // The joined pair wins a tie. + if (d - joined - tr).abs() <= spaced_err(best) + self.size() * 1e-5 { 0 } else { best } } - } + None if spaces.is_finite() && spaces > 0.5 => (spaces.round() as usize).clamp(1, 64), + None => 0, + }; + self.text.extend(std::iter::repeat_n(' ', n)); self.text.push(m.ch); self.pieces.push(id); self.matches.push(m.clone()); @@ -455,13 +467,14 @@ impl Line { /// its characters, spaces included, from `budget` before it runs; without enough left, the /// line stays as it is, or becomes the best tracked reading laid out before the budget ran out. fn tracked(self, system_layout: bool, budget: &mut usize) -> Line { - let reach = self.pieces.len(); + let reach = self.text.chars().count(); self.tracked_reaching(system_layout, budget, reach) } - /// [`Line::tracked`] for a line whose tracking is applied to `reach` glyphs: a measured tracking - /// within 0.05 of a whole number is read as that number only when the difference moves the - /// glyph `reach` places on by no more than the tolerance [`first_mismatch`] allows. + /// [`Line::tracked`] for a line whose tracking is applied to `reach` characters, its glyphs and + /// the spaces between them: a measured tracking within 0.05 of a whole number is read as that + /// number only when the difference moves the character `reach` places on by no more than the + /// tolerance [`first_mismatch`] allows. fn tracked_reaching(self, system_layout: bool, budget: &mut usize, reach: usize) -> Line { let size = self.size(); let n = self.pieces.len(); @@ -743,61 +756,10 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) // The glyphs before the mismatch, then the rest, each checked as a line of its // own: the type before the mismatch may draw otherwise without what follows it (a // font can place a glyph by the glyph after it), and the first glyph on its own - // may still be drawn as it was (a contextual form changed it in the line). The - // rest takes the tracking its own glyphs are spaced by, while the budget for - // measuring it lasts and when type draws its first glyph as it was, followed by the - // next two (else that glyph splits off first, and the tracking is measured from the - // next one); past it, an untracked line's rest keeps its text as it is. The tracking - // is measured from the rest's first [`MEASURE_SPAN`] glyphs at most, and the glyphs - // after them follow at that tracking, so each split costs the same however long the - // rest is, and splits at irregular gaps early in a line leave the budget for a long - // evenly tracked run after them. + // may still be drawn as it was (a contextual form changed it in the line). Some(k) => { let k = k.max(1); - let span = (n - k).min(MEASURE_SPAN); - // A measure takes at least six times the glyphs it reads from each budget. - let measurable = n - k >= 3 && remeasured >= span.saturating_mul(6) && track_budget >= span.saturating_mul(6); - let first_drawn = measurable && { - budget = budget.saturating_sub(3); - l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) - }; - let rest = if first_drawn { - // Rebuilding the glyphs measured takes them from the budget. - remeasured = remeasured.saturating_sub(span.saturating_mul(6)); - track_budget = track_budget.saturating_sub(span); - l.respaced(k, k + span, 0.0).map(|r| { - let mut r = r.tracked_reaching(system_layout, &mut track_budget, n - k); - // Tracking that leaves a space under half its advance: the gaps alone - // do not show the spaces past the glyphs measured (only the kerning a - // space breaks may), so the whole rest is measured while the budget - // lasts. - let more = n - k - span; - let space = space_advance(&r.face) * r.scale; - if more > 0 - && space + r.tracking_pt() < space / 2.0 - && remeasured >= (n - k).saturating_mul(6) - && track_budget >= (n - k).saturating_mul(6) - && let Some(whole) = l.respaced(k, n, 0.0) - { - remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); - track_budget = track_budget.saturating_sub(n - k); - return whole.tracked(system_layout, &mut track_budget); - } - // The glyphs after those measured follow at that tracking; a gap reads as - // spaces only when they fit it better than the joined pair does, as in - // the glyphs measured, while the budget for laying the pairs out lasts. - let steps = - l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut track_budget)).unwrap_or_default(); - for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(k + span).enumerate() { - r.push_joined(*id, m, steps.get(j).copied()); - } - r - }) - } else if l.tracking == 0.0 { - l.part(k, n) - } else { - l.respaced(k, n, 0.0) - }; + let rest = rest_after_split(&l, k, system_layout, &mut budget, &mut remeasured, &mut track_budget); match rest { Some(r) => todo.push_front(r), None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()), @@ -811,6 +773,75 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) out } +/// The rest of `l` from glyph `k` (at least 1) after [`verified`] splits it there. The rest takes +/// the tracking its own glyphs are spaced by, while the budgets for measuring it last and when type +/// draws its first glyph as it was, followed by the next two (else that glyph splits off first, and +/// the tracking is measured from the next one); past it, an untracked line's rest keeps its text as +/// it is. The tracking is measured from the rest's first [`MEASURE_SPAN`] glyphs at most, and the +/// glyphs after them follow at that tracking, so each split costs the same however long the rest +/// is, and splits at irregular gaps early in a line leave the budget for a long evenly tracked run +/// after them. A gap after the glyphs measured reads as spaces only when they fit it better than +/// the joined pair does, as in the glyphs measured: laying those pairs out is set aside from +/// `track_budget` before the tracking is measured, and without enough for both the rest is not +/// measured. +fn rest_after_split(l: &Line, k: usize, system_layout: bool, budget: &mut usize, remeasured: &mut usize, track_budget: &mut usize) -> Option { + let n = l.pieces.len(); + let span = (n - k).min(MEASURE_SPAN); + let more = n - k - span; + // What [`Line::pair_steps`] takes for the last glyph measured and the glyphs after it. + let pairs = if more > 0 { more.saturating_add(1).saturating_mul(3) } else { 0 }; + // A measure takes at least six times the glyphs it reads from each budget. + let measurable = n - k >= 3 && *remeasured >= span.saturating_mul(6) && *track_budget >= span.saturating_mul(6).saturating_add(pairs); + let first_drawn = measurable && { + *budget = budget.saturating_sub(3); + l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) + }; + if !first_drawn { + return if l.tracking == 0.0 { l.part(k, n) } else { l.respaced(k, n, 0.0) }; + } + // Rebuilding the glyphs measured takes them from the budget. + *remeasured = remeasured.saturating_sub(span.saturating_mul(6)); + *track_budget = track_budget.saturating_sub(span).saturating_sub(pairs); + let mut pair_budget = pairs; + // The characters the rest's tracking applies to: its glyphs and the spaces between them (a + // space before glyph `at` follows glyph `at - 1`). + let reach = l + .text + .chars() + .scan(0usize, |glyph, c| { + let at = *glyph; + *glyph += usize::from(c != ' '); + Some(if c == ' ' { at > k } else { at >= k }) + }) + .filter(|kept| *kept) + .count() + .max(n - k); + let mut r = l.respaced(k, k + span, 0.0)?.tracked_reaching(system_layout, track_budget, reach); + // Tracking that leaves a space under half its advance: the gaps alone do not show the spaces + // past the glyphs measured (only the kerning a space breaks may), so the whole rest is measured + // while the budget lasts. + let space = space_advance(&r.face) * r.scale; + if more > 0 + && space + r.tracking_pt() < space / 2.0 + && *remeasured >= (n - k).saturating_mul(6) + && track_budget.saturating_add(pair_budget) >= (n - k).saturating_mul(6) + && let Some(whole) = l.respaced(k, n, 0.0) + { + *remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); + *track_budget = track_budget.saturating_add(pair_budget).saturating_sub(n - k); + return Some(whole.tracked(system_layout, track_budget)); + } + // The glyphs after those measured follow at that tracking. + let steps = match more { + 0 => vec![], + _ => l.matches.get(k + span - 1..).and_then(|ms| r.pair_steps(ms, system_layout, &mut pair_budget)).unwrap_or_default(), + }; + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(k + span).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + Some(r) +} + /// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes /// of the area type on the layers Retype changes /// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index ac55ca6fb8..0338c8defd 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1055,6 +1055,32 @@ fn a_long_run_after_a_split_keeps_the_fraction_of_its_tracking() { assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); } +#[test] +fn a_long_spaced_run_after_a_split_keeps_the_fraction_of_its_tracking() { + // Tracking 300.04 read as 300 moves the last of the 192 glyphs after the irregular gaps by less + // than the tolerance, counting the glyphs alone, but the word spaces between them take the + // tracking too: the run keeps 300.04 and stays one object. + let mut s = session(); + let text = vec!["ii"; 100].join(" "); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 6})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300.04})).unwrap(); + // The first eight glyphs, at 0, 1, 3, 4, 6, 7, 9 and 10 (a space after each two). + for (i, t) in [50, 170, 90, 230, 130, 410, 20, 520].into_iter().enumerate() { + let at = i + i / 2; + s.execute("text.setRangeStyle", &json!({"id": id, "start": at, "end": at + 1, "tracking": t})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat().replace(' ', ""), "i".repeat(200), "{r}"); + assert!(texts.len() <= 9, "at most one object per irregular gap, then the run: {texts:?}"); + let run = text_of(&s, r["ids"].as_array().unwrap().last().unwrap().as_u64().unwrap()); + assert_eq!(run.plain_text().chars().filter(|c| *c == 'i').count(), 192, "{texts:?}"); + assert!(run.runs.iter().all(|r| near(r.style.tracking, 300.04, 1e-3)), "{texts:?}"); +} + #[test] fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() { // Tracking 0.2 moves none of the 32 glyphs measured by more than the tolerance, but moves the @@ -1142,6 +1168,97 @@ fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_ assert_eq!(texts, vec![(&text[1..], tracking)]); } +#[test] +fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_when_the_budget_runs_short() { + // As above, with a measuring budget that covers the tracking's measure but not the layout of + // the pairs after the glyphs measured: those pairs still read no space. + use vectorcraft_text::test_fonts::{POSITIVE_KERNING_FAMILY, POSITIVE_KERNING_UNITS, positive_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(positive_kerning_font().unwrap()); + let mut s = session(); + let text = "i".repeat(60); + let probe = s.execute("text.create", &json!({"x": 10, "y": 200, "text": "i", "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [probe]})).unwrap(); + let pg = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let pl = lines_in_family(&s, pg, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap(); + let space = super::space_advance(&pl.face) / pl.face.units_per_em() * 1000.0; + let tracking = (f64::from(POSITIVE_KERNING_UNITS) - space).round(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 10, "font": POSITIVE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let l = lines_in_family(&s, g, Some(POSITIVE_KERNING_FAMILY)).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); + // What measuring the tracking of the rest's first 32 glyphs takes. + let span = super::MEASURE_SPAN; + let mut measure = 100_000; + let measured = l.respaced(1, 1 + span, 0.0).unwrap().tracked_reaching(false, &mut measure, 59); + assert_eq!(measured.tracking, tracking); + let measure = 100_000 - measure; + // The pairs after the glyphs measured take three characters each. + let pairs = (60 - 1 - span + 1) * 3; + for short in (0..pairs).step_by(7) { + let mut track_budget = (span + measure + short).max(span * 6); + let (mut glyphs, mut remeasured) = (100_000, 100_000); + let r = super::rest_after_split(&l, 1, false, &mut glyphs, &mut remeasured, &mut track_budget).unwrap(); + assert_eq!(r.text, text[1..], "a budget {short} short of the pairs"); + } +} + +#[test] +fn a_word_space_after_a_glyph_kerned_against_it_reads_as_one_space_past_the_glyphs_measured() { + // The font adds 130 units to an i before a space, so the gap before the next glyph is more than + // one and a half spaces wide; the distance the pair with one space between them is laid out at + // fits one space. + use vectorcraft_text::test_fonts::{SPACE_KERNING_FAMILY, space_kerning_font}; + + vectorcraft_text::FontDb::global().add_font(space_kerning_font().unwrap()); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_KERNING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let l = lines_in_family(&s, g, Some(SPACE_KERNING_FAMILY)).into_iter().next().unwrap(); + assert_eq!(l.pieces.len(), 4); + let mut r = l.respaced(0, 2, 0.0).unwrap(); + let mut budget = 1_000; + let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + assert_eq!(r.text, "ii ii"); +} + +#[test] +fn a_word_space_after_a_glyph_kerned_toward_it_is_kept_past_the_glyphs_measured() { + // The font takes 130 units off an i before a space, so the gap before the next glyph is under + // half a space wide; the distance the pair with one space between them is laid out at fits it. + use vectorcraft_text::test_fonts::{SPACE_NARROWING_FAMILY, space_narrowing_font}; + + vectorcraft_text::FontDb::global().add_font(space_narrowing_font().unwrap()); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "ii ii", "size": 10, "font": SPACE_NARROWING_FAMILY})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let l = lines_in_family(&s, g, Some(SPACE_NARROWING_FAMILY)).into_iter().next().unwrap(); + assert_eq!(l.pieces.len(), 4); + let mut r = l.respaced(0, 2, 0.0).unwrap(); + let mut budget = 1_000; + let steps = r.pair_steps(&l.matches[1..], false, &mut budget).unwrap(); + for (j, (id, m)) in l.pieces.iter().zip(&l.matches).skip(2).enumerate() { + r.push_joined(*id, m, steps.get(j).copied()); + } + assert_eq!(r.text, "ii ii"); +} + #[test] fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { // Tracking as tight as a space is wide leaves the space no advance, and only the kerning it diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index fd2fe20c9d..2b654f6822 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1853,6 +1853,64 @@ pub fn positive_kerning_font() -> Option> { Some(builder.build()) } +/// The family of [`space_kerning_font`]. +pub const SPACE_KERNING_FAMILY: &str = "Spacekern Sans"; + +/// The units [`space_kerning_font`] adds to the advance of an i that a space follows. +pub const SPACE_KERNING_UNITS: i16 = 130; + +/// The bundled Source Sans 3 Regular as family [`SPACE_KERNING_FAMILY`], its `GPOS` replaced by one +/// `kern` pair, i followed by a space, that adds [`SPACE_KERNING_UNITS`] to the first glyph's +/// advance. `None` when it can't be built. +pub fn space_kerning_font() -> Option> { + space_kerned_font(SPACE_KERNING_FAMILY, "Spacekern", SPACE_KERNING_UNITS) +} + +/// The family of [`space_narrowing_font`]. +pub const SPACE_NARROWING_FAMILY: &str = "Spacenarrow Sans"; + +/// The units [`space_narrowing_font`] takes off the advance of an i that a space follows. +pub const SPACE_NARROWING_UNITS: i16 = 130; + +/// [`space_kerning_font`] as family [`SPACE_NARROWING_FAMILY`], its pair taking +/// [`SPACE_NARROWING_UNITS`] off the first glyph's advance instead. `None` when it can't be built. +pub fn space_narrowing_font() -> Option> { + space_kerned_font(SPACE_NARROWING_FAMILY, "Spacenarrow", -SPACE_NARROWING_UNITS) +} + +/// The bundled Source Sans 3 Regular as `family` (`short` Sans in its PostScript name), its `GPOS` +/// replaced by one `kern` pair, i followed by a space, that adds `units` to the first glyph's +/// advance. +fn space_kerned_font(family: &str, short: &str, units: i16) -> Option> { + use write_fonts::tables::gpos::{Gpos, PairPos, PairSet, PairValueRecord, PositionLookup, PositionLookupList, ValueRecord}; + use write_fonts::tables::layout::{CoverageFormat1, Feature, FeatureList, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord}; + use write_fonts::types::GlyphId16; + + const BASE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf"); + let font = skrifa::FontRef::new(BASE).ok()?; + let charmap = font.charmap(); + let gid = |c| Some(GlyphId16::new(u16::try_from(charmap.map(c)?.to_u32()).ok()?)); + let (i, space) = (gid('i')?, gid(' ')?); + let record = PairValueRecord::new(space, ValueRecord::new().with_x_advance(units), ValueRecord::new()); + let coverage = CoverageFormat1::new(vec![i]); + let pos = PairPos::format_1(coverage.into(), vec![PairSet::new(vec![record])]); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0])), vec![]))]); + let features = FeatureList::new(vec![FeatureRecord::new(Tag::new(b"kern"), Feature::new(None, vec![0]))]); + let lookups = PositionLookupList::new(vec![PositionLookup::Pair(Lookup::new(Default::default(), vec![pos]))]); + let (full, ps) = (format!("{family} Regular"), format!("{short}Sans-Regular")); + let name = name_table(&[(1, family), (2, "Regular"), (4, &full), (6, &ps)])?; + let mut builder = FontBuilder::new(); + builder.add_table(&Gpos::new(scripts, features, lookups)).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"kern") && !builder.contains(tag) { + builder.add_raw(tag, font.table_data(r.tag())?.as_bytes()); + } + } + Some(builder.build()) +} + /// The family of [`twin_font`]: two versions of one family and style. pub const TWIN_FAMILY: &str = "Twintest Sans"; From 2fa3e32c838350d64d9e8629caf3e7cce24f9ed5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:57:11 -0800 Subject: [PATCH 023/126] Retype: stacked lines split from one compound path become one object Lines that a compound path of several glyphs splits into share that shape, so the check that one line's shape comes right after the last line's never passed for them, and each line stayed an object of its own. Two lines of one shape now follow each other, and the other joining rules decide as for lines of separate shapes. The lines of the existing paint-order test are moved farther apart so they still make two objects. --- crates/engine/src/cmd/retype.rs | 5 +++-- crates/engine/src/cmd/retype_tests.rs | 22 ++++++++++++++++++++-- docs/mcp.md | 2 +- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index c9c4281935..563678293e 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -999,7 +999,7 @@ fn share_tracking(lines: &mut [Line], system_layout: bool) { /// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of /// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after -/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. +/// shape `a`, or is `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. fn blocks(lines: Vec, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec { let mut out = vec![]; let mut block: Option = None; @@ -1489,8 +1489,9 @@ fn retype(s: &mut Session, p: &Value) -> Result { let mut seen = std::collections::HashSet::new(); unmatched.retain(|id| !kept.contains(id) && seen.insert(*id)); let at: std::collections::HashMap = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect(); + // Lines split from one compound path share its shape, with nothing between them. let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) { - (Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier), + (Some(i), Some(j)) => *j == *i || (*j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier)), _ => false, }; // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 3882c50f5e..e5231b47b0 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1146,9 +1146,10 @@ fn a_lone_period_in_a_compound_selected_alone_stays_an_outline() { #[test] fn lines_from_one_compound_path_keep_their_order() { let mut s = session(); - // Two lines of outlines made into one compound path. + // Two lines of outlines made into one compound path, farther apart than the lines of one + // paragraph, so each stays an object of its own. let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); - let low = outlined(&mut s, json!({"x": 40, "y": 220, "text": "Ham", "size": 40})); + let low = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Ham", "size": 40})); let mut glyphs = children_of(&s, top); glyphs.extend(children_of(&s, low)); s.execute("select.set", &json!({"ids": glyphs})).unwrap(); @@ -1166,6 +1167,23 @@ fn lines_from_one_compound_path_keep_their_order() { assert!(at[first] < at[second], "{texts:?} at {at:?}"); } +#[test] +fn stacked_lines_from_one_compound_path_become_one_object() { + let mut s = session(); + // Two lines of one paragraph, outlined and made into one compound path: they join as the + // lines of separate outlines do. + let text = "Tim\nHam"; + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 40})); + let glyphs = children_of(&s, g); + s.execute("select.set", &json!({"ids": glyphs})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + assert!(s.doc().unwrap().doc.node(NodeId(c)).is_none(), "the compound becomes the type"); +} + #[test] fn a_compound_whose_parts_are_not_all_glyphs_stays_whole() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 910853c024..412809d4f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12526,7 +12526,7 @@ tracking their own gaps give. These rules are VectorCraft's own. Each entry of t ## Retype several lines -`type.retype` joins lines that follow each other in paint order, with the same group, paint, font, size, turn and +`type.retype` joins lines that follow each other in paint order (lines split from one compound path do), with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the tracking of the others), into one type object when each line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its From cf80c118712c43ae747b7bc714d297109f5e0ad0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 23:05:44 -0800 Subject: [PATCH 024/126] Retype: a compound tries its other complete splits when the paint check rejects the first two A compound path whose split with the longest runs and split with the shortest runs both failed the paint check stayed an outline, even when another complete split (AB and CD for groups A, B, C and D) passed it. The split search now checks the other complete splits in order, at most 32 per shape for exact matches and 32 for near matches, and looks each run of groups up at most once, only when the search reaches it. --- crates/engine/src/cmd/retype.rs | 191 +++++++++++++++++++++----- crates/engine/src/cmd/retype_tests.rs | 69 ++++++++++ docs/mcp.md | 4 +- 3 files changed, 225 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 563678293e..69272c1928 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1147,6 +1147,10 @@ fn partial_lines(lines: &[Vec], glyphs_of: &std::collections::HashMap( } /// [`parts`] of a shape split into contour `groups`, each run's candidates from `find`; empty for -/// no groups, when the groups cannot all be matched and when `together` rejects the runs of a split -/// of several parts. +/// no groups, when the groups cannot all be matched and when `together` rejects every split of +/// several parts it is asked about. The complete splits are tried with the longest runs first, +/// then with the shortest runs, then the others in order, a longer run at an earlier group first. +/// `together` is asked about at most [`MAX_SPLIT_TRIES`] splits. `find` is asked about a run only +/// when the search reaches it, and about each run at most once, so at most [`MAX_RUN`] times per +/// group. fn split_parts(groups: &[BezPath], find: &dyn Fn(&BezPath) -> Vec, together: &dyn Fn(&[BezPath]) -> bool) -> Vec> { - if groups.is_empty() { + let g = groups.len(); + let mut s = Splits { groups, find, found: (0..g).map(|_| (0..MAX_RUN).map(|_| None).collect()).collect(), whole: vec![None; g] }; + // A split is the runs it takes, each as (start, number of groups). + let mut first = vec![]; + if g == 0 || !s.extend(&mut first, false) { return vec![]; } - let g = groups.len(); - // The split with the longest runs first; when `together` rejects it, the one with the shortest - // runs, which is the other end of the complete splits. - for longest in [true, false] { - // From the last group back: the run that starts at each group, the longest (or shortest) - // that matches and leaves a rest that can all be matched, with its candidates. Runs past - // such a start are never tried for one whose rest cannot be matched. - let mut chosen: Vec)>> = (0..g).map(|_| None).collect(); - for i in (0..g).rev() { - let mut lens: Vec = (1..=MAX_RUN.min(g - i)).collect(); - if longest { - lens.reverse(); + let runs_of = + |split: &[(usize, usize)]| -> Vec { split.iter().map(|&(at, n)| groups.get(at..at + n).map(joined).unwrap_or_default()).collect() }; + let accepted = 'search: { + if first.len() == 1 { + break 'search Some(first); + } + // The shortest runs are looked up only once the longest are rejected. + let mut shortest = vec![]; + let mut shortest_next = true; + let mut rest = first.clone(); + let mut candidate = Some(first.clone()); + let mut tried = 0; + while let Some(split) = candidate.take() { + if tried == MAX_SPLIT_TRIES { + break; } - for n in lens { - let rest_ok = i + n == g || chosen.get(i + n).is_some_and(Option::is_some); - if !rest_ok { - continue; + tried += 1; + if together(&runs_of(&split)) { + break 'search Some(split); + } + if std::mem::take(&mut shortest_next) && s.extend(&mut shortest, true) && shortest != first { + candidate = Some(shortest.clone()); + continue; + } + candidate = loop { + if !s.advance(&mut rest) { + break None; } - let Some(run) = groups.get(i..i + n) else { continue }; - let cands = find(&joined(run)); - if !cands.is_empty() { - if let Some(c) = chosen.get_mut(i) { - *c = Some((n, cands)); + if rest != shortest { + break Some(rest.clone()); + } + }; + } + None + }; + let Some(split) = accepted else { return vec![] }; + let mut out = vec![]; + for (at, n) in split { + let Some(Some(cands)) = s.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))).map(Option::take) else { return vec![] }; + out.push(cands); + } + out +} + +/// The state of one [`split_parts`] search: each run's candidates and whether the groups from each +/// start can all be matched, each found when the search first needs it. +struct Splits<'a, M> { + groups: &'a [BezPath], + find: &'a dyn Fn(&BezPath) -> Vec, + /// By start and length less one: the run's candidates, once looked up. + found: Vec>>>, + /// By start: whether the groups from there on can all be matched, once known. + whole: Vec>, +} + +impl Splits<'_, M> { + /// Whether the run of `n` groups at `at` matches, looking it up the first time. + fn matches(&mut self, at: usize, n: usize) -> bool { + let Some(slot) = self.found.get_mut(at).and_then(|f| f.get_mut(n.wrapping_sub(1))) else { return false }; + if slot.is_none() { + let cands = self.groups.get(at..at + n).map(|run| (self.find)(&joined(run))).unwrap_or_default(); + *slot = Some(cands); + } + slot.as_ref().is_some_and(|c| !c.is_empty()) + } + + /// Whether the groups from `at` on can all be matched. The search goes from `at` forward, the + /// longest run first, and no start is searched twice, so it ends after at most [`MAX_RUN`] + /// lookups and checks per group. + fn completes(&mut self, at: usize) -> bool { + let g = self.groups.len(); + if at >= g { + return at == g; + } + if let Some(known) = self.whole.get(at).copied().flatten() { + return known; + } + // From `at`: the starts still to settle, each with the run length to try next. + let mut stack: Vec<(usize, usize)> = vec![(at, MAX_RUN.min(g - at))]; + while let Some(&(i, n)) = stack.last() { + if self.whole.get(i).copied().flatten().is_some() { + stack.pop(); + continue; + } + if n == 0 { + if let Some(w) = self.whole.get_mut(i) { + *w = Some(false); + } + stack.pop(); + continue; + } + if let Some(top) = stack.last_mut() { + top.1 = n - 1; + } + if !self.matches(i, n) { + continue; + } + let next = i + n; + match if next == g { Some(true) } else { self.whole.get(next).copied().flatten() } { + Some(true) => { + if let Some(w) = self.whole.get_mut(i) { + *w = Some(true); } - break; + stack.pop(); + } + Some(false) => {} + None => { + // Settle `next` first, then try this run again. + if let Some(top) = stack.last_mut() { + top.1 = n; + } + stack.push((next, MAX_RUN.min(g - next))); } } } - let mut out = vec![]; - let mut runs = vec![]; - let mut i = 0; + self.whole.get(at).copied().flatten() == Some(true) + } + + /// Whether `n` groups at `at` are a run a complete split can take. + fn fits(&mut self, at: usize, n: usize) -> bool { + self.matches(at, n) && self.completes(at + n) + } + + /// Takes `split` on to the last group, with the longest run that fits at each start (or, with + /// `shortest`, the shortest); false when no run fits. + fn extend(&mut self, split: &mut Vec<(usize, usize)>, shortest: bool) -> bool { + let g = self.groups.len(); + let mut i = split.last().map_or(0, |&(at, n)| at + n); while i < g { - let Some(Some((n, cands))) = chosen.get_mut(i).map(Option::take) else { return vec![] }; - out.push(cands); - runs.push(groups.get(i..i + n).map(joined).unwrap_or_default()); + let most = MAX_RUN.min(g - i); + let lens: Vec = if shortest { (1..=most).collect() } else { (1..=most).rev().collect() }; + let Some(n) = lens.into_iter().find(|&n| self.fits(i, n)) else { return false }; + split.push((i, n)); i += n; } - if out.len() == 1 || together(&runs) { - return out; + true + } + + /// Moves `split` on to the next complete split, in order: the runs before the last start where + /// a shorter run fits kept, that shorter run, and the longest runs after it. False past the last. + fn advance(&mut self, split: &mut Vec<(usize, usize)>) -> bool { + while let Some((at, n)) = split.pop() { + if let Some(m) = (1..n).rev().find(|&m| self.fits(at, m)) { + split.push((at, m)); + return self.extend(split, false); + } } - // Every run a single group: the other order gives the same split. - if out.len() == g { - break; - } + false } - vec![] } /// Contour groups joined into one path. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index e5231b47b0..61cbe532bd 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1355,6 +1355,75 @@ fn a_split_the_paint_check_rejects_gives_way_to_another_complete_split() { assert!(super::parts(&p, &groups, &find, &|_, _| false).is_empty()); } +#[test] +fn a_split_between_the_longest_and_the_shortest_runs_is_tried() { + use kurbo::Shape; + // Four groups A, B, C and D. ABC and D (the longest runs first) and the four single glyphs + // (the shortest) are complete splits the paint check rejects; AB and CD is the one it accepts. + let mut p = kurbo::BezPath::new(); + for x in [0.0, 100.0, 200.0, 300.0] { + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let find = |path: &kurbo::BezPath, part: bool, _near: bool| -> Vec<&'static str> { + let b = path.bounding_box(); + match (part, b.x0.round() as i64, b.x1.round() as i64) { + (true, 0, 240) => vec!["ABC"], + (true, 0, 140) => vec!["AB"], + (true, 200, 340) => vec!["CD"], + (true, 0, 40) => vec!["A"], + (true, 100, 140) => vec!["B"], + (true, 200, 240) => vec!["C"], + (true, 300, 340) => vec!["D"], + _ => vec![], + } + }; + let groups = all_groups(&p); + let pairs = |runs: &[kurbo::BezPath], _near: bool| runs.len() == 2 && runs.first().is_some_and(|r| r.bounding_box().x1.round() as i64 == 140); + assert_eq!(super::parts(&p, &groups, &find, &pairs), vec![vec!["AB"], vec!["CD"]]); +} + +#[test] +fn at_most_max_split_tries_complete_splits_are_checked() { + use kurbo::Shape; + // Twelve groups, every run of up to three of them a glyph: far more complete splits than the + // cap. The paint check is asked about the cap's number of them and no more, and each run is + // looked up at most once. + let mut p = kurbo::BezPath::new(); + for i in 0..12 { + let x = f64::from(i) * 100.0; + p.extend(kurbo::Rect::new(x, 0.0, x + 40.0, 40.0).path_elements(0.1)); + } + let groups = all_groups(&p); + assert_eq!(groups.len(), 12); + let looked_up = std::cell::Cell::new(0usize); + let find = |_: &kurbo::BezPath| -> Vec<&'static str> { + looked_up.set(looked_up.get() + 1); + vec!["glyph"] + }; + let asked = &std::cell::Cell::new(0usize); + let accept_at = |n: usize| { + move |_: &[kurbo::BezPath]| { + asked.set(asked.get() + 1); + asked.get() == n + } + }; + // Rejected every time: the search stops at the cap. + assert!(super::split_parts(&groups, &find, &accept_at(usize::MAX)).is_empty()); + assert_eq!(asked.get(), super::MAX_SPLIT_TRIES); + assert!(looked_up.get() <= super::MAX_RUN * groups.len(), "{} lookups", looked_up.get()); + // A first split that is accepted looks up its own runs only: four runs of three groups. + asked.set(0); + looked_up.set(0); + assert_eq!(super::split_parts(&groups, &find, &accept_at(1)).len(), 4); + assert_eq!(looked_up.get(), 4); + // The last split tried is still taken; the one past the cap is not tried. + asked.set(0); + assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES)).len() > 1); + asked.set(0); + assert!(super::split_parts(&groups, &find, &accept_at(super::MAX_SPLIT_TRIES + 1)).is_empty()); + assert_eq!(asked.get(), super::MAX_SPLIT_TRIES); +} + /// `path`'s contour groups, with no limit on the contours grouped. fn all_groups(path: &kurbo::BezPath) -> Vec { let mut budget = usize::MAX; diff --git a/docs/mcp.md b/docs/mcp.md index 412809d4f8..543e4472c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11336,7 +11336,9 @@ whose inner contour runs the same way as its outer one paints its center, so a r outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. The glyphs of a compound path that splits into several are set one beside another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each -other under the even-odd rule) stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours +other under the even-odd rule) stays an outline. When the split with the longest runs fails that check, the split with the +shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 +for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left From b237da4672231767e8d8ca526e49e78d83d4ff77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 00:24:20 -0800 Subject: [PATCH 025/126] Retype: a near glyph whose size and turn would draw it past the tolerance ends the line A near-matched glyph joins a line when its size and turn are each within the tolerance of the line's, and the line's type then draws it at the line's size and turn. Together with the glyph's own leftover distance, that change could put the drawn glyph further from its shape than the tolerance: an m 4% larger and turned 0.04 radians stayed on its line at tolerance 0.05. The layout check now also measures, for each near-matched glyph (and each glyph of a line whose first glyph is one), how far the change from its matched size and turn moves the drawn outline relative to its spread, combined with its own leftover distance, and splits the line before it when that passes the tolerance, or when the glyph's center sits further away than its origin may. --- crates/engine/src/cmd/retype.rs | 42 +++++++++++++++- crates/engine/src/cmd/retype_tests.rs | 69 +++++++++++++++++++++++++++ docs/mcp.md | 4 +- 3 files changed, 113 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 69272c1928..26991f032c 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it); a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -637,11 +637,51 @@ fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64, slack: f64) if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { return Some(k); } + // The type sets the glyph at its line's size and turn, which may differ from the glyph's + // own: the glyph drawn so must still lie within the tolerance of the shape (its center + // within the same distance as its origin). + if !(m.exact && first_exact) { + let (shape, moved) = set_apart(t, g, m); + // An exact match's own leftover is within the exact matcher's reach, not the tolerance. + let own = if m.exact { 0.0 } else { m.pose_residual }; + if own.hypot(shape) > slack + 1e-9 || moved > tol { + return Some(k); + } + } } // Ink the outlines did not have: the last glyph is where it went wrong. drawn.next().map(|_| matches.len().saturating_sub(1)) } +/// How glyph `g`, as type `t` draws it, differs from glyph `m` in the size, turn and place `m` +/// was matched in. The first value bounds, whatever points the outline is sampled at, the root +/// mean square distance between the two outlines' points about their center, relative to the +/// root mean square distance of `m`'s points from that center (the measure of near matches' +/// leftover distance): the largest stretch of the change from `m`'s size and turn to the drawn +/// one, which for a change of size and turn alone is that distance exactly. The second is how far +/// apart the two draw the center of the glyph's bounding box. Both are infinite when they cannot +/// be measured. +fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMatch) -> (f64, f64) { + let (sin, cos) = m.angle.sin_cos(); + let matched = kurbo::Affine::new([m.scale * cos, m.scale * sin, -m.scale * sin, m.scale * cos, m.origin.x, m.origin.y]); + let (gd, md) = (g.xf.determinant(), matched.determinant()); + if !gd.is_finite() || gd.abs() < 1e-12 || !md.is_finite() || md.abs() < 1e-12 { + return (f64::INFINITY, f64::INFINITY); + } + let drawn = t.xf * g.xf; + // The change from the matched glyph to the drawn one, less the identity, without the move. + let [a, b, c, d, _, _] = (drawn * matched.inverse()).as_coeffs(); + let (a, d) = (a - 1.0, d - 1.0); + // The largest singular value of [[a, c], [b, d]]. + let (p, q) = ((a * a + b * b + c * c + d * d) / 2.0, a * d - b * c); + let shape = (p + (p * p - q * q).max(0.0).sqrt()).sqrt(); + // The center of the glyph's box, in font units. + let center = g.xf.inverse() * kurbo::Shape::bounding_box(&g.outline).center(); + let moved = (drawn * center).distance(matched * center); + let finite = |v: f64| if v.is_finite() { v } else { f64::INFINITY }; + (finite(shape), finite(moved)) +} + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 61cbe532bd..1d8097f54c 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1063,6 +1063,75 @@ fn a_near_glyph_moved_by_more_than_the_tolerance_ends_the_line() { assert!(run(0.06) > 1, "past it: the line splits where the m was moved"); } +/// The bounding box of shape `id` (a path, or a compound path's paths), in document space. +fn shape_box(s: &Session, id: u64) -> kurbo::Rect { + let d = &s.doc().unwrap().doc; + let n = d.node(NodeId(id)).unwrap(); + let paths: Vec<&vectorcraft_doc::Node> = match n.children() { + Some(c) => c.iter().map(|c| &**c).collect(), + None => vec![n], + }; + paths + .iter() + .filter_map(|p| match &p.kind { + NodeKind::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path.to_bezpath())), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap() +} + +/// The bounding box of each glyph with ink that type `t` draws, in document space. +fn drawn_boxes(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| kurbo::Shape::bounding_box(&(t.xf * g.outline.clone()))).collect() +} + +#[test] +fn a_near_glyph_whose_size_and_turn_differ_past_the_tolerance_ends_the_line() { + // The m of simplified outlines made 4% larger, and turned 0.04 radians as well, about where it + // starts on the baseline, retyped with a tolerance of 0.05. Each change alone is within the + // size and turn a near-matched line allows, but drawn at the line's size and turn the m would + // lie further than 0.05 of its spread from its outline: it becomes type of its own. Larger + // alone, it is still within the tolerance and stays on the line. + for (scale, turn, lines) in [(1.04, 0.0, 1), (1.04, 0.04, 2)] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Tim", "size": 40})); + simplify_every_path(&mut s, 0.05); + let kids = children_of(&s, g); + let m = *kids.last().unwrap(); + let x0 = shape_box(&s, m).x0; + s.edit("test", |d, _| { + let at = kurbo::Vec2::new(x0, 100.0); + let xf = kurbo::Affine::translate(at) * kurbo::Affine::rotate(turn) * kurbo::Affine::scale(scale) * kurbo::Affine::translate(-at); + let data = d.node_mut(NodeId(m)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&(xf * data.to_bezpath())); + Ok(()) + }) + .unwrap(); + let before: Vec = kids.iter().map(|k| shape_box(&s, *k)).collect(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"tolerance": 0.05})).unwrap(); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + assert_eq!(texts.concat(), "Tim", "{r}"); + assert_eq!(texts.len(), lines, "scale {scale}, turn {turn}: {r}"); + if lines == 1 { + continue; + } + let drawn: Vec = r["ids"].as_array().unwrap().iter().flat_map(|id| drawn_boxes(&text_of(&s, id.as_u64().unwrap()))).collect(); + assert_eq!(drawn.len(), before.len(), "{r}"); + for b in &before { + // The glyph drawn nearest where the outline was. + let d = drawn.iter().min_by(|p, q| p.center().distance(b.center()).total_cmp(&q.center().distance(b.center()))).unwrap(); + let size = b.width().hypot(b.height()); + assert!( + (d.width() - b.width()).abs() < size * 0.01 && (d.height() - b.height()).abs() < size * 0.01, + "scale {scale}, turn {turn}: the outline's box {b:?}, the type's {d:?}: {r}" + ); + } + } +} + #[test] fn an_exact_glyph_moved_splits_the_line_whatever_the_tolerance() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 543e4472c3..a75c2f8ff8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11322,7 +11322,9 @@ mean square distance of its sampled outline points from their center), is at mos tolerance: an outline simplified, a curve split in two, or contours in another order, start or direction. The tolerance and this measure are VectorCraft's own. A near-matched glyph may differ from its line by the tolerance in size, turn and place; an exact glyph keeps the exact limits unless the line's first glyph, whose size and turn the line takes, is -a near match. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 +a near match. The line also splits before a near-matched glyph, or a glyph of a line whose first glyph is one, that +the type would draw further from its shape than the tolerance by the same measure (its own leftover distance together +with the change of size and turn) or with its center further away than its origin may be. Each entry of `fonts` in the result has a `score`, from 1 when every glyph of the line is exact down to 0 at a leftover distance of 0.05. A compound path that holds several glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the From d1859cf03febea597918e6d05affdc1f382bb97c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 00:44:37 -0800 Subject: [PATCH 026/126] Retype: a compound path of more than 65,536 path elements is not split into glyphs Splitting a compound path copies its contours and compares each with the others. A selected compound of a few contours with a very large number of path elements was split however many elements it had. Such a shape is now matched whole only, like one of more than 256 groups or 512 contours. --- crates/engine/src/cmd/retype.rs | 15 ++++++++++----- crates/engine/src/cmd/retype_tests.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 4 ++-- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 26991f032c..f4efd65cb3 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups and 512 contours, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -1201,13 +1201,18 @@ const MAX_SPLIT_CONTOURS: usize = 512; /// matched whole only. const MAX_SPLIT_TOTAL_CONTOURS: usize = 16_384; +/// A shape of more path elements than this is not split, and its contours are not grouped: 16 +/// times the most a glyph may have ([`vectorcraft_text::retype::MAX_ELEMENTS`]). +const MAX_SPLIT_ELEMENTS: usize = 16 * vectorcraft_text::retype::MAX_ELEMENTS; + /// `path`'s contour groups when it is split into glyphs: none for fewer than two or more than -/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours, and for more contours than -/// `budget` holds. A path of two or more contours takes them from `budget` when it is grouped. +/// [`MAX_SPLIT_GROUPS`], for more than [`MAX_SPLIT_CONTOURS`] contours or [`MAX_SPLIT_ELEMENTS`] +/// path elements, and for more contours than `budget` holds. A path of two or more contours takes +/// them from `budget` when it is grouped. fn split_groups(path: &BezPath, budget: &mut usize) -> Vec { - // Grouping compares every contour with every other: count them first. + // Grouping copies the contours and compares every contour with every other: count first. let n = path.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); - if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget { + if !(2..=MAX_SPLIT_CONTOURS).contains(&n) || n > *budget || path.elements().len() > MAX_SPLIT_ELEMENTS { return vec![]; } *budget -= n; diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 1d8097f54c..4ee5388692 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1565,6 +1565,30 @@ fn a_shape_that_lost_a_glyph_drops_the_lines_of_its_other_glyphs() { assert!(super::partial_lines(&whole, &glyphs_of).is_empty()); } +#[test] +fn a_compound_of_too_many_path_elements_is_not_grouped() { + // Two contours side by side, each a polygon of `k` corners. + let two = |k: usize| { + let mut p = kurbo::BezPath::new(); + for x in [0.0, 300.0] { + for i in 0..k { + let a = i as f64 / k as f64 * std::f64::consts::TAU; + let q = kurbo::Point::new(x + 100.0 + 100.0 * a.cos(), 100.0 + 100.0 * a.sin()); + if i == 0 { p.move_to(q) } else { p.line_to(q) } + } + p.close_path(); + } + p + }; + let mut budget = usize::MAX; + assert_eq!(super::split_groups(&two(100), &mut budget).len(), 2, "a small compound is grouped"); + let big = two(super::MAX_SPLIT_ELEMENTS / 2); + assert!(big.elements().len() > super::MAX_SPLIT_ELEMENTS); + let mut budget = usize::MAX; + assert!(super::split_groups(&big, &mut budget).is_empty(), "past the element limit it is matched whole only"); + assert_eq!(budget, usize::MAX, "and takes no contours from the budget"); +} + #[test] fn the_runs_and_near_keys_a_selection_is_looked_up_by_are_bounded() { use kurbo::Shape; diff --git a/docs/mcp.md b/docs/mcp.md index a75c2f8ff8..bb74d45a8f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11340,8 +11340,8 @@ counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each other under the even-odd rule) stays an outline. When the split with the longest runs fails that check, the split with the shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 -for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups or 512 contours -is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are +for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours +or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in From f9548440bd1ae09c3a153aab4e73c144c2f5041b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:40:36 -0800 Subject: [PATCH 027/126] Retype: a translucent compound path whose glyphs overlap stays an outline The glyphs of a split compound path can become separate type objects, for example on two lines. A compound filled by the nonzero rule whose glyphs overlap passed the paint check, and with an opacity below 100% the two objects then painted the overlap twice. A split whose parts overlap now keeps the shape an outline when the shape has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke. --- crates/engine/src/cmd/retype.rs | 32 ++++++++++++++------ crates/engine/src/cmd/retype_tests.rs | 43 +++++++++++++++++++++++++++ docs/mcp.md | 4 ++- 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index f4efd65cb3..b464696542 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] @@ -596,10 +596,16 @@ impl Line { /// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and /// blend once, spans a gradient over all of it, and strokes after filling every glyph. fn paints_as_one(l: &Line) -> bool { - l.opacity == 1.0 - && l.blend == vectorcraft_color::BlendMode::Normal - && matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. }) - && matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None) + paints_once(l.opacity, l.blend, &l.appearance) +} + +/// Does art with `opacity`, `blend` and `appearance` paint its overlaps the same as one object +/// and as several ([`paints_as_one`])? +fn paints_once(opacity: f32, blend: vectorcraft_color::BlendMode, appearance: &Appearance) -> bool { + opacity == 1.0 + && blend == vectorcraft_color::BlendMode::Normal + && matches!(appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. }) + && matches!(appearance.stroke_paint(), vectorcraft_color::Paint::None) } /// The tracking Retype sets, in 1/1000 em. @@ -1554,11 +1560,19 @@ fn retype(s: &mut Session, p: &Value) -> Result { let fill = pc.filled.then_some(pc.nonzero); // Parts that all match exactly are checked at tolerance 0, in the near phase as in // the exact one; only a part that matches nearly brings the tolerance in. + // The glyphs of a split may become separate objects: when the shape does not paint + // its overlaps as several objects would (translucent, another blend, a gradient or + // pattern fill, a stroke), its parts must not overlap, which the parts read by the + // even-odd rule against them all joined show. + let once = paints_once(pc.opacity, pc.blend, &pc.appearance); let together = |runs: &[BezPath], near: bool| { - fill.is_none_or(|nz| { - let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); - vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, if nearly { tolerance } else { 0.0 }) - }) + if fill.is_none() && once { + return true; + } + let nearly = near && runs.iter().any(|r| find(r, true, false, fill).is_empty()); + let tol = if nearly { tolerance } else { 0.0 }; + fill.is_none_or(|nz| vectorcraft_text::retype::parts_paint_alike(&pc.path, runs, nz, tol)) + && (once || vectorcraft_text::retype::parts_paint_alike(&joined(runs), runs, false, tol)) }; parts(&pc.path, g, &|p, part, near| find(p, part, near, fill), &together) }) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 4ee5388692..f939dcf410 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1289,6 +1289,49 @@ fn glyphs_that_overlap_in_an_even_odd_compound_stay_an_outline() { assert!(s.doc().unwrap().doc == before, "nothing changes"); } +#[test] +fn a_translucent_compound_whose_glyphs_overlap_stays_an_outline() { + // Two i's, the second moved half onto the first and down off its baseline, made into one + // compound path filled by the nonzero rule with every contour running one way: the parts paint + // the shape's area, but on two lines they become two objects, and at 50% opacity their + // overlap would be painted twice. + for opacity in [1.0f32, 0.5] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ii", "size": 40})); + let kids = children_of(&s, g); + let dx = shape_box(&s, kids[0]).x0 - shape_box(&s, kids[1]).x0 + 2.0; + s.execute("object.move", &json!({"ids": [kids[1]], "dx": dx, "dy": 6})).unwrap(); + s.execute("select.set", &json!({"ids": kids})).unwrap(); + let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap(); + let paths = children_of(&s, c); + s.edit("test", |d, _| { + // Make Compound Path turns the second glyph's contours the other way round. + for p in &paths { + let data = d.node_mut(NodeId(*p)).unwrap().path_data_mut().unwrap(); + let b = data.to_bezpath(); + if kurbo::Shape::area(&b) < 0.0 { + *data = vectorcraft_geom::PathData::from_bezpath(&b.reverse_subpaths()); + } + } + let n = d.node_mut(NodeId(c)).unwrap(); + n.opacity = opacity; + if let NodeKind::Compound { rule, .. } = &mut n.kind { + *rule = vectorcraft_geom::FillRule::NonZero; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})); + if opacity == 1.0 { + let r = r.unwrap(); + assert_eq!(r["texts"], json!(["i", "i"]), "opaque, the two lines become type: {r}"); + } else { + assert!(r.is_err(), "translucent, the compound stays an outline: {r:?}"); + } + } +} + #[test] fn overlapping_exact_glyphs_stay_an_outline_when_near_matches_are_allowed() { // Exact parts the even-odd rule rejects stay rejected when the near phase finds them again. diff --git a/docs/mcp.md b/docs/mcp.md index bb74d45a8f..dcaccb2992 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11338,7 +11338,9 @@ whose inner contour runs the same way as its outer one paints its center, so a r outline tolerance across in some direction, turned or not, cannot be checked this way and stays an outline: at `tolerance` 0.05, a counter 10 units wide in a 100 by 100 shape, or a 60 by 10 one turned 45 degrees. So does a shape whose outline is too large to check. The glyphs of a compound path that splits into several are set one beside another, so a split whose parts overlap where the shape's fill rule leaves the overlap unpainted (two o's on each -other under the even-odd rule) stays an outline. When the split with the longest runs fails that check, the split with the +other under the even-odd rule) stays an outline. A split whose parts overlap at all also stays an outline when the +compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, since the +glyphs may become separate objects that paint the overlap twice. When the split with the longest runs fails that check, the split with the shortest runs is checked, then the other complete splits in order, up to 32 splits per shape for exact matches and 32 for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are From 4e5345968b07c37dd78b9a392ac76db2e2955253 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:59:28 -0800 Subject: [PATCH 028/126] Retype: ranking near-match candidates counts against the comparison budget Near matching ranked every glyph of the shape's contour count and proportion before comparing the 256 closest, and that ranking was not counted against the point comparisons each shape and command may make, so a large selection over many fonts could spend unbounded time there. Each glyph ranked now takes one comparison per contour and one more from the same budget, the ranking keeps the closest glyphs without sorting the rest, and the shares of contour length are read without allocating per glyph. --- crates/text/src/retype.rs | 87 +++++++++++++++++++++++++++++---------- docs/mcp.md | 4 +- 2 files changed, 67 insertions(+), 24 deletions(-) diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 6df2f396f2..0a991c669f 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -451,7 +451,8 @@ impl RetypeIndex { /// than 8 contours. A shape is compared with at most the 256 glyphs closest to it in proportion /// (the spread-to-length ratio, and the share of the length each contour has), closest first, /// in at most 50 million point comparisons, and the index's calls make at most 2 billion in - /// all; once they are spent, the glyphs not yet compared are left out. + /// all (ranking a glyph by proportion counts as one per contour and one more); once they are + /// spent, the glyphs not yet ranked or compared are left out. pub fn near_matches(&self, shape: &BezPath, tolerance: f64) -> Vec { // NaN too. if tolerance.is_nan() || tolerance <= 0.0 { @@ -463,30 +464,12 @@ impl RetypeIndex { return vec![]; } let Some(s) = near_signature(shape) else { return vec![] }; - let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; - let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); - let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); - let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + if !self.buckets.contains_key(&s.contours) { + return vec![]; + } let tol = s.spread * OUTLINE_TOLERANCE.max(3.0 * tolerance); let mut shape_flat: Option> = None; let mut out: Vec<(usize, GlyphMatch)> = vec![]; - // The glyphs closest to the shape in proportion, at most NEAR_FITS, closest first: their - // spread-to-length ratio, and the share of the length each contour has, longest first. - let shares = |sig: &Signature| { - let total: f64 = sig.lens.iter().sum(); - let mut v: Vec = sig.lens.iter().map(|l| l / total).collect(); - v.sort_by(|a, b| b.total_cmp(a)); - v - }; - let own = shares(&s); - let apart = |e: &Entry| { - let d = (e.sig.invariant - s.invariant).abs() / s.invariant + shares(&e.sig).iter().zip(&own).map(|(a, b)| (a - b).abs()).sum::(); - if d.is_finite() { d } else { f64::INFINITY } - }; - let mut near: Vec<(f64, &Entry)> = - list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi).map(|e| (apart(e), e)).collect(); - near.sort_by(|a, b| a.0.total_cmp(&b.0)); - near.truncate(NEAR_FITS); // This call's allowance comes out of the index's budget in one step, so calls that overlap // never spend the same comparisons; what it leaves unspent goes back afterward. let mut seen = self.near_work.load(Ordering::Acquire); @@ -497,6 +480,7 @@ impl RetypeIndex { Err(now) => seen = now, } }; + let near = self.ranked_near(&s, &mut work); for (_, e) in near { if work == 0 { break; @@ -535,6 +519,47 @@ impl RetypeIndex { keep_per_face(&mut out); out.into_iter().map(|(_, m)| m).collect() } + + /// The glyphs of as many contours as near-matching shape `s` that are closest to it in + /// proportion, at most [`NEAR_FITS`], closest first: their spread-to-length ratio, and the + /// share of the length each contour has, longest first. Ranking a glyph takes one comparison + /// per contour, and one more, from `work`; once it is spent, the glyphs not yet ranked are + /// left out. + fn ranked_near(&self, s: &Signature, work: &mut u64) -> Vec<(f64, &Entry)> { + let Some(list) = self.buckets.get(&s.contours) else { return vec![] }; + let lo = s.invariant * (1.0 - NEAR_INVARIANT_SLACK); + let hi = s.invariant * (1.0 + NEAR_INVARIANT_SLACK); + let start = list.partition_point(|i| self.entries.get(*i).is_some_and(|e| e.sig.invariant < lo)); + // Each contour's share of the length, longest first (a near-matched shape has at most + // MAX_NEAR_CONTOURS contours, and the glyphs ranked as many). + let shares = |sig: &Signature| { + let mut v = [0.0f64; MAX_NEAR_CONTOURS]; + let total: f64 = sig.lens.iter().sum(); + for (o, l) in v.iter_mut().zip(&sig.lens) { + *o = l / total; + } + v.sort_by(|a, b| b.total_cmp(a)); + v + }; + let own = shares(s); + let apart = |e: &Entry| { + let d = (e.sig.invariant - s.invariant).abs() / s.invariant + shares(&e.sig).iter().zip(&own).map(|(a, b)| (a - b).abs()).sum::(); + if d.is_finite() { d } else { f64::INFINITY } + }; + let cost = s.contours as u64 + 1; + let mut near: Vec<(f64, &Entry)> = vec![]; + for e in list.iter().skip(start).filter_map(|i| self.entries.get(*i)).take_while(|e| e.sig.invariant <= hi) { + let Some(left) = work.checked_sub(cost) else { break }; + *work = left; + near.push((apart(e), e)); + } + if near.len() > NEAR_FITS { + near.select_nth_unstable_by(NEAR_FITS, |a, b| a.0.total_cmp(&b.0)); + near.truncate(NEAR_FITS); + } + near.sort_by(|a, b| a.0.total_cmp(&b.0)); + near + } } /// Turns of one glyph [`RetypeIndex::near_matches`] keeps, at most: its pose and its alternatives. @@ -2181,6 +2206,24 @@ mod tests { assert_eq!(index.near_work.load(Ordering::Acquire), 0); } + #[test] + fn ranking_near_match_candidates_takes_from_the_work_budget() { + let db = FontDb::global(); + let face = db.face("Source Sans 3", "Regular").unwrap(); + let gid = face.mapped_chars().iter().find(|(c, _)| *c == 'o').map(|(_, g)| *g).unwrap(); + let shape = Affine::translate((100.0, 200.0)) * Affine::scale(0.04) * simplified(&db.outline_uncached(&face, gid), 4.0); + let index = RetypeIndex::build_near(db, [face], &BTreeSet::new(), &[near_key(&shape).unwrap()]); + let s = near_signature(&shape).unwrap(); + let mut all = u64::MAX; + let ranked = index.ranked_near(&s, &mut all).len(); + assert!(ranked >= 1, "the o is ranked"); + assert_eq!(u64::MAX - all, ranked as u64 * 3, "each glyph of two contours takes three"); + // Enough to rank one glyph of two contours and nothing more. + let mut work = 4; + assert_eq!(index.ranked_near(&s, &mut work).len(), 1); + assert_eq!(work, 1); + } + #[test] fn a_round_glyph_with_an_off_centre_counter_near_matches_at_its_turn() { // A round outer contour fits the shape at every turn; only the counter, off the centre, diff --git a/docs/mcp.md b/docs/mcp.md index dcaccb2992..edbcdcb3f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11345,8 +11345,8 @@ shortest runs is checked, then the other complete splits in order, up to 32 spli for near matches; when none passes, the shape stays an outline. Glyphs fused into one contour are not split, and a compound path of more than 256 groups, 512 contours or 65,536 path elements is matched whole only. One command groups at most 16,384 contours, in selection order; the shapes after them are matched whole only. Near matching compares a shape with at most the 256 glyphs closest to it in proportion, in at -most 50 million point comparisons per shape and 2 billion per command; past them, the glyphs not yet compared are left -out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in +most 50 million point comparisons per shape and 2 billion per command, ranking a glyph by proportion counting as one +comparison per contour and one more; past them, the glyphs not yet ranked or compared are left out. It looks glyphs up for at most 1,024 distinct shapes and runs per command: every selected shape first, in selection order, then the runs of groups of the compound paths. Glyphs close only to the shapes and runs past that limit are not looked up. At most 262,144 glyphs are drawn to check whether they could near match, and at most 32,768 are indexed for it, each face taking an equal share of both; of a face's glyphs, those closest to the selected shapes From c5959c36ae153b196bc70e93349ef96f2a443a68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 05:43:25 -0800 Subject: [PATCH 029/126] Retype: glyphs that fit several fonts equally often take the font they fit closest in all Each shape votes for every face it fits, and each glyph is set in the face with the most votes. When faces tied, each glyph took its own closest face, so one line could be set in several fonts. With Noto Sans CJK SC loaded, simplified Source Sans 3 outlines of "Tim" fit both faces (and Noto Sans Hebrew) three times each: T and m took Source Sans 3 and i took Noto Sans CJK SC, so T and m were left as lone outlines. A tie now goes to the face with the least leftover distance summed over the shapes that fit it, so every glyph that fits that face takes it. --- crates/engine/src/cmd/retype.rs | 46 +++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b464696542..0885ce4ddd 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -1578,21 +1578,40 @@ fn retype(s: &mut Session, p: &Value) -> Result { }) .collect(); // The face most shapes match, so a glyph several fonts share is set in the same font as - // the glyphs around it. - let mut votes: Vec<(u32, usize)> = vec![]; + // the glyphs around it. Among faces that as many shapes match, the one whose glyphs fit + // them closest in all (the least leftover distance summed over those shapes), so every + // part that fits it takes the same face, exact matches as near ones. Simplified outlines + // of one font can nearly fit another font's look-alike glyphs, some of them more closely. + // A part's matches are all exact or all near, so the distances a face sums compare alike. + let mut votes: Vec<(u32, usize, f64)> = vec![]; for ms in found.iter().flatten() { - // Each shape votes once for each face it fits. - let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); - faces.sort_unstable(); - faces.dedup(); - for f in faces { - match votes.iter_mut().find(|(v, _)| *v == f) { - Some(v) => v.1 += 1, - None => votes.push((f, 1)), + // Each shape votes once for each face it fits, with the leftover distance of its + // closest glyph in that face. + let mut faces: Vec<(u32, f64)> = vec![]; + for m in ms { + let residual = if m.residual.is_finite() { m.residual } else { f64::INFINITY }; + match faces.iter_mut().find(|(f, _)| *f == m.face.id()) { + Some(f) => f.1 = f.1.min(residual), + None => faces.push((m.face.id(), residual)), + } + } + for (f, residual) in faces { + match votes.iter_mut().find(|(v, ..)| *v == f) { + Some(v) => { + v.1 += 1; + v.2 += residual; + } + None => votes.push((f, 1, residual)), } } } - let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); + let rank = |face: u32| votes.iter().find(|(f, ..)| *f == face).map_or((0, f64::INFINITY), |v| (v.1, v.2)); + // Most votes, then the least summed distance, then the first (the matches come upright and + // closest first). + let ranked = |(i, a): &(usize, &GlyphMatch), (j, b): &(usize, &GlyphMatch)| { + let ((va, da), (vb, db)) = (rank(a.face.id()), rank(b.face.id())); + va.cmp(&vb).then(db.total_cmp(&da)).then(j.cmp(i)) + }; let mut lines: Vec = vec![]; let mut unmatched = vec![]; // An unmatched shape between glyphs ends the line: the type after it is painted after it. @@ -1610,9 +1629,8 @@ fn retype(s: &mut Session, p: &Value) -> Result { } glyphs_of.insert(pc.id, parts.len()); for ms in parts { - // The part's candidates in the face most shapes fit (the first such face, as the - // matches come upright and closest first). - let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + // The part's candidates in the face most shapes fit (see `ranked`). + let face = ms.iter().enumerate().max_by(ranked).map(|(_, m)| m.face.id()); let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); let joined = match lines.last_mut() { Some(l) if open => join(l, pc, &cands), From f9c00a5ae5e6dabe6da128b16815f7cd84df0968 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 06:26:51 -0800 Subject: [PATCH 030/126] Live Paint: graphic styles on a group's contents give fills to its faces and strokes to its edges Follows #8765. graphicStyle.apply with target "contents" gave every face and edge of a Live Paint group the whole style, so faces drew the style's strokes along their outlines and edges drew its fills. Each face now takes only the style's fills and each edge only its strokes, with or without add, and neither is linked to the style. An add that gives a face or edge nothing leaves it and its link as they are, and an apply that changes nothing records no undo step. appearance.clear on the contents leaves a face one empty fill and an edge one empty stroke, and appearance.reduceToBasic keeps only a face's fill and only an edge's stroke. Docs: docs/mcp.md, params text, docs/target-app-parity.md. --- crates/engine/src/cmd/appearance.rs | 32 ++++++++++- crates/engine/src/cmd/style.rs | 23 ++++++-- crates/engine/src/tests/build.rs | 87 +++++++++++++++++++++++++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 5 files changed, 143 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 3b23d62634..037983da5c 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Clear Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), 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, and the art of a graph design in a series, which is left out: 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", + "{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own; in the contents of a Live Paint group, a face one empty fill and an edge one empty stroke) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), 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, and the art of a graph design in a series, which is left out: 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", has_doc, clear_appearance ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Reduce to Basic Appearance", ["Window", "Appearance"], None, - "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: 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 (of a line, only what the edit changes)", + "{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked; in the contents of a Live Paint group, a face keeps only the fill and an edge only the stroke), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: 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 (of a line, only what the edit changes)", has_doc, reduce_basic ), @@ -529,6 +529,24 @@ pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result Result<(HashSet, HashSet)> { + if !targets_contents(p)? { + return Ok((HashSet::new(), HashSet::new())); + } + let (faces, edges, _) = super::paint::live_paint_split(&s.doc()?.doc, &appearance_roots(s, p)?); + Ok((faces, edges)) +} + +/// Remove from `n` its stroke rows (`fill`) or its fill rows: a Live Paint face draws fills and an edge strokes. +pub(crate) fn keep_rows_of_kind(n: &mut Node, fill: bool) { + if n.appearance.items.iter().any(|it| it.is_fill() != fill) { + n.appearance.items.retain(|it| it.is_fill() == fill); + } +} + /// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series. const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it"; @@ -1044,12 +1062,17 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { fn clear_appearance(s: &mut Session, p: &Value) -> Result { let ids = require_whole_targets(s, p, "appearance.clear")?; + let (faces, edges) = contents_parts(s, p)?; // When every object is cleared already, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); super::overprint::edit_counted(s, "Clear Appearance", |d| { for id in &ids { if let Some(n) = d.node_mut(*id) { clear(n); + // A Live Paint group's face keeps an empty fill and its edge an empty stroke. + if faces.contains(id) || edges.contains(id) { + keep_rows_of_kind(n, faces.contains(id)); + } super::object::snap_if_aligned(n); } } @@ -1284,6 +1307,7 @@ fn is_group(n: &Node) -> bool { fn reduce_basic(s: &mut Session, p: &Value) -> Result { let ids = require_whole_targets(s, p, "appearance.reduceToBasic")?; + let (faces, edges) = contents_parts(s, p)?; // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); // The Appearance panel's active row (a row of the first selected object's stack, and in each @@ -1322,6 +1346,10 @@ fn reduce_basic(s: &mut Session, p: &Value) -> Result { st.blend = BlendMode::Normal; n.appearance.items.push(AppearanceItem::Stroke(st)); } + // A Live Paint group's face keeps only its fill and its edge only its stroke. + if faces.contains(id) || edges.contains(id) { + keep_rows_of_kind(n, faces.contains(id)); + } super::object::snap_if_aligned(n); } } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 1b5fec0a3b..14c6957e23 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -31,7 +31,7 @@ pub fn specs() -> Vec { "Apply Graphic Style", ["Window", "Graphic Styles"], None, - "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: 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 (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", + "{name, add?: bool, ids?|id? (layers too), target?: \"object\"|\"contents\"} give the objects (default: the selection; a group or layer itself, its fills and strokes painting its members and its effects applying to them as one piece; target contents: the objects inside instead) the style's appearance, opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks. In the contents of a Live Paint group, each face takes only the style's fills and each edge only its strokes, and neither is linked. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (with `add`: of the kinds of row the style shows) and, without `add`, the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: 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 (with `add`: of the kinds of row the style shows) and, without `add`, its object opacity and blend mode for every label or line of its kind. With nothing selected (and no ids) the next object drawn takes the style instead (see appearance.newArt) → {newArt: true}", has_doc, style_apply ), @@ -351,6 +351,9 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { // The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves, // and a style added on top unlinks them. let groups = super::appearance::stood_for(&own, &ids); + // In the contents of a Live Paint group, a face takes the style's fills and an edge its strokes. + let (faces, edges) = super::appearance::contents_parts(s, p)?; + let part = |id: &NodeId| (faces.contains(id) || edges.contains(id)).then(|| faces.contains(id)); if ids.is_empty() { if p.get("ids").is_some() || p.get("id").is_some() { return Err(bad("graphicStyle.apply", "no such objects")); @@ -361,13 +364,20 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "newArt": true })); } let before = s.doc()?.doc.clone(); - s.edit("Apply Graphic Style", |d, _| { + // An apply that changes nothing (a fill-only style added to edges only) records no undo step. + super::overprint::edit_counted(s, "Apply Graphic Style", |d| { if add { let g = d.graphic_styles[i].clone(); for id in &ids { if let Some(n) = d.node_mut(*id) { let ap = g.appearance_on(n).into_owned(); - n.appearance.items.extend(ap.items); + let kind = part(id); + let rows: Vec<_> = ap.items.into_iter().filter(|it| kind.is_none_or(|fill| it.is_fill() == fill)).collect(); + // A face or edge the style adds nothing to keeps its appearance and its link. + if kind.is_some() && rows.is_empty() && ap.effects.is_empty() { + continue; + } + n.appearance.items.extend(rows); n.appearance.effects.extend(ap.effects); n.extras_mut().graphic_style = None; } @@ -387,13 +397,18 @@ fn style_apply(s: &mut Session, p: &Value) -> Result { let mut shared = None; for id in &ids { apply_style(d, *id, &g, &mut shared, chars); + // A face or edge that keeps only the rows of its kind no longer has the style's look, so it is not linked. + if let (Some(fill), Some(n)) = (part(id), d.node_mut(*id)) { + super::appearance::keep_rows_of_kind(n, fill); + n.extras_mut().graphic_style = None; + } } super::appearance::clear_stood_for(d, &groups); super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, true); // A label or graph line keeps its new rows for its kind. super::graph::capture_label_rows(d, &ids); } - Ok(()) + Ok(usize::from(*d != *before)) })?; ok() } diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 316e9b8ffc..b37550d5c5 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4630,6 +4630,93 @@ fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_it assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused"); } +/// Whether every face of Live Paint group `g` holds only fill rows and every edge only stroke rows. +fn parts_hold_their_kind(s: &Session, g: NodeId) -> bool { + let (faces, edges) = part_looks(s, g); + faces.iter().all(|a| a.items.iter().all(|it| it.is_fill())) && edges.iter().all(|a| a.items.iter().all(|it| !it.is_fill())) +} + +/// A graphic style applied to the contents of a Live Paint group, replacing their appearance or added to it, gives +/// the faces its fills and the edges its strokes, and the faces and edges are not linked to it. +#[test] +fn live_paint_group_contents_take_a_graphic_style_by_kind() { + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for add in [false, true] { + let mut s = session(); + let g = live(&mut s); + let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Both", "id": r.0})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Both", "target": "contents", "add": add})).unwrap(); + assert!(parts_hold_their_kind(&s, g), "add {add}: faces hold fills and edges strokes"); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().all(|a| a.items.iter().any(|it| *it.paint() == red)), "add {add}: each face takes the style's fill"); + assert!(edges.iter().all(|a| a.items.iter().any(|it| *it.paint() == blue)), "add {add}: each edge takes the style's stroke"); + let n = node(&s, g); + let mut parts = vectorcraft_tools::builder::faces(&n).into_iter().chain(vectorcraft_tools::builder::edges(&n)); + assert!(parts.all(|p| p.extras().graphic_style.is_none()), "add {add}: no face or edge is linked"); + } +} + +/// A fill-only graphic style added to the contents of a Live Paint group without faces changes nothing and records no +/// undo step. +#[test] +fn live_paint_group_contents_without_faces_take_no_fill_only_style() { + let mut s = session(); + let g = live(&mut s); + let faces: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !faces.contains(&c.id)); + Ok(()) + }) + .unwrap(); + let r = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.edit("t", |d, _| { + let fill = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#ff0000").unwrap()))); + d.node_mut(r).unwrap().appearance = vectorcraft_doc::Appearance { items: vec![fill], ..Default::default() }.into(); + Ok(()) + }) + .unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Fill", "id": r.0})).unwrap(); + // The edges are linked to a style of their own, which they keep. + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("graphicStyle.new", &json!({"name": "Edge", "id": edge.0})).unwrap(); + assert!(node(&s, g).children().unwrap().iter().any(|c| c.extras().graphic_style.is_some()), "an edge is linked"); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (before, undo) = (node(&s, g), s.doc().unwrap().history.undo.len()); + s.execute("graphicStyle.apply", &json!({"name": "Fill", "target": "contents", "add": true})).unwrap(); + assert_eq!(node(&s, g), before, "the edges keep their rows and their link"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); +} + +/// Clear Appearance and Reduce to Basic Appearance on the contents of a Live Paint group leave each face with fill +/// rows only and each edge with stroke rows only. +#[test] +fn live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind() { + for cmd in ["appearance.clear", "appearance.reduceToBasic"] { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + // A face and an edge given rows of the other kind through their own ids. + let n = node(&s, g); + let (face, edge) = (vectorcraft_tools::builder::faces(&n)[0].id, vectorcraft_tools::builder::edges(&n)[0].id); + s.execute("appearance.addStroke", &json!({"ids": [face.0]})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [edge.0]})).unwrap(); + assert!(!parts_hold_their_kind(&s, g), "{cmd}: the face and the edge hold rows of the other kind"); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute(cmd, &json!({"target": "contents"})).unwrap(); + assert!(parts_hold_their_kind(&s, g), "{cmd}: faces hold fills and edges strokes"); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().chain(&edges).all(|a| !a.items.is_empty()), "{cmd}: each face and edge keeps a row"); + } +} + /// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit /// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and /// leaves the settings for new art as they are. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..2b70c411c3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5702,11 +5702,15 @@ fills and strokes above it paint over the members (characters), those below unde `appearance.contents_index`. The `appearance.*`, `effect.*` and `graphicStyle.apply` commands edit the selected objects themselves (a group's own stack; layers through `ids`) or, with `target: "contents"`, the objects inside the groups and layers. In a Live Paint group those are its faces and edges, not its hidden source paths. -`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only; a selected group left with only its hidden source paths is returned without a change. A +`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only. On a +selected group left with only its hidden source paths, either command changes nothing. A fill or stroke command with an `item` and `target: "contents"` (such as `paint.setFill`, `stroke.set`, `paint.invert`, `paint.setGradientGeom` and `object.setOverprint`) changes the faces for a fill row and the edges for a stroke row. The row commands (`appearance.setItem`, `appearance.removeItem` and the others) find their rows on each -face and edge as on any other object in the contents. +face and edge as on any other object in the contents. `graphicStyle.apply` gives each face only the style's fills and +each edge only its strokes, with or without `add`, and links neither to the style. `appearance.clear` leaves a face +one empty fill and an edge one empty stroke, and `appearance.reduceToBasic` keeps only a face's fill and only an +edge's stroke. `appearance.targetContents` selects a group's members (double-clicking the Contents row). SVG and PDF export bake a group's own fills, strokes and geometry effects into paths; its raster effects stay a filter on the whole group in SVG and become an image of the whole group in PDF. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..7a211b564a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1935,7 +1935,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. As VectorCraft's own rule, a Live Paint edit that changes nothing records no undo step, keeps the redo steps and leaves a saved document saved: a Live Paint Bucket click or drag over faces that already have the fill, a stroke on an edge that already has the paint and weight, Gap Options OK with the options the groups have and no gap to close, and Make or Merge with one Live Paint group alone. Such a fill or stroke also leaves the recent colors as they are. Regression tests: `live_paint_fill_same_paint_is_no_op`, `live_paint_bucket_click_with_the_face_paint_is_no_op`, `live_paint_stroke_edge_same_paint_and_width_is_no_op`, `live_paint_gap_options_same_values_are_no_op`, `live_paint_gap_options_close_without_gaps_is_no_op`, `live_paint_make_existing_group_is_no_op` and `live_paint_merge_single_group_is_no_op` in `crates/engine/src/tests/build.rs`, and `ok_on_unchanged_options_records_no_undo_step` in `crates/ui-egui/src/dialogs/live_paint_gaps.rs`. As VectorCraft's own rule, the Live Paint Bucket replaces all of a face's fills, or all of an edge's strokes, with one fill or stroke of the paint, shown, fully opaque and blending normally, so a lower fill or stroke no longer draws under the new paint and a fill or stroke of none leaves nothing of that kind drawing; the face's strokes, the edge's fills, the part's own opacity and the topmost shown stroke's dashes, caps and arrowheads stay as they are, and a part that already has only that one fill or stroke records no undo step. [The help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) says the tool paints faces with the current fill and edges with the current stroke. Regression tests: `live_paint_bucket_replaces_every_fill_row`, `live_paint_stroke_edge_replaces_every_stroke_row` and `live_paint_stroke_edge_paints_the_shown_stroke` in `crates/engine/src/tests/build.rs`. - As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects}`. + As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges; a graphic style gives the faces only its fills and the edges only its strokes, and Clear Appearance and Reduce to Basic Appearance leave the faces only fill rows and the edges only stroke rows. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects, live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group, live_paint_group_eyedropper_does_not_target_its_own_source_group, live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit, live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents, live_paint_group_contents_take_a_graphic_style_by_kind, live_paint_group_contents_without_faces_take_no_fill_only_style, live_paint_group_contents_clear_and_reduce_keep_each_part_to_its_kind}`. As VectorCraft's own rule, `tool.setOption` for the Live Paint Bucket and the Live Paint Selection tool, chosen or not, checks every value before it sets any: a switch that is not `true` or `false`, a `color` that is not an RGB color or a layer color's name, or that has an alpha part, a `width` that is not a number and an option the tool does not have give an error naming the option, and nothing is set or saved. A `width` outside 1 to 20 px is still set to the nearest end of that range. Saved settings that hold an invalid value still load, and the tool keeps its default for that option. Evidence: `tests::build::{live_paint_tool_options_refuse_invalid_values_and_change_nothing, live_paint_tool_options_take_rgb_colors_and_clamp_the_width, live_paint_tools_load_saved_settings_with_invalid_values}`. As VectorCraft's own rule, `tool.setOption` for the Shape Builder, chosen or not, checks every value the same way: a switch that is not `true` or `false`, a `pickColorFrom` or `selection` that is not one of its names, a `gapLength` that is not a number, a `highlightColor` that is not an RGB color or a layer color's name, or that has an alpha part, and an option the tool does not have give an error naming the option, and nothing is set or saved. A `gapLength` outside 0 to 72 pt is still set to the nearest end of that range. Evidence: `tests::build::{shape_builder_tool_options_refuse_invalid_values_and_change_nothing, shape_builder_tool_options_take_valid_values_and_clamp_the_gap}`. A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. From 4df75635da84c5dc3979b4b4212f1e7ce7a308bd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:14:26 -0800 Subject: [PATCH 031/126] Tests: a confined single-file PDF of several artboards checks every artboard it carries A single-file PDF with Preserve Editing of an artboard range carries the whole document, so a confined export of it checks the links on every chosen artboard. The new test exports artboards 1-2 as one PDF, then places an image linked outside the read roots on the second artboard only and checks that the export is refused without writing its folder. It also checks that assets.export refuses pdfs `single`, the source that pdfs `single` does not accept. --- crates/engine/src/tests/links.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 5dd3357641..268fa79ad0 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2617,6 +2617,37 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } +/// A confined caller's single-file PDF with Preserve Editing of several artboards carries the art +/// of every artboard on its pages: an image linked outside the read roots on the second artboard +/// alone refuses it. A single-file PDF of assets is refused before any link is checked. +#[test] +fn confined_single_file_pdf_checks_every_artboard_it_carries() { + use crate::file_access::{AutomationRoots, confine}; + + let away = Folder::new("single-pdf-away"); + let home = Folder::new("single-pdf-home"); + let photo = away.file("photo.png"); + write(&photo, &png(60, 30, RED)); + let mut s = session(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); + s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 200, "height": 200})).unwrap(); + let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); + let p = |folder: &str| json!({"range": "1-2", "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); + let r = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("plain"))).unwrap_or_else(|e| panic!("{e}")); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); + let r = s.execute("file.place", &json!({"path": photo, "at": [2100, 100]})).unwrap(); + assert_eq!(r["linked"], true, "{r}"); + let e = confine(roots.as_ref(), || s.execute("document.exportForScreens", &p("linked"))).expect_err("second artboard links outside").to_string(); + assert!(e.contains("a linked image file is outside the read roots"), "{e}"); + assert!(!Path::new(&home.file("linked")).exists(), "the refused export writes no folder"); + let asset = s.execute("assets.add", &json!({"ids": [rect.0]})).unwrap()["assets"][0].as_u64().unwrap(); + let assets = json!({"assets": [asset], "folder": home.file("assets"), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); + let e = confine(roots.as_ref(), || s.execute("assets.export", &assets)).expect_err("single-file PDF of assets").to_string(); + assert!(e.contains("pdfs `single` writes artboards as the pages of one PDF"), "{e}"); + assert!(!Path::new(&home.file("assets")).exists(), "the refused export writes no folder"); +} + /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open From 3023335b59b2f2e96afb12e27d80cb4fc8290c2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:09:24 -0800 Subject: [PATCH 032/126] Mesh: picked points stay picked between the mesh-point tools Gradient mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso now stay picked when another of these tools is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl click, so a fill color chosen afterwards recolors just those points. Before, only a switch to or from the Eyedropper kept them. Any other tool, Group Selection included, drops them. Session::switch_tool, lend_selection_tool and give_back_tool share one test of which tools pick mesh points. Giving the tool back leaves the lender's picks alone when they did not change, so the Mesh tool keeps the point whose handles it shows. Tests: crates/engine/src/tests/mesh_picks.rs. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/mesh_picks.rs | 107 +++++++++++++++++++++ crates/engine/src/tooling.rs | 36 ++++--- crates/tools/src/addons/polygonal_lasso.rs | 2 +- crates/tools/src/direct.rs | 2 +- crates/tools/src/meshblend.rs | 2 +- crates/tools/src/meshedit.rs | 2 +- crates/tools/src/xform/wand.rs | 2 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 10 files changed, 142 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/tests/mesh_picks.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c39c88cbbb..d92bcb7d71 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -112,6 +112,7 @@ mod live; mod livecorners; mod maskview; pub(super) mod menucmds; +mod mesh_picks; mod nativefile; mod newart; mod newdoc; diff --git a/crates/engine/src/tests/mesh_picks.rs b/crates/engine/src/tests/mesh_picks.rs new file mode 100644 index 0000000000..0159709fdb --- /dev/null +++ b/crates/engine/src/tests/mesh_picks.rs @@ -0,0 +1,107 @@ +//! Gradient mesh points picked with one of the tools that pick them (the Mesh tool, Direct +//! Selection, the Lasso, the Polygonal Lasso) stay picked when another of them is chosen, or lent +//! for a Cmd-click, so a fill color then recolors just them. + +use serde_json::json; +use vectorcraft_color::Color; +use vectorcraft_doc::NodeKind; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use crate::*; + +/// A session with a selected 1 x 1 gradient mesh (four white points) at (10, 10), 50 pt square. +fn mesh_session() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let m = NodeId(s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + (s, m) +} + +fn colors(s: &Session, m: NodeId) -> Vec { + match &s.doc().unwrap().doc.node(m).unwrap().kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect(), + k => panic!("not a mesh: {k:?}"), + } +} + +/// Click mesh point `i` of `m` with the active tool. +fn press(s: &mut Session, m: NodeId, i: usize, mods: Mods) { + let q = match &s.doc().unwrap().doc.node(m).unwrap().kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), ViewInfo::default()).unwrap(); + } +} + +/// A point picked with the Mesh tool stays picked through Direct Selection, the Lasso and the +/// Polygonal Lasso and back to the Mesh tool: each fill color recolors just that point. +#[test] +fn mesh_point_picks_carry_between_the_mesh_point_tools() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let white = colors(&s, m)[0]; + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + for (tool, hex, c) in [ + ("directSelection", "#0000ff", Color::rgb8(0, 0, 255)), + ("lasso", "#00ff00", Color::rgb8(0, 255, 0)), + ("polygonalLasso", "#ff0000", Color::rgb8(255, 0, 0)), + ("directSelection", "#ffff00", Color::rgb8(255, 255, 0)), + ("mesh", "#00ffff", Color::rgb8(0, 255, 255)), + ] { + s.select_tool(tool, v).unwrap(); + s.execute("paint.setFill", &json!({"color": hex})).unwrap(); + assert_eq!(colors(&s, m), [c, white, white, white], "{tool} recolors only the picked point"); + } +} + +/// A point picked with Direct Selection stays picked for the Mesh tool. +#[test] +fn direct_selection_picks_carry_to_the_mesh_tool() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let white = colors(&s, m)[0]; + s.select_tool("directSelection", v).unwrap(); + press(&mut s, m, 2, Mods::default()); + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(colors(&s, m), [white, white, Color::rgb8(0, 0, 255), white]); +} + +/// The Selection tool picks no mesh points: after it, the Mesh tool starts with none picked, and a +/// fill color leaves every point as it was. +#[test] +fn a_tool_that_picks_no_mesh_points_drops_the_picks() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let before = colors(&s, m); + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(colors(&s, m), before, "no point is picked"); +} + +/// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a +/// Shift-click adds to them, and gives back what it left picked. +#[test] +fn the_lent_direct_selection_carries_the_mesh_tools_picks() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let white = colors(&s, m)[0]; + // Cmd lends the selection tool chosen last. + s.select_tool("directSelection", v).unwrap(); + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + press(&mut s, m, 3, Mods { cmd: true, shift: true, ..Default::default() }); + assert_eq!(s.tool_id(), "mesh"); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let b = Color::rgb8(0, 0, 255); + assert_eq!(colors(&s, m), [b, white, white, b], "both points stay picked"); +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7b1caffb7c..7c1af811ed 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -186,12 +186,13 @@ impl Session { let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id))) .then(|| self.tool.options()) .filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end")); - // The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked - // for the Eyedropper, which samples into them (#8090), and for the tool after it. - let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper") + // The gradient mesh points the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso + // picked stay picked when another of these tools or the Eyedropper, which samples into + // them (#8090), is chosen: a fill color then recolors just them. None stay picked when + // none were. + let mesh_points = (Self::picks_mesh_points(id) && Self::picks_mesh_points(self.tool.id())) .then(|| self.tool.options().get("meshPoints").cloned()) - .flatten() - .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); + .flatten(); self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); @@ -208,6 +209,13 @@ impl Session { Ok(()) } + /// Does tool `id` pick gradient mesh points (its `meshPoints` option): the Mesh tool, Direct + /// Selection, the Lasso, the Polygonal Lasso and the Eyedropper? Group Selection, which + /// selects whole objects, does not. + fn picks_mesh_points(id: &str) -> bool { + matches!(id, "mesh" | "directSelection" | "lasso" | "polygonalLasso" | "eyedropper") + } + /// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the /// batch settled the tool's drag when it began, and the open interaction holds the batch's /// steps, which the batch keeps or rolls back as a whole. @@ -292,9 +300,9 @@ impl Session { // double-click or triple-click compares. self.tool.press_elsewhere(); let mut lent = self.make_tool(id); - // The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift - // click adds to (#8090). - if self.tool.id() == "eyedropper" { + // The gradient mesh points the lending tool picked (the Mesh tool's, the Lasso's, the + // Eyedropper's) are the lent tool's picks, which a Shift click adds to (#8090). + if Self::picks_mesh_points(self.tool.id()) && Self::picks_mesh_points(id) { let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); lent.set_option("meshPoints", &points); } @@ -312,10 +320,14 @@ impl Session { /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { let Some(lender) = self.lender.take() else { return Ok(()) }; - // The points the lent tool left picked go back to the Eyedropper, none when it unpicked - // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. - let mesh_points = - (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); + // The points the lent tool left picked go back to the tool it was lent to when that tool + // picks mesh points, none when it unpicked them all (#8090). Group Selection and the + // Selection tool pick no mesh points, so the tool keeps its own. Unchanged picks are not + // set again, so the Mesh tool keeps the point whose handles it shows. + let mesh_points = (Self::picks_mesh_points(lender.id()) && Self::picks_mesh_points(self.tool.id())) + .then(|| self.tool.options().get("meshPoints").cloned()) + .flatten() + .filter(|p| lender.options().get("meshPoints") != Some(p)); let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; diff --git a/crates/tools/src/addons/polygonal_lasso.rs b/crates/tools/src/addons/polygonal_lasso.rs index b212943117..2810b0b309 100644 --- a/crates/tools/src/addons/polygonal_lasso.rs +++ b/crates/tools/src/addons/polygonal_lasso.rs @@ -167,7 +167,7 @@ impl Tool for PolygonalLassoTool { self.mesh.options() } - /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + /// Pick the gradient mesh points the tool chosen before held (`meshPoints`). fn set_option(&mut self, key: &str, value: &serde_json::Value) { if key == "meshPoints" { self.mesh.set_options(value); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cd4432c3c8..c889671a6e 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -823,7 +823,7 @@ impl Tool for DirectSelectionTool { fn options(&self) -> Value { self.mesh.options() } - /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group + /// Direct Selection picks the gradient mesh points the tool chosen before held (`meshPoints`); Group /// Selection, which selects whole objects, does not. /// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture /// ([`DirectSelectionTool::mirrors`]). diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index c9ab307028..89e640d48e 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -360,7 +360,7 @@ impl Tool for MeshTool { fn options(&self) -> serde_json::Value { self.edit.options() } - /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + /// Pick the gradient mesh points the tool chosen before held (`meshPoints`). fn set_option(&mut self, key: &str, value: &serde_json::Value) { if key == "meshPoints" { self.edit.set_options(value); diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index 71ae329c4c..2dbeaf07a7 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -325,7 +325,7 @@ impl MeshEdit { } /// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the - /// points the Eyedropper held when the tool switched back. + /// points the tool chosen before (another mesh-point tool or the Eyedropper) held. pub fn set_options(&mut self, value: &Value) { if self.drag.is_some() { return; diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index d2074e386e..991f43881c 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -165,7 +165,7 @@ impl Tool for LassoTool { self.mesh.options() } - /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + /// Pick the gradient mesh points the tool chosen before held (`meshPoints`). fn set_option(&mut self, key: &str, value: &Value) { if key == "meshPoints" { self.mesh.set_options(value); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..a2dfff4bfa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14191,8 +14191,10 @@ away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options -(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching to the Eyedropper keeps them picked, its -options list them too, and the Mesh tool, Direct Selection or a Lasso chosen next picks them again. While a selected, editable mesh has +(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching between the Mesh tool, Direct Selection, +the Lasso, the Polygonal Lasso and the Eyedropper keeps them picked, and so does a Cmd/Ctrl-click with the selection +tool one of them lends; any other tool, Group Selection included, drops them. The Eyedropper's options list them too. +While a selected, editable mesh has points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo step, none when the color is unchanged. Other selected objects keep their paint. A click on one of those meshes, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..25b0e47a10 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1905,6 +1905,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. - **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. +- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterwards recolors just those points. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. From a04159b287372b9f17f4a7356d09c407f64d0f97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:39:10 -0800 Subject: [PATCH 033/126] Graphic Styles: Redefine Graphic Style keeps the own style of a path inside a series group linked to the target graphicStyle.redefine passed the redefined style to every path directly in a graph series group linked to it, and to every line and label of a linked Axes or Legend group, so a member linked to another style (the `from` style or a third one) was restyled and relinked to the target. Such a member now keeps its look and its link, in the `from` and the object forms; unlinked members and members still linked to the target follow as before. The group is still cleared and unlinked, and one undo takes it all back. --- crates/engine/src/cmd/graph/tests.rs | 139 +++++++++++++++++++++++++++ crates/engine/src/cmd/style.rs | 9 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 148 insertions(+), 5 deletions(-) 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/style.rs b/crates/engine/src/cmd/style.rs index 1b5fec0a3b..6e73e02e37 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 ), @@ -539,10 +539,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/docs/mcp.md b/docs/mcp.md index e7abf476a9..b7aaeb1161 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. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..311acbc012 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2124,7 +2124,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`). From 2d0389c8fdf0042820ba5d4483555e81dcb83e4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:44:44 -0800 Subject: [PATCH 034/126] Gradient: moving out of a freeform object ends the Lines mode line In freeform Lines mode, moving the pointer out of the object and back now ends the line being drawn, so the next click on the object starts a new line. The help page describes this way of starting another line in the same object: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262 The line ends on the first pointer move, with no button held, that leaves the object. The object counts as its path's area inside any clipping masks above it, plus its own painted art (stroke, glyphs); other art lying over it does not end the line, and outline view, a layer with Preview off and the path-only selection preferences do not shrink the area. Escape and a click off the art still end the line. --- crates/tools/src/xform/freeform.rs | 160 +++++++++++++++++++++++++++-- docs/target-app-parity.md | 1 + 2 files changed, 154 insertions(+), 7 deletions(-) diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index 89c6faa933..8a5a461a2b 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -8,14 +8,15 @@ //! //! Points mode (the Gradient panel's Draw toggle): a click inside the selected art adds a point //! there, coloured as the gradient is there. Lines mode: successive clicks draw a smooth line -//! through the points they add, until Escape (or a click off the art) ends it; clicking an -//! existing point first starts the line from it. Delete or Backspace removes the selected point. +//! through the points they add, until Escape, a click off the art or moving the pointer out of +//! the object ends it; clicking an existing point first starts the line from it. Delete or +//! Backspace removes the selected point. use serde_json::{Value, json}; use vectorcraft_color::freeform::LineHit; use vectorcraft_color::{Color, Freeform, FreeformMode, FreeformPoint}; use vectorcraft_doc::NodeId; -use vectorcraft_doc::hit::hit_test; +use vectorcraft_doc::hit::{HitOptions, hit_test, hit_test_visible_skipping}; use vectorcraft_geom::{Point, Shape, Vec2}; use super::paint_owner; @@ -183,6 +184,43 @@ fn on_art(cx: &ToolContext, p: Point) -> bool { hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| cx.selection.objects.contains(&paint_owner(cx.doc, h.leaf))) } +/// Is `p` on object `id`: inside its path's area (where a dragged point stays) and every clipping +/// mask above it, or on its own art where a click hits it with the art lying over it left out (a +/// stroke, type's glyphs)? +fn on_object(cx: &ToolContext, id: NodeId, p: Point) -> bool { + let Some(n) = cx.doc.node(id) else { return false }; + let ancestry = cx.doc.ancestry(id).unwrap_or_default(); + let contains = |shapes: &[(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)]| { + shapes.iter().any(|(bp, rule)| vectorcraft_geom::hit::fill_contains(bp, *rule, p)) + }; + // A mask with a live effect clips by the effect's result, which the hit test below measures. + let plain = |clip: &vectorcraft_doc::Node| { + let mut effects = false; + clip.walk(&mut |c| { + effects |= c.appearance.effects.iter().any(|e| e.visible) || c.appearance.items.iter().any(|i| i.effects().iter().any(|e| e.visible)); + }); + !effects + }; + let unmasked = || { + ancestry.iter().filter_map(|a| cx.doc.node(*a)).filter(|a| a.clips()).all(|a| { + a.children() + .and_then(|c| c.first()) + .is_none_or(|clip| clip.id == id || plain(clip) && contains(&vectorcraft_doc::hit::clip_regions(clip))) + }) + }; + if contains(&n.clip_shapes(None)) && unmasked() { + return true; + } + let mut keep = std::collections::HashSet::new(); + n.walk(&mut |c| { + keep.insert(c.id); + }); + keep.extend(ancestry); + // The art as painted, whatever the view and the path-only selection preferences. + let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ..cx.hit_options() }; + hit_test_visible_skipping(cx.doc, p, opt, &|n| !keep.contains(&n)).is_some_and(|h| h.leaf == id || h.ancestry.contains(&id)) +} + pub(super) fn press(cx: &ToolContext, a: &Annotator, p: Point) -> (Vec, Gesture) { let mut out = vec![]; let grab = if let Some(i) = a.point_at(cx, p) { @@ -293,8 +331,13 @@ pub(super) fn double_click(cx: &ToolContext, a: &Annotator, p: Point) -> Vec Date: Fri, 20 Nov 2026 15:02:06 -0800 Subject: [PATCH 035/126] Links: the Unembed code comment names TIFF among the stored formats An image that keeps CMYK inks is stored as TIFF, and Unembed writes it as a .tif file when the path has no extension. The comment above the format choice now lists TIFF with PNG, JPEG, GIF and WebP. --- crates/engine/src/cmd/links.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 9d0a0bbcb3..fccff66c0c 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2809,7 +2809,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("image {} is linked already", id.0))); } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; - // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. + // As stored (PNG, JPEG, GIF, WebP, or TIFF for an image that keeps CMYK inks), unless the path names another format. let stored = stored_extension(blob); let path = str_param(p, "path"); let ext = match path.map(fileio::extension) { From eb5635d04027425a48c2d1440279c957572ff786 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:02:12 -0800 Subject: [PATCH 036/126] Docs: Relink and Update Links keep a clipping mask edited in the document The PSD clipping-path entry said that links.update and links.relink leave a plain group whenever the new file names no clipping path. A clip group whose clipping path was changed in the document, and a clipping mask made in the document, are kept when Placement Options do not clip the image: a new file with no clipping path leaves the mask clipping the image, and a new file's clip group goes inside the mask. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..0efd8dffc7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2321,7 +2321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (its anchors, whether it is closed, or its fill rule) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From d9dba9c467ca37b06919000ea20812c9bbfa5642 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:02:27 -0800 Subject: [PATCH 037/126] Legacy .ai: gradient definitions are found by a key of their gradient Each gradient fill looked for its definition by comparing its gradient with every definition written so far, so a document with thousands of distinct gradients spent most of the export in these comparisons. The writer now keeps each definition's place under a key made from every field of its gradient, the same key the editing data's writer uses, which moves to a module both writers share. Each candidate under a key is still compared in full, and the first equal definition in definition order is used. Spot color names, written spot colors and fonts are also found through maps and sets, while the lists the file is written from keep their order. The written file is unchanged, byte for byte. On Linux, writing 10,006 gradient fills (5,000 distinct and 5,000 of 50 others) took 79 ms of thread CPU time through the index and 291 ms comparing each definition in turn (median of 7 runs, release build). --- crates/eps/src/ai_editing/writer/paints.rs | 23 +---- crates/eps/src/gradient_key.rs | 29 ++++++ crates/eps/src/legacy_ai/tests.rs | 113 +++++++++++++++++++++ crates/eps/src/legacy_ai/writer.rs | 54 ++++++++-- crates/eps/src/lib.rs | 2 + 5 files changed, 190 insertions(+), 31 deletions(-) create mode 100644 crates/eps/src/gradient_key.rs diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 5a850d7db3..f1573c39ba 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -3,7 +3,6 @@ use std::collections::HashMap; use std::fmt::Write; -use std::hash::{Hash, Hasher}; use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; @@ -14,6 +13,7 @@ use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2}; use super::{MAX_NEST, Writer, Xy}; use crate::ai_ops::{self, average, unit}; +use crate::gradient_key::gradient_key; use crate::ps; pub(in crate::ai_editing) const GRADIENTS: &str = @@ -64,27 +64,6 @@ fn same_gradient(a: &Gradient, b: &Gradient) -> bool { a == b } -/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its -/// bits, with -0 as 0); different gradients may share one. -fn gradient_key(g: &Gradient) -> u64 { - let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; - let mut h = std::hash::DefaultHasher::new(); - std::mem::discriminant(&g.kind).hash(&mut h); - std::mem::discriminant(&g.method).hash(&mut h); - (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); - for s in &g.stops { - let (model, c) = match s.color { - Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), - Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), - Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), - Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), - }; - (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); - (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); - } - h.finish() -} - /// The gradient definitions, in the order they are first used, found by name and by gradient /// without comparing each one. #[derive(Default)] diff --git a/crates/eps/src/gradient_key.rs b/crates/eps/src/gradient_key.rs new file mode 100644 index 0000000000..3bdb7f833a --- /dev/null +++ b/crates/eps/src/gradient_key.rs @@ -0,0 +1,29 @@ +//! A key of a gradient for the gradient definitions the legacy `.ai` writer +//! ([`crate::legacy_ai`]) and the editing data writer ([`crate::ai_editing`]) look up: the writers +//! keep each definition's place under its gradient's key and compare only the gradients that +//! share it. + +use std::hash::{Hash, Hasher}; + +use vectorcraft_color::{Color, Gradient}; + +/// A key of `g`: the same gradients have the same key (each number by its bits, with -0 as 0); +/// different gradients may share one. +pub(crate) fn gradient_key(g: &Gradient) -> u64 { + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut h = std::hash::DefaultHasher::new(); + std::mem::discriminant(&g.kind).hash(&mut h); + std::mem::discriminant(&g.method).hash(&mut h); + (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); + for s in &g.stops { + let (model, c) = match s.color { + Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), + }; + (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); + (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); + } + h.finish() +} diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 6018bc6920..2f5a528340 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1696,6 +1696,119 @@ fn colliding_gradient_and_spot_names_are_numbered_as_before() { assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}"); } +/// `doc` written with its gradient definitions found by comparing each in turn (`scanned`) or +/// through their index. +fn export_scanned(doc: &Document, scanned: bool) -> LegacyAiOutput { + let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() }; + super::writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned)); + let out = export_legacy_ai(doc, &o); + super::writer::SCANNED_DEFINITIONS.with(|s| s.set(false)); + out.unwrap() +} + +/// A document of rectangles filled with gradients: one with a gradient swatch `Sky` of its own; +/// `distinct` with gradients of their own; `reused` with one of `ramps` others in turn; one with a +/// gradient swatch `Dawn` whose gradient is the first of those `ramps`; two whose gradients differ +/// only in the sign of a zero offset; and two with the same gradient, whose midpoint is not a +/// number. +fn many_gradients(distinct: u16, reused: u16, ramps: u16) -> Document { + let mut doc = Document::new(1000.0, 1000.0); + let layer = doc.layers[0].id; + let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1)); + let mut paints = vec![gradient_from(Color::rgb(0.1, 0.2, 0.3), Some("Sky"))]; + for i in 0..distinct { + paints.push(gradient_from(Color::rgb(shade(i, distinct), 0.5, 0.0), None)); + } + for i in 0..reused { + paints.push(gradient_from(Color::cmyk(0.0, shade(i % ramps.max(1), ramps), 0.5, 0.0), None)); + } + paints.push(gradient_from(Color::cmyk(0.0, 0.0, 0.5, 0.0), Some("Dawn"))); + let stops = |offset: f32, midpoint: f32| { + let mut first = GradientStop::new(offset, Color::rgb(0.2, 0.3, 0.4)); + first.midpoint = midpoint; + let g = Gradient::new(GradientKind::Linear, vec![first, GradientStop::new(1.0, Color::BLACK)]); + Paint::Gradient(Box::new(GradientPaint::new(g))) + }; + paints.extend([stops(0.0, 0.5), stops(-0.0, 0.5), stops(0.0, f32::NAN), stops(0.0, f32::NAN)]); + for (i, paint) in (0u16..).zip(paints) { + let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40 % 40) * 25.0); + let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + doc +} + +/// Gradient definitions found through their index are those found by comparing each in turn: the +/// file is the same, byte for byte, with the same warnings. An earlier definition of the same +/// gradient serves a gradient swatch of another name; gradients that differ only in the sign of a +/// zero share a definition; a gradient that is not equal to itself is defined each time. +#[test] +fn indexed_gradient_definitions_write_the_same_file() { + let doc = many_gradients(300, 300, 7); + let (indexed, scanned) = (export_scanned(&doc, false), export_scanned(&doc, true)); + let differ = indexed.bytes.iter().zip(&scanned.bytes).position(|(a, b)| a != b); + assert!(indexed.bytes == scanned.bytes, "the files differ from byte {differ:?} ({} and {} bytes)", indexed.bytes.len(), scanned.bytes.len()); + assert_eq!(indexed.warnings, scanned.warnings); + assert_eq!(indexed.setting_notes, scanned.setting_notes); + let text = String::from_utf8(indexed.bytes).unwrap(); + let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect(); + // `Sky`, 300 of their own, 7 reused, 1 for both signs of zero and 2 for the gradient that + // is not a number. + assert_eq!(defined.len(), 1 + 300 + 7 + 1 + 2, "{defined:?}"); + assert_eq!(defined.first(), Some(&"(Sky)")); + assert!(!defined.contains(&"(Dawn)"), "{defined:?}"); +} + +/// A gradient is matched with the definitions of the same gradient, not with each definition: +/// 1,000 gradients of their own and 1,000 of 10 others take a comparison or so each, where +/// comparing each definition in turn takes hundreds of thousands. +#[test] +fn legacy_gradient_definitions_are_found_without_comparing_each() { + let doc = many_gradients(1000, 1000, 10); + let comparisons = |scanned: bool| { + super::writer::GRADIENT_COMPARISONS.with(|c| c.set(0)); + export_scanned(&doc, scanned); + super::writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get) + }; + let (indexed, scanned) = (comparisons(false), comparisons(true)); + assert!(indexed <= 2 * 2006, "{indexed} comparisons through the index"); + assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index"); +} + +/// The time to write 5,000 rectangles with gradients of their own and 5,000 with 50 others, with +/// the definitions found by comparing each in turn and through their index: the median of 7 runs +/// of each, alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture legacy_gradient_definitions_timing`. +#[test] +#[ignore = "timing"] +fn legacy_gradient_definitions_timing() { + let doc = many_gradients(5000, 5000, 50); + let mut times = [vec![], vec![]]; + let mut files: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [true, false].into_iter().enumerate() { + let (start, h) = thread_time(); + let out = export_scanned(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + files[k].get_or_insert(out.bytes); + } + } + assert_eq!(files[0], files[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("10,006 gradient fills, median of 7 runs ({how}):"); + println!("| definitions found | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["comparing each in turn", "through the index"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// The time this thread has run, and how it was measured. fn thread_time() -> (std::time::Duration, &'static str) { if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::().ok()) { diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 7e7dbfe4fc..2fa0fcb6c2 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -10,6 +10,7 @@ use super::{ TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; use super::{CONIC, CONIC_WEDGES, DEEP_DISTORTED, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; +use crate::gradient_key::gradient_key; #[cfg(test)] thread_local! { @@ -18,6 +19,18 @@ thread_local! { /// Whether [`Numbered::take`] numbers names on this thread by searching the names given so /// far, one number at a time, for each number it tries. pub(super) static SCANNED_NAMES: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether [`Writer::defined`] finds a gradient's definition on this thread by comparing the + /// gradient with each definition in turn. + pub(super) static SCANNED_DEFINITIONS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`Writer::defined`] has compared two gradients on this thread. + pub(super) static GRADIENT_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Are gradients `a` and `b` the same? +fn same_gradient(a: &Gradient, b: &Gradient) -> bool { + #[cfg(test)] + GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1)); + a == b } /// An image's coverage ([`ImageBlob::coverage`]): its width, its height and one byte a pixel. @@ -34,7 +47,7 @@ pub(super) struct Writer<'a> { /// Spot colors used: the name written and full CMYK equivalent. pub(super) spots: Vec<(String, [f32; 4])>, /// The name each spot color (by its swatch's name) is written with ([`Self::spot`]). - spot_names: Vec<(String, String)>, + spot_names: std::collections::HashMap, pub(super) warnings: Vec, /// Notes on what the options asked for ([`crate::LegacyAiOutput::setting_notes`]). pub(super) setting_notes: Vec, @@ -73,6 +86,13 @@ pub(super) struct Writer<'a> { gradient_names: Numbered, /// The names spot colors are written with ([`Self::spot`]). spot_written: Numbered, + /// The names of [`Self::spots`]. + spot_set: std::collections::HashSet, + /// The PostScript names of [`Self::fonts`]. + font_set: std::collections::HashSet, + /// The places in [`Self::gradients`] of the definitions, in order, by their gradient's key + /// ([`gradient_key`]). + gradient_index: std::collections::HashMap>, } impl<'a> Writer<'a> { @@ -84,7 +104,7 @@ impl<'a> Writer<'a> { body: String::new(), gradients: vec![], spots: vec![], - spot_names: vec![], + spot_names: std::collections::HashMap::new(), warnings: vec![], setting_notes: vec![], locked: false, @@ -103,6 +123,9 @@ impl<'a> Writer<'a> { in_graph: false, gradient_names: Numbered::default(), spot_written: Numbered::default(), + spot_set: std::collections::HashSet::new(), + font_set: std::collections::HashSet::new(), + gradient_index: std::collections::HashMap::new(), } } @@ -160,16 +183,17 @@ impl<'a> Writer<'a> { /// Windows-1252 are written as `?` (with a warning), and it is numbered when another spot color /// is already written with that name; the name is the same each time. fn spot(&mut self, name: &str, cmyk: [f32; 4]) -> String { - let written = match self.spot_names.iter().find(|(n, _)| n == name) { - Some((_, w)) => w.clone(), + let written = match self.spot_names.get(name) { + Some(w) => w.clone(), None => { let base = self.latin_name(name, TITLE_AND_COLOR_NAMES); let written = self.spot_written.take(base); - self.spot_names.push((name.to_string(), written.clone())); + self.spot_names.insert(name.to_string(), written.clone()); written } }; - if !self.spots.iter().any(|(n, _)| *n == written) { + if !self.spot_set.contains(&written) { + self.spot_set.insert(written.clone()); self.spots.push((written.clone(), cmyk)); } written @@ -178,7 +202,7 @@ impl<'a> Writer<'a> { /// The name spot color `name` (its swatch's name) is written with, once [`Self::spot`] has /// noted it. pub(super) fn spot_name<'n>(&'n self, name: &'n str) -> &'n str { - self.spot_names.iter().find(|(n, _)| n == name).map_or(name, |(_, w)| w.as_str()) + self.spot_names.get(name).map_or(name, String::as_str) } /// A top-level layer. False when it isn't a layer. @@ -831,15 +855,26 @@ impl<'a> Writer<'a> { /// The name of the definition of `g` (its swatch's name when it has one, with each character /// outside Windows-1252 written as `?` and a warning), defined the first time. fn define(&mut self, g: &Gradient, swatch: Option<&str>) -> String { - if let Some((name, _)) = self.gradients.iter().find(|(_, d)| d == g) { + let key = gradient_key(g); + if let Some((name, _)) = self.defined(g, key).and_then(|i| self.gradients.get(i)) { return name.clone(); } let base = self.latin_name(swatch.filter(|s| !s.is_empty()).unwrap_or("Gradient"), TITLE_AND_COLOR_NAMES); let name = self.gradient_names.take(base); + self.gradient_index.entry(key).or_default().push(self.gradients.len()); self.gradients.push((name.clone(), g.clone())); name } + /// The place in [`Self::gradients`] of the first definition of `g`, whose key is `key`. + fn defined(&self, g: &Gradient, key: u64) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.gradients.iter().position(|(_, d)| same_gradient(d, g)); + } + self.gradient_index.get(&key)?.iter().copied().find(|i| self.gradients.get(*i).is_some_and(|(_, d)| same_gradient(d, g))) + } + // ---------- type ---------- /// Type: a text object when the format can hold it as text, else its outlines (type with @@ -1016,7 +1051,8 @@ impl<'a> Writer<'a> { self.line_style(&st.stroke_layer()); } let (name, truetype, ascent, descent) = font_of(st); - if !self.fonts.iter().any(|(n, _)| *n == name) { + if !self.font_set.contains(&name) { + self.font_set.insert(name.clone()); self.fonts.push((name.clone(), truetype)); } let size = finite(st.size, 12.0); diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 39737dae3a..44d974bd35 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -32,12 +32,14 @@ //! ([`export_ai_editing`], [`ai_private_data`]). //! - `ai_ops`: the path and line style operators those two write. //! - `ai_graph`: the records of a live graph those two write around its group. +//! - `gradient_key`: the key those two find gradient definitions by. //! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing. mod ai_editing; mod ai_graph; mod ai_ops; pub mod dcs; +mod gradient_key; mod import; mod latin; mod legacy_ai; From 5c9b0004fea11d1ca074fbecc06b8d46968865ac Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:02:35 -0800 Subject: [PATCH 038/126] Command Palette: docs order typo matches by the field the word is met in Among results matched through a typo, the ranking key compares the typo grade (a word met in the label grades better than one met in the menu path) before the other words' grades and the label's length, so two results can come in a different order than the word spelled right gives them. The paragraph now states that order. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..8e7a28bc6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1588,7 +1588,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds the word before one whose menu path holds it, then by the grades of the other words, and after that as every other result is ordered, so two such results can come in a different order than the word spelled right gives them. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). From 125ab663489380d0e739e69fe788ba0840f8e8cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:03:29 -0800 Subject: [PATCH 039/126] Selection: on-canvas widgets check an object's kind before its editability 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 now check that a selected object is of a kind that has the widget before asking whether it is editable. With an artboard locked, the editability check measures the art of the layer object holding the object, so a large selected group of another kind was measured on every repaint and pointer move. The widgets shown are the same. A test-only counter (vectorcraft-doc feature locked-artboard-count) counts those measurements; widget_order_tests checks that objects of other kinds are not measured, compares every widget with the editability-first result on a mixed document, and holds an ignored timing test, widget_order_perf. --- crates/doc/Cargo.toml | 2 + crates/doc/src/artboard.rs | 17 ++ crates/doc/src/lib.rs | 3 + crates/tools/Cargo.toml | 4 +- crates/tools/src/corners.rs | 17 +- crates/tools/src/lib.rs | 3 + crates/tools/src/mirror.rs | 5 +- crates/tools/src/objects_on_path.rs | 8 +- crates/tools/src/pie.rs | 10 +- crates/tools/src/repeat_grid.rs | 5 +- crates/tools/src/repeat_radial.rs | 5 +- crates/tools/src/select.rs | 9 +- crates/tools/src/sidewidget.rs | 6 +- crates/tools/src/trace_split.rs | 6 +- crates/tools/src/typewidget.rs | 6 +- crates/tools/src/widget_order_tests.rs | 354 +++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 17 files changed, 436 insertions(+), 25 deletions(-) create mode 100644 crates/tools/src/widget_order_tests.rs 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/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/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/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/lib.rs b/crates/tools/src/lib.rs index 688f295478..a705f9a3c2 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -714,6 +714,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 31253003d9..fe1bab3348 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 dbb6f8bfdf..44e28a58e8 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 ae9d934954..75c37b7cd2 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 eecc6ba0fe..338e88c9d7 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 7304570404..61f63f269e 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 fc18a978e6..ff41a72a75 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -597,8 +597,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..afe52c6f73 --- /dev/null +++ b/crates/tools/src/widget_order_tests.rs @@ -0,0 +1,354 @@ +//! 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 the +/// widgets made before their kind check (the same calls, on the same ids), and without it. 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) { + 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(); + std::hint::black_box(sel.objects.iter().filter(|id| editable(**id)).count()); + std::hint::black_box(f(std::hint::black_box(doc), sel, 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/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..6b59bf77d8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2495,6 +2495,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. From a82de18956d5261134899800fcda6cf1cc33cf30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:14:53 -0800 Subject: [PATCH 040/126] Symbols: in Draw Behind a placed instance goes directly below the selection symbol.place, symbol.placeFromDocument and symbol.addFromLibrary with `place` now read the drawing mode: in Draw Behind the new instance goes directly below the selected object, or at the bottom of the current layer when nothing is selected, as the help page describes for placing symbols (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html). Place Symbol Instance in the Symbols panel and a symbol dragged onto the canvas from the Symbols panel or a symbol library all go through these commands. VectorCraft's own rules: with several objects selected the instance goes below the bottommost one, a selected path in a compound path puts it beside the compound path, and a clipping path stays at the bottom of its clip group or clipping layer. Draw Normal and Draw Inside keep the instance on top of the current layer, and a locked or hidden layer still refuses it with no edit. --- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/symbols.rs | 38 ++++++++++++- crates/engine/src/cmd/symbollib.rs | 16 +++--- crates/engine/src/tests/brushsym.rs | 67 +++++++++++++++++++++++ crates/engine/src/tests/symbollib.rs | 42 ++++++++++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 7 files changed, 162 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..580f2d7a30 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -48,7 +48,7 @@ use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instanc use symbolism::symbol_set_density; use symbols::selected_instances; pub(crate) use symbols::{ - expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, + Placement, expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, stored_natural_size, }; use symbols::{ @@ -234,7 +234,7 @@ pub fn specs() -> Vec { "Place Symbol Instance", [], None, - "{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current) → {id}", + "{name?, x?, y?} place an instance so its registration point is at (x, y) (default: artboard centre; name default: current), on top of the current layer, or in Draw Behind directly below the bottommost selected object (at the bottom of the current layer with nothing selected) → {id}", has_doc, symbol_place ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 14e52ffe4f..ac85e71de4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -33,6 +33,40 @@ pub(crate) fn place_xf(at: Point, (w, h): (f64, f64), reg: SymbolRegistration) - Affine::translate(c.to_vec2()) * Affine::scale_non_uniform(w / (2.0 * HALF), h / (2.0 * HALF)) } +/// Where a placed symbol instance goes in the active document, worked out before the edit from +/// the drawing mode, the selection and the layer new art goes into. +pub(crate) struct Placement { + parent: Option, + behind: bool, + anchor: Option, +} + +impl Placement { + /// On top of the layer new art goes into; in Draw Behind, directly below the bottommost + /// selected object (beside the compound path that holds it), or at the bottom of that layer + /// when nothing is selected. An error when that layer is locked or hidden. + pub(crate) fn of(s: &Session) -> Result { + let st = s.doc()?; + let parent = st.target_parent()?; + let behind = s.draw_mode == crate::DrawMode::Behind; + let compound_of = |id: NodeId| st.doc.parent_of(id).filter(|p| st.doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))); + let anchor = behind.then(|| st.selection.in_paint_order(&st.doc).first().copied()).flatten().map(|id| compound_of(id).unwrap_or(id)); + Ok(Self { parent, behind, anchor }) + } + + /// Inserts instance `n` where this placement puts it. In a clip group or a clipping layer the + /// clipping path stays at the bottom. + pub(crate) fn insert(&self, d: &mut Document, n: Node) -> Result { + let (parent, index) = match (self.behind, self.anchor.and_then(|a| d.position(a))) { + (false, _) => return Ok(d.insert(self.parent, usize::MAX, n)?), + (true, Some((par, i, _))) => (par, i), + (true, None) => (self.parent, 0), + }; + let floor = usize::from(parent.and_then(|p| d.node(p)).is_some_and(Node::clips)); + Ok(d.insert(parent, index.max(floor), n)?) + } +} + fn registration_param(p: &Value, cmd: &str) -> Result> { match p.get("registration") { None => Ok(None), @@ -437,10 +471,10 @@ pub(super) fn symbol_place(s: &mut Session, p: &Value) -> Result { let at = Point::new(number_or(p, "x", centre.x, "symbol.place")?, number_or(p, "y", centre.y, "symbol.place")?); let size = natural_size(d, &name); let reg = d.symbol_registration(&name); - let parent = s.doc()?.target_parent()?; + let spot = Placement::of(s)?; let id = s.edit("Place Symbol Instance", |d, sel| { let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?; + spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(at, size, reg) }))?; sel.set([id]); Ok(id) })?; diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 660e15248c..60db399f42 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -15,7 +15,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol, SymbolNineSlice}; use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Rect, SubPath, shapes}; -use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_natural_size}; +use super::brushsym::{CURRENT_SYMBOL, Placement, natural_size, normalize, place_xf, set_natural_size}; use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::swatch::str_list; @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Add to Symbols", ["Window", "Symbol Libraries"], None, - "{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}", + "{library: id or name, name? | names?: [symbol names in the library] (default: all of it), place?: false (also place an instance of the first one, its registration point at x, y: default the first artboard's centre, in the stacking order symbol.place gives it, Draw Behind included), x?, y?, swatchConflict? (as edit.paste)} copy library symbols into the document's Symbols as one undo step (with the place), with their Symbol Options and the resources they use (the symbols they nest, patterns, swatches, brushes, graphic styles, images). A symbol the document already has (same name and art) isn't added again; a name another symbol has gets a number (\"Star 2\"). The first one becomes the current symbol → {library, names: [each symbol's name in the document], added: [names added], existing: [names already there], placed?: id}", has_doc, add ), @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Place Symbol Instance", [], None, - "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", + "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), in the stacking order symbol.place gives it (Draw Behind included), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", has_doc, place_from_document ), @@ -816,7 +816,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let doc_names: Vec = picked.iter().map(|n| target(&imported.renamed, n)).collect(); let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None }; - let parent = if place { st.target_parent()? } else { None }; + let spot = if place { Some(Placement::of(s)?) } else { None }; let mut out = json!({ "library": shown_library_id(s, &info.id) }); if imported.added > 0 || place { let placed = s.edit("Add to Symbols", |d, sel| { @@ -830,10 +830,10 @@ fn add(s: &mut Session, p: &Value) -> Result { } let Some(first) = doc_names.first() else { return Ok(None) }; d.unknown.insert(CURRENT_SYMBOL.into(), json!(first)); - let Some(at) = at else { return Ok(None) }; + let (Some(at), Some(spot)) = (at, &spot) else { return Ok(None) }; let xf = place_xf(at, natural_size(d, first), d.symbol_registration(first)); let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?; + spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: first.clone(), xf }))?; sel.set([id]); Ok(Some(id)) })?; @@ -860,7 +860,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result { let st = s.doc()?; let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?); - let parent = st.target_parent()?; + let spot = Placement::of(s)?; let same = uid == st.uid; let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc)); let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?; @@ -883,7 +883,7 @@ fn place_from_document(s: &mut Session, p: &Value) -> Result { }; let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed)); let id = d.alloc_id(); - d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; + spot.insert(d, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; sel.set([id]); Ok((id, placed)) })?; diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 1d53214ec9..62b1bac629 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -2228,6 +2228,73 @@ fn place_and_break_link_round_trip_geometry() { assert_eq!(n.appearance.stroke_width(), 1.0, "strokes are not scaled by normalisation"); } +/// In Draw Behind, Place Symbol Instance puts the instance directly below the bottommost selected +/// object (beside the compound path that holds a selected path, above a clipping path), or at the +/// bottom of the current layer with nothing selected, selected and in one undo step. Draw Normal +/// and Draw Inside keep it on top, and a locked layer refuses it with no edit. +#[test] +fn placed_instances_go_below_the_selection_in_draw_behind() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0, 10.0), rect(&mut s, 20.0, 0.0, 10.0, 10.0)); + let layer = s.doc().unwrap().doc.layers[0].id; + let kids = |s: &Session, id: NodeId| node(s, id).children().unwrap().iter().map(|c| c.id).collect::>(); + let place = |s: &mut Session| NodeId(s.execute("symbol.place", &json!({"name": name, "x": 300, "y": 200})).unwrap()["id"].as_u64().unwrap()); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + select(&mut s, &[b]); + let before = undo_len(&s); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, a, p, b], "directly below the selected object"); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(s.doc().unwrap().selection.objects, [p]); + assert!(close(bounds(&s, p), Rect::new(260.0, 180.0, 340.0, 220.0), 1e-9), "{:?}", bounds(&s, p)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kids(&s, layer), vec![inst, a, b]); + // Below the bottommost of several selected objects. + select(&mut s, &[b, a]); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, p, a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + // With nothing selected, at the bottom of the current layer. + select(&mut s, &[]); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![p, inst, a, b]); + s.execute("edit.undo", &json!({})).unwrap(); + // A path selected in a compound path: beside the compound path, not inside it. + select(&mut s, &[a, b]); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = kids(&s, layer)[1]; + let member = kids(&s, compound)[1]; + select(&mut s, &[member]); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, p, compound]); + assert_eq!(kids(&s, compound).len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + // Draw Normal and Draw Inside put it on top of the layer. + for mode in ["normal", "inside"] { + select(&mut s, &[compound]); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![inst, compound, p], "{mode}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // In a clipping layer the clipping path stays at the bottom, the selected clipping path too. + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert_eq!(kids(&s, layer), vec![compound, inst]); + for picked in [&[][..], &[compound]] { + select(&mut s, picked); + let p = place(&mut s); + assert_eq!(kids(&s, layer), vec![compound, p, inst], "{picked:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // A locked layer takes nothing. + s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap(); + let before = (undo_len(&s), s.doc().unwrap().doc.clone()); + assert!(s.execute("symbol.place", &json!({"name": name})).is_err()); + assert_eq!((undo_len(&s), &s.doc().unwrap().doc), (before.0, &before.1)); +} + #[test] fn hidden_instance_fill_does_not_tint_expanded_symbol_art() { for command in ["symbol.breakLink", "object.expand"] { diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index de7f938f78..19d2333b6e 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -514,3 +514,45 @@ fn another_documents_symbol_is_added_and_placed_in_one_step() { let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err(); assert!(e.to_string().contains("no longer open"), "{e}"); } + +/// A symbol dragged onto the canvas, from another document's Symbols panel or from a symbol +/// library, is stacked as Place Symbol Instance stacks it: in Draw Behind directly below the +/// selected object, or at the bottom of the current layer with nothing selected, in one undo step +/// with the symbol it adds. A locked layer refuses it with no edit. +#[test] +fn dropped_symbols_go_below_the_selection_in_draw_behind() { + let mut s = kit(); + let source = s.doc().unwrap().uid; + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let rect = + |s: &mut Session, x: f64| NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].as_u64().unwrap()); + let (a, b) = (rect(&mut s, 0.0), rect(&mut s, 20.0)); + let layer = doc(&s).layers[0].id; + let kids = |s: &Session| doc(s).node(layer).unwrap().children().unwrap().iter().map(|c| c.id).collect::>(); + run(&mut s, "view.drawMode", json!({"mode": "behind"})); + let drops = [ + ("symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40}), "id"), + ("symbol.addFromLibrary", json!({"library": "basic shapes", "name": "Square", "place": true, "x": 30, "y": 40}), "placed"), + ]; + for (cmd, p, key) in &drops { + for (picked, at) in [(vec![b], 1), (vec![], 0)] { + run(&mut s, "select.set", json!({"ids": picked.iter().map(|i| i.0).collect::>()})); + let before = undo_len(&s); + let placed = NodeId(run(&mut s, cmd, p.clone())[*key].as_u64().unwrap()); + let mut want = vec![a, b]; + want.insert(at, placed); + assert_eq!(kids(&s), want, "{cmd} {picked:?}"); + assert_eq!(undo_len(&s), before + 1, "{cmd}"); + assert_eq!(s.doc().unwrap().selection.objects, [placed]); + run(&mut s, "edit.undo", json!({})); + assert!(symbols(&s).is_empty(), "{cmd}: the undo takes the added symbol too"); + } + } + // A locked layer takes nothing. + run(&mut s, "layer.setProps", json!({"id": layer.0, "locked": true})); + let before = (undo_len(&s), doc(&s).clone()); + for (cmd, p, _) in &drops { + assert!(s.execute(cmd, p).is_err(), "{cmd}"); + assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{cmd}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..4bc570f99b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3885,7 +3885,10 @@ already walks Image Trace. Short agent entry points: art, where it is, snaps the art again after it is edited, and does not count instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has adds no undo step), - `symbol.place {name?, x?, y?}`, `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol + `symbol.place {name?, x?, y?}` (on top of the current layer; in Draw Behind directly below the bottommost selected + object, beside the compound path that holds it, or at the bottom of the current layer with nothing selected, above + a clipping path; `symbol.placeFromDocument` and `symbol.addFromLibrary` with `place` stack the instance the same + way), `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol of another open document, as a symbol dragged from that document's Symbols panel onto the canvas places it: the symbol, the symbols it nests and the resources they use are added as `edit.dropSelection` adds them, in the same undo step, and a symbol with the same name but other art or Symbol Options is added under a free name; an error @@ -9132,7 +9135,8 @@ undo step. When a matched layer, or a layer around it, is hidden or locked, the Drawing modes (`view.drawMode`) apply too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind, -`edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection. `edit.pasteInFront` and +`edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection, and a placed symbol instance +(`symbol.place`) goes just below the selection too. `edit.pasteInFront` and `edit.pasteInBack` ignore the drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`, or a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so the new art can be picked and isn't dimmed; `edit.undo` or `edit.redo` that removes the isolated object ends diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..9fa3b6635b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1421,7 +1421,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). From 5ca427ff2d09df4573c510798d0e165074aaf1ba Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:15:06 -0800 Subject: [PATCH 041/126] Dimension: a guide member of a compound path does not hold a preview-bounds corner With Use Preview Bounds on, the member of a stroked compound path whose own box reaches nearest a corner holds the Linear point placed there. A visible, unlocked member made into a guide could hold it, so the dimension was linked to the guide, although paths made into guides give no corners. A guide member now gives no corner, as a hidden or locked member does. --- crates/tools/src/dimension.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 5e2e179bdf..b9ac881910 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -313,12 +313,12 @@ fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Optio } // 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 gives no corner. + // 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; + 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)); } @@ -1781,6 +1781,23 @@ mod tests { let (q, _) = t.snap_linear(&c, Point::new(81.0, 81.0)); assert!(!near(q, Point::new(80.0, 80.0)) && t.corner.is_none(), "{kind}: {q:?}"); } + // A visible, unlocked member of a stroked compound path made into a guide does not hold + // the corner its box puts there. + 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 mut guide = Node::path(part, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Default::default()); + if let NodeKind::Path { guide, .. } = &mut guide.kind { + *guide = true; + } + let small = Node::path(hole, vectorcraft_geom::shapes::rectangle(Rect::new(140.0, 140.0, 160.0, 160.0)), Default::default()); + let mut n = + Node::new(whole, NodeKind::Compound { children: vec![std::sync::Arc::new(small), std::sync::Arc::new(guide)], rule: Default::default() }); + n.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 0, n).expect("the compound path"); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + let (q, _) = t.snap_linear(&c, Point::new(99.6, 99.6)); + assert!(t.corner.is_none() && !near(q, Point::new(99.5, 99.5)), "{q:?} {:?}", t.corner); // Two stroked rectangles sharing the edge x = 200; the right one is on top. let (mut d, left) = doc_with_rect(); let (l, right) = (d.layers[0].id, d.alloc_id()); From ef9d6022400e36b44a03f2faec93f318ce54b41d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:16:47 -0800 Subject: [PATCH 042/126] Docs: name the clipping path tolerance and the distorted image case on Update Links A clipping path counts as changed in the document when an anchor or handle moves by a thousandth of a point or more, and links.update leaves a distorted image's clipping as it is. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0efd8dffc7..2374e8c0aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2321,7 +2321,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (its anchors, whether it is closed, or its fill rule) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From 4051d6c9cae7cbda120047cdadf9f2375a142fc8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:17:45 -0800 Subject: [PATCH 043/126] Command Palette: docs state the order for two typo words With more than one query word matched through a typo, a result whose label holds every such word comes first, and then the other words' grades and how many such words the menu path holds decide. Two results that hold the two words in label and menu path the other way round tie on these grades. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8e7a28bc6c..d3038ee060 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1588,7 +1588,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds the word before one whose menu path holds it, then by the grades of the other words, and after that as every other result is ordered, so two such results can come in a different order than the word spelled right gives them. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them, how the whole query matches is judged with the misspelled word replaced by the word it meets. Results that match it equally then come in this order: a result whose label holds every word matched through a typo before one whose menu path holds such a word, then by the grades of the other words and how many such words the menu path holds, and after that as every other result is ordered, so two such results can come in a different order than the words spelled right give them. With two words matched through typos, a result whose label holds one and whose menu path holds the other ties on these grades with a result that holds them the other way round. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). From 662acb72ff2f27e683a70bbb645f1da766e8e03a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:23:41 -0800 Subject: [PATCH 044/126] Dimension: pointer moves read a compound path's members once per revision With Use Preview Bounds on, every pointer move near a corner of a compound path's preview bounds scanned all of its members to find the one holding that corner. A compound with tens of thousands of members cost one visit from the walk budget and then a full member scan on each move. - The holder of each of the four corners is found in one pass over the members when the compound is measured, and cached with the bounds for the document's revision. Later moves read it from the cache. - Measuring an object not yet measured (its geometric bounds, its preview bounds and its holders) counts its members against a separate limit of 20,000 per move. An object with more members than are left gives no corner on that move, and nothing is cached for it. --- crates/tools/src/dimension.rs | 150 ++++++++++++++++++++++++++++------ 1 file changed, 125 insertions(+), 25 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 5e2e179bdf..525c2ff547 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -238,10 +238,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 { @@ -257,7 +265,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>, @@ -266,8 +276,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 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; + 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; @@ -277,7 +317,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()), @@ -285,25 +324,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() { @@ -311,26 +370,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 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; - 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 })); } } @@ -353,7 +399,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); } @@ -1615,6 +1661,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] From 55611881a4dc26a72f4b77e2ac30408fb0f7de19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:23:48 -0800 Subject: [PATCH 045/126] Docs: a blurred 3D shadow expands to an image The 3D shadows section of docs/mcp.md said Expand Appearance keeps the shadow as a path. Since #7761 a shadow blurred by the first light's Softness expands to an image; only a hard shadow stays a path, as docs/three-d.md already says. --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..6486c31308 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5147,7 +5147,7 @@ art", and a loaded file draws the source path, as it does for a solid past its l documentation names the controls and their ranges ([3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html)). The settings are saved in the native file; SVG and PDF exports draw the shadow, and `effect.expandAppearance` keeps -it as a path. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows). +a hard shadow as a path and turns a blurred one into an image. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow. See [three-d.md](three-d.md#shadows). ```json {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"params":{"shadow":true,"shadowPosition":"below","shadowDistance":10,"shadowBounds":150}}}} From 14e22a1dff2d155b86dd463752b68686ed6771a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:28:27 -0800 Subject: [PATCH 046/126] Mesh: a Lasso click that deselects also unpicks the mesh points A plain Lasso click away from the art deselects everything but kept the mesh points the tool held, so the Mesh tool chosen next showed the deselected points as picked, nudged them with the arrow keys and recolored them with a fill color. The click now unpicks them. Shift and Alt clicks still change nothing. docs/target-app-parity.md also lists the Eyedropper among the tools that keep the picks, and docs/mcp.md describes the Lasso click. Test: a_lasso_click_that_deselects_unpicks_the_mesh_points in crates/engine/src/tests/mesh_picks.rs. --- crates/engine/src/tests/mesh_picks.rs | 20 ++++++++++++++++++++ crates/tools/src/xform/wand.rs | 7 ++++++- docs/mcp.md | 3 ++- docs/target-app-parity.md | 2 +- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/mesh_picks.rs b/crates/engine/src/tests/mesh_picks.rs index 0159709fdb..93556481da 100644 --- a/crates/engine/src/tests/mesh_picks.rs +++ b/crates/engine/src/tests/mesh_picks.rs @@ -88,6 +88,26 @@ fn a_tool_that_picks_no_mesh_points_drops_the_picks() { assert_eq!(colors(&s, m), before, "no point is picked"); } +/// A plain Lasso click away from the art deselects it and unpicks the points the Mesh tool picked, +/// so the Mesh tool chosen next has none picked. +#[test] +fn a_lasso_click_that_deselects_unpicks_the_mesh_points() { + let (mut s, m) = mesh_session(); + let v = ViewInfo::default(); + let before = colors(&s, m); + s.select_tool("mesh", v).unwrap(); + press(&mut s, m, 0, Mods::default()); + s.select_tool("lasso", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 500.0, 500.0), v).unwrap(); + } + assert!(s.doc().unwrap().selection.objects.is_empty(), "the click deselects the mesh"); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(colors(&s, m), before, "no point is picked"); +} + /// Direct Selection lent to the Mesh tool for a Cmd-click starts from the Mesh tool's picks, so a /// Shift-click adds to them, and gives back what it left picked. #[test] diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index 991f43881c..d6e3192266 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -145,7 +145,12 @@ impl Tool for LassoTool { let poly = std::mem::take(&mut self.points); let (add, sub) = (ev.mods.shift, ev.mods.alt); if poly.len() < 3 { - return if add || sub { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; + if add || sub { + return vec![]; + } + // The click deselects everything, so no mesh point stays picked. + self.mesh.unfocus(); + return vec![Action::Exec("select.none".into(), json!({}))]; } vec![lasso_select(cx, &mut self.mesh, &poly, add, sub)] } diff --git a/docs/mcp.md b/docs/mcp.md index a2dfff4bfa..f6ffab55d8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14193,7 +14193,8 @@ moves them all as one undo step (`object.mesh.movePoints`), a click on one of se and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options (`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching between the Mesh tool, Direct Selection, the Lasso, the Polygonal Lasso and the Eyedropper keeps them picked, and so does a Cmd/Ctrl-click with the selection -tool one of them lends; any other tool, Group Selection included, drops them. The Eyedropper's options list them too. +tool one of them lends; any other tool, Group Selection included, drops them. A plain Lasso click away from the art +(`select.none`) unpicks them. The Eyedropper's options list them too. While a selected, editable mesh has points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 25b0e47a10..baeac9f26a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1905,7 +1905,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. - **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. -- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterwards recolors just those points. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged. +- **Picked mesh points survive a tool switch:** mesh points picked with the Mesh tool, Direct Selection, the Lasso or the Polygonal Lasso stay picked when another of these tools or the Eyedropper is chosen, and when one of them lends Direct Selection for a Cmd/Ctrl-click, so a fill color chosen afterward recolors just those points. A plain Lasso click away from the art deselects it and unpicks them. Any other tool, Group Selection included, drops them. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point picked with the Mesh tool is recolored by choosing a fill color in the Swatches or Color panel), [Archived help guide, page 202](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=202) (the Mesh tool and Direct Selection both move mesh points). Carrying the picks between the tools is VectorCraft's own rule. Tests: `crates/engine/src/tests/mesh_picks.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. From e60afb9ea365c7b6844a5cc53a3d6d16976d486e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:28:58 -0800 Subject: [PATCH 047/126] Path Precision Tools: the Tangent Circle Tool leaves out a circle that would reach past the canvas A circle tangent to two segments near the canvas edge could show in the preview and then fail on release, because `shape.circleThroughPoints` refuses a circle that reaches more than 4,000,000 pt from the origin. The tool's check of the three points now goes through `circle::circle_of`, which applies the same bounds, so such a circle counts as no circle: the note shows, a click draws nothing and the first segment stays picked. --- crates/tools/src/addons/tangent_circle.rs | 43 +++++++++++++++++++++-- docs/mcp.md | 4 +-- docs/target-app-parity.md | 2 +- 3 files changed, 43 insertions(+), 6 deletions(-) diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index a8d24d8853..1870d20b3b 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -155,7 +155,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] @@ -165,7 +166,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; } @@ -425,7 +426,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) @@ -717,4 +718,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/docs/mcp.md b/docs/mcp.md index e7abf476a9..3b62792440 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14493,8 +14493,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, or another document forgets the first segment. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..a244132592 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2990,7 +2990,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. 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 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. 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 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) From 4ed194779e42c3b0013bd5dca007b83a8a53c2a9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:37:59 -0800 Subject: [PATCH 048/126] Type: tests check where the Single-line Composer sets lines around text wrap composer_x_mixed_sizes_around_text_wrap and composer_x_mixed_sizes_overflow_around_text_wrap compared only the Single-line Composer's line texts with the Every-line Composer's. Both tests now run their room, overflow and wrap-object checks on each composer, so a Single-line layout that breaks the same lines but sets a span past its room or into the object fails. --- crates/text/src/tests/combos.rs | 73 +++++++++++++++++---------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/crates/text/src/tests/combos.rs b/crates/text/src/tests/combos.rs index a2d837e286..aca8d6bbde 100644 --- a/crates/text/src/tests/combos.rs +++ b/crates/text/src/tests/combos.rs @@ -421,26 +421,27 @@ fn composer_x_mixed_sizes_around_text_wrap() { let l = layout(db(), &t); (line_texts(&t, &l), l, t) }; - let (every, l, t) = set(Composer::EveryLine); - assert_eq!( - every, - ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."] - ); - assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{:?}", l.lines); - // Two spans share each baseline beside the object. - assert_eq!(l.lines[1].baseline, l.lines[2].baseline); - assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{:?}", l.lines); - let text = t.plain_text(); - let hits = l.glyphs.iter().filter(|g| { - let li = &l.lines[g.line]; - let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; - across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 - }); - assert_eq!(hits.count(), 0, "{:?}", l.lines); // The single-line composer measures each line across its height too, and breaks this - // paragraph the same way. - let (greedy, _, _) = set(Composer::SingleLine); - assert_eq!(every, greedy); + // paragraph the same way, with its lines set clear of the object as well. + for composer in [Composer::EveryLine, Composer::SingleLine] { + let (texts, l, t) = set(composer); + assert_eq!( + texts, + ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature", "destroyed this", "way."], + "{composer:?}" + ); + assert!(past_their_room(&t, &l).is_empty() && !l.overflow, "{composer:?}: {:?}", l.lines); + // Two spans share each baseline beside the object. + assert_eq!(l.lines[1].baseline, l.lines[2].baseline, "{composer:?}"); + assert!(l.lines[1].ascent > 30.0 && l.lines[2].avail.0 > object.x1, "{composer:?}: {:?}", l.lines); + let text = t.plain_text(); + let hits = l.glyphs.iter().filter(|g| { + let li = &l.lines[g.line]; + let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; + across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 + }); + assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines); + } } #[test] @@ -581,23 +582,23 @@ fn composer_x_mixed_sizes_overflow_around_text_wrap() { let l = layout(db(), &t); (line_texts(&t, &l), l, t) }; - let (every, l, t) = set(Composer::EveryLine); - assert!(l.overflow && l.lines.len() >= 3, "{:?}", l.lines); - assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{:?}", l.lines); - assert!(past_their_room(&t, &l).is_empty(), "{:?}", l.lines); - let text = t.plain_text(); - let hits = l.glyphs.iter().filter(|g| { - let li = &l.lines[g.line]; - let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; - across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 - }); - assert_eq!(hits.count(), 0, "{:?}", l.lines); - // The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame. - assert_eq!(every, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"]); - // The single-line composer measures each line across its height too, and breaks the lines - // that fit the same way. - let (greedy, ..) = set(Composer::SingleLine); - assert_eq!(every, greedy); + // The single-line composer measures each line across its height too, and breaks and sets the + // lines that fit the same way. + for composer in [Composer::EveryLine, Composer::SingleLine] { + let (texts, l, t) = set(composer); + assert!(l.overflow && l.lines.len() >= 3, "{composer:?}: {:?}", l.lines); + assert!(l.lines.windows(2).all(|p| p[0].end == p[1].start && p[0].start < p[0].end), "{composer:?}: {:?}", l.lines); + assert!(past_their_room(&t, &l).is_empty(), "{composer:?}: {:?}", l.lines); + let text = t.plain_text(); + let hits = l.glyphs.iter().filter(|g| { + let li = &l.lines[g.line]; + let across = li.baseline - li.ascent < object.y1 && li.baseline + li.descent > object.y0; + across && !text[g.byte..].starts_with(char::is_whitespace) && g.origin.x < object.x1 && g.origin.x + g.advance > object.x0 + }); + assert_eq!(hits.count(), 0, "{composer:?}: {:?}", l.lines); + // The lines that fit break as in `composer_x_mixed_sizes_around_text_wrap`'s taller frame. + assert_eq!(texts, ["Destroy all creatures with", "toughness\u{a0}X", "or less. Then", "draw a card for", "each creature"], "{composer:?}"); + } } #[test] From adda7c1c6ec33e2bf24a8479349fbaedb4af2d1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:40:31 -0800 Subject: [PATCH 049/126] Tests: font changes on other threads wait while a Type layout count runs The Type overlay layout-count tests in vectorcraft-tools held a read lock that only tests which add fonts or change hyphenation exceptions take for writing. Other tests still load system fonts on demand (a fallback for a character no loaded font covers, a cataloged family on first use), which changes FontDb::global()'s generation, the key of every kept frame layout. type_overlays_keep_at_most_frame_layouts_max then laid out 2051 frames instead of 2 in 18 of 21 full `cargo test -p vectorcraft-tools --lib` runs on Linux. vectorcraft_text::test_fonts::steady_fonts (test and test-fonts builds only) now holds back font changes on other threads: adding faces, a rescan and setting or removing a composite font wait before they publish anything. A first scan does not wait, and steady_fonts catalogs the database before it returns. steady_layout_inputs() takes it for the global database. With it, 0 of 20 full runs failed. --- crates/text/src/fontdb/composite.rs | 4 + crates/text/src/fontdb/db.rs | 7 +- crates/text/src/test_fonts.rs | 130 ++++++++++++++++++++++++++++ crates/text/src/tests/sysfonts.rs | 115 ++++++++++++++++++++++++ crates/tools/src/lib.rs | 8 +- 5 files changed, 261 insertions(+), 3 deletions(-) diff --git a/crates/text/src/fontdb/composite.rs b/crates/text/src/fontdb/composite.rs index 7b17fb74de..bdcb84ae8c 100644 --- a/crates/text/src/fontdb/composite.rs +++ b/crates/text/src/fontdb/composite.rs @@ -91,6 +91,8 @@ impl FontDb { /// guard's thread uses the fonts it lends and not this one. pub fn set_composite_font(&self, font: &CompositeFont) -> bool { let key = font.name.to_lowercase(); + #[cfg(any(test, feature = "test-fonts"))] + let _change = crate::test_fonts::font_change(); { let mut map = self.composites.write().unwrap_or_else(|e| e.into_inner()); if map.get(&key).is_some_and(|f| **f == *font) { @@ -104,6 +106,8 @@ impl FontDb { /// Forget the composite font named `name` (any case). Whether there was one. pub fn remove_composite_font(&self, name: &str) -> bool { + #[cfg(any(test, feature = "test-fonts"))] + let _change = crate::test_fonts::font_change(); let removed = self.composites.write().unwrap_or_else(|e| e.into_inner()).remove(&name.to_lowercase()).is_some(); if removed { self.changed(); diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 3be2c871de..046db94dfd 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -305,6 +305,8 @@ impl FontDb { } } } + #[cfg(any(test, feature = "test-fonts"))] + let _change = (!made.is_empty()).then(crate::test_fonts::font_change); let mut faces = self.faces.write().unwrap_or_else(std::sync::PoisonError::into_inner); let before = faces.len(); for f in made { @@ -325,7 +327,7 @@ impl FontDb { /// Catalog the installed fonts unless that has been done: the first caller scans the font /// folders, any other waits for that scan to finish. A no-op on wasm. - pub(super) fn ensure_catalog(&self) { + pub(crate) fn ensure_catalog(&self) { #[cfg(not(target_arch = "wasm32"))] self.cataloged.get_or_init(|| { self.scan_font_dirs(); @@ -448,6 +450,9 @@ impl FontDb { } log::debug!("cataloged {n} system font faces"); let installed: std::collections::HashSet = catalog.values().flat_map(|c| c.faces.iter().map(|cf| cf.path.clone())).collect(); + // The first scan waits for nothing: a guard is made only for a database already cataloged. + #[cfg(any(test, feature = "test-fonts"))] + let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change); *self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at }); *self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog; *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases; diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 7a2a23f089..1ba4fe3f99 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -45,6 +45,136 @@ pub fn drop_kept_layouts() { crate::kept::drop_kept_layouts(); } +/// Who holds [`SteadyFonts`] and who changes fonts ([`font_change`]), guarded by [`steadiness`] and +/// signaled through [`STEADINESS_CHANGED`]. +struct Steadiness { + /// Threads that hold a [`SteadyFonts`]. + holders: usize, + /// Font changes waiting to start. + waiting: usize, + /// Of `waiting`, those made on a thread that holds a [`SteadyFonts`]. + holders_waiting: usize, + /// Whether a font change is under way. + changing: bool, +} + +static STEADINESS: std::sync::Mutex = std::sync::Mutex::new(Steadiness { holders: 0, waiting: 0, holders_waiting: 0, changing: false }); +static STEADINESS_CHANGED: std::sync::Condvar = std::sync::Condvar::new(); + +fn steadiness() -> std::sync::MutexGuard<'static, Steadiness> { + STEADINESS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Wait for [`STEADINESS_CHANGED`]. +fn await_steadiness(s: std::sync::MutexGuard<'static, Steadiness>) -> std::sync::MutexGuard<'static, Steadiness> { + STEADINESS_CHANGED.wait(s).unwrap_or_else(std::sync::PoisonError::into_inner) +} + +std::thread_local! { + /// How many [`SteadyFonts`] this thread holds. + static STEADY: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Whether this thread holds the [`FontChange`] under way. + static CHANGING: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While held, a cataloged font database's fonts and its +/// [`FontDb::generation`](crate::FontDb::generation) change only on this thread: a change on another +/// thread (a system font loaded for a character no loaded font covers, fonts added, a rescan, a +/// composite font set or removed) waits until it is dropped, before it publishes anything. A change +/// on this thread waits until no other thread holds one, unless every other thread that holds one is +/// itself waiting to change fonts. Tests hold it to count the layouts that a cache keyed on the +/// generation keeps. The guards one thread holds count as one, until the last of them is dropped, in +/// whatever order they are. +pub struct SteadyFonts { + /// Dropped on the thread that made it. + _thread: std::marker::PhantomData<*const ()>, +} + +impl Drop for SteadyFonts { + fn drop(&mut self) { + let last = STEADY.with(|n| { + n.set(n.get() - 1); + n.get() == 0 + }); + if last { + steadiness().holders -= 1; + STEADINESS_CHANGED.notify_all(); + } + } +} + +/// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for +/// any guard, so this thread can wait for one running on another thread while it holds a guard. A +/// thread's first guard waits for the font changes under way or waiting. +pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts { + db.ensure_catalog(); + if STEADY.with(std::cell::Cell::get) == 0 { + let mut s = steadiness(); + while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) { + s = await_steadiness(s); + } + s.holders += 1; + } + STEADY.with(|n| n.set(n.get() + 1)); + SteadyFonts { _thread: std::marker::PhantomData } +} + +/// Held while a font database's fonts change, from before the change is published until its +/// generation has changed ([`font_change`]). +pub(crate) struct FontChange { + /// Made while this thread already held one (a change made inside another, as a test hook run + /// when faces are published can). + nested: bool, +} + +impl Drop for FontChange { + fn drop(&mut self) { + if !self.nested { + CHANGING.with(|c| c.set(false)); + steadiness().changing = false; + STEADINESS_CHANGED.notify_all(); + } + } +} + +/// [`FontChange`]: waits until no other change is under way and no other thread holds a +/// [`SteadyFonts`] (on a thread that holds one: none that is not itself waiting to change fonts). +/// Inside a change this thread is making, it does not wait. +pub(crate) fn font_change() -> FontChange { + if CHANGING.with(std::cell::Cell::get) { + return FontChange { nested: true }; + } + let holder = STEADY.with(std::cell::Cell::get) > 0; + let mut s = steadiness(); + #[cfg(test)] + font_changers().push(std::thread::current().id()); + s.waiting += 1; + s.holders_waiting += usize::from(holder); + while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } { + s = await_steadiness(s); + } + s.waiting -= 1; + s.holders_waiting -= usize::from(holder); + s.changing = true; + CHANGING.with(|c| c.set(true)); + FontChange { nested: false } +} + +/// Whether a font change on another thread would wait now (a [`SteadyFonts`] is held, or another +/// change is under way). +#[cfg(test)] +pub(crate) fn font_changes_held_back() -> bool { + let s = steadiness(); + s.holders > 0 || s.changing +} + +/// The threads that have asked to change a font database's generation ([`font_change`]). +#[cfg(test)] +pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec> { + static CHANGERS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + CHANGERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The family of [`variable_font`]. pub const VARIABLE_FAMILY: &str = "Varitest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index ada5c45dd1..06c4db899c 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -50,6 +50,121 @@ fn concurrent_fallback_lookups_all_find_the_installed_face() { std::fs::remove_dir(dir).unwrap(); } +/// Two [`test_fonts::steady_fonts`] guards on one thread hold font changes back until the last of +/// them is dropped, whichever was made first. +#[test] +fn steady_fonts_hold_back_font_changes_until_the_last_guard_is_dropped() { + let db = FontDb::with_font_dirs(vec![]); + let outer = crate::test_fonts::steady_fonts(&db); + let inner = crate::test_fonts::steady_fonts(&db); + drop(outer); + assert!(crate::test_fonts::font_changes_held_back(), "the inner guard is still held"); + drop(inner); + let first = crate::test_fonts::steady_fonts(&db); + let second = crate::test_fonts::steady_fonts(&db); + drop(second); + assert!(crate::test_fonts::font_changes_held_back(), "the first guard is still held"); + drop(first); +} + +/// While a thread holds [`test_fonts::steady_fonts`], a font added on another thread, which may +/// hold one too, changes the database's generation only once the guard is dropped. A thread that +/// holds the only guard adds a font itself while another thread's change waits, which then still +/// waits for the guard. +#[test] +fn steady_fonts_hold_back_other_threads_font_changes() { + for guarded in [false, true] { + let db = FontDb::with_font_dirs(vec![]); + let font = crate::test_fonts::variable_font().unwrap(); + let steady = crate::test_fonts::steady_fonts(&db); + let before = db.generation(); + std::thread::scope(|scope| { + let adding = scope.spawn(|| { + let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db)); + db.add_font(font) + }); + let id = adding.thread().id(); + while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard"); + let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY); + assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped"); + drop(steady); + assert!(adding.join().unwrap() > 0, "guarded {guarded}: the font is new to this database"); + }); + assert_ne!(db.generation(), before, "guarded {guarded}: the change is made once the guard is dropped"); + } + let db = FontDb::with_font_dirs(vec![]); + let steady = crate::test_fonts::steady_fonts(&db); + std::thread::scope(|scope| { + let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap())); + let id = adding.thread().id(); + while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + let before = db.generation(); + assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0); + let after = db.generation(); + assert_ne!(after, before, "the guard's own thread changes the fonts"); + assert!(!adding.is_finished(), "the waiting change still waits for the guard"); + assert_eq!(db.generation(), after, "the waiting change still waits for the guard"); + drop(steady); + assert!(adding.join().unwrap() > 0); + }); +} + +/// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`] +/// held for another database, so a thread holding one can catalog a database that another thread +/// is scanning. +#[test] +fn a_first_scan_does_not_wait_for_steady_fonts() { + let (held, scanned) = (FontDb::with_font_dirs(vec![]), FontDb::with_font_dirs(vec![])); + let steady = crate::test_fonts::steady_fonts(&held); + std::thread::scope(|scope| { + let scanning = scope.spawn(|| scanned.load_system_fonts()); + let id = scanning.thread().id(); + while !scanning.is_finished() && !crate::test_fonts::font_changers().contains(&id) { + std::thread::yield_now(); + } + let finished = scanning.is_finished(); + drop(steady); + assert!(finished, "the first scan waited for the guard"); + scanning.join().unwrap(); + }); +} + +/// A font that a hook adds while another add publishes its faces, on the same thread, is added +/// without that thread waiting for its own change. +#[test] +fn a_font_added_while_faces_are_published_is_added() { + let db = Arc::new(FontDb::with_font_dirs(vec![])); + let adder = db.clone(); + // Not scoped: a thread that waits for its own change never finishes, and the test still reports. + let adding = std::thread::spawn(move || { + let (hook_db, mut extra) = (adder.clone(), crate::test_fonts::two_axis_font()); + crate::fontdb::on_faces_published(Some(Box::new(move || { + if let Some(font) = extra.take() { + hook_db.add_font(font); + } + }))); + let added = adder.add_font(crate::test_fonts::variable_font().unwrap()); + crate::fontdb::on_faces_published(None); + added + }); + let id = adding.thread().id(); + let changes = || crate::test_fonts::font_changers().iter().filter(|t| **t == id).count(); + while !adding.is_finished() && changes() < 2 { + std::thread::yield_now(); + } + assert!(adding.is_finished(), "the hook's add waited for the change around it"); + assert!(adding.join().unwrap() > 0); + let families = db.families(); + for family in [crate::test_fonts::VARIABLE_FAMILY, crate::test_fonts::TWO_AXIS_FAMILY] { + assert!(families.iter().any(|f| f == family), "{family} is added"); + } +} + /// A bundled Source Sans 3 file renamed [`FAMILY`] (as long as the original name). fn renamed(file: &str) -> Vec { renamed_to(file, FAMILY) diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 688f295478..98d0b999cb 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -705,8 +705,12 @@ pub(crate) mod testutil { /// and a count must not include a refresh another test caused. static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(()); - pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> { - LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()) + /// Catalogs the installed fonts, then also holds back the font changes other tests make without + /// [`changing_layout_inputs`] (a system font loaded for a character no loaded font covers, a + /// rescan) until it is dropped. + pub fn steady_layout_inputs() -> (std::sync::RwLockReadGuard<'static, ()>, vectorcraft_text::test_fonts::SteadyFonts) { + let inputs = LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner()); + (inputs, vectorcraft_text::test_fonts::steady_fonts(vectorcraft_text::FontDb::global())) } pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> { From f88a6b5877a8826fe4c3a1a6ed6e2152a1b93846 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:47:54 -0800 Subject: [PATCH 050/126] Eraser: a drag's outline takes the tip halfway along each step in two more cases The outline of an Eraser drag takes, at each step, the tip the pen gives halfway along it, as path.eraseRegion erases. Two cases still used the tips at the step's ends: - A round tip whose Size follows the pen drew each step as wide as the mean of the tips at its ends. Where an end is held at the 0.1 pt least size, that mean differs from the tip halfway along: with Size 10 pt on Pressure by 20 pt, a step from no pressure to full pressure showed 15.05 pt wide where the release erases 10 pt. - A pen turned or tilted in place at the last point updated the last step only when the tip at that point changed. With Size 10 pt on Tilt by 20 pt, tilting from 80 to 85 degrees after an upright point keeps the end tip at 0.1 pt while the tip halfway along goes from 12.22 pt to 11.11 pt, and the outline kept the old one. The area outline now keeps and compares the tip halfway along the last step. --- crates/tools/src/draw2/gesture.rs | 14 ++---- crates/tools/src/draw2/gesture/area.rs | 29 +++++------ crates/tools/src/draw2/gesture/tests.rs | 67 +++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 24 deletions(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index ba5e8afe9c..dc123e6cc1 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1300,12 +1300,6 @@ impl GestureTool { self.poses.len() == self.points.len() } - /// The tip at point `i` of the stroke, as `path.eraseRegion` reads the pen there - /// ([`Self::controls_of_point`]). - fn tip_of_point(&self, i: usize) -> [f64; 3] { - self.tip_of_controls(self.controls_of_point(i)) - } - /// The tip halfway along the step from point `j` to point `j + 1`, as `path.eraseRegion` reads /// the pen there: the pressure and tilt halfway between those at the two points, and the /// bearing and rotation halfway between them the shorter way round. A tip whose angle follows @@ -1945,7 +1939,7 @@ impl Tool for GestureTool { }; let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0])); let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }]; - area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j))); + area.step(&self.points, &|j| sized(self.tip_between(j))); let paths = area.paths(&self.points); o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None })); o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false })); @@ -1953,9 +1947,9 @@ impl Tool for GestureTool { self.area.set(Some(area)); } else if size_varies { // With Size on a mode that follows the pen, each step of the drag shows as wide as the - // tip the pen gives at its ends. A long drag's steps are kept from call to call - // ([`LinePreview::segments`]). - let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32; + // tip the pen gives halfway along it, as `path.eraseRegion` reads it. A long drag's + // steps are kept from call to call ([`LinePreview::segments`]). + let width_of = |j: usize| (self.tip_between(j)[2] * cx.zoom) as f32; if self.points.len() > line::PIECE_SEGMENTS + 1 { let mut kept = self.line.take().unwrap_or_default(); for (j, path) in kept.segments(&self.points).into_iter().enumerate() { diff --git a/crates/tools/src/draw2/gesture/area.rs b/crates/tools/src/draw2/gesture/area.rs index 5a33e6e77f..9c3a9f8cb6 100644 --- a/crates/tools/src/draw2/gesture/area.rs +++ b/crates/tools/src/draw2/gesture/area.rs @@ -157,8 +157,8 @@ pub(super) struct AreaPreview { sq: Vec, /// The last point taken, on the page. last: Point, - /// The tip at the last point taken, when the tip varies along the drag. - last_tip: Option, + /// The tip halfway along the last segment taken, when the tip varies along the drag. + last_middle: Option, /// The tip's radius along each segment, where its tip is round. It is also as far as the /// segment's area reaches from the segment in the grid's space. radius: Vec, @@ -196,7 +196,7 @@ impl AreaPreview { side: widest.max(MIN_BRUSH_SIZE), sq: vec![], last: first, - last_tip: None, + last_middle: None, radius: vec![], to_round: vec![], pieces: vec![], @@ -240,20 +240,22 @@ impl AreaPreview { } /// Take the points of the drag `pts` added since the last call and check outlines, within this - /// call's limits. When the tip varies along the drag, `tip(i)` gives the tip at point `i`, and - /// segment `j` takes `middle(j)`, the tip halfway along it. A last point whose tip changed since - /// it was taken (a pen turned or tilted in place) gives its segment the new tip. - pub(super) fn step(&mut self, pts: &[Point], tip: &dyn Fn(usize) -> Tip, middle: &dyn Fn(usize) -> Tip) { + /// call's limits. When the tip varies along the drag, segment `j` takes `middle(j)`, the tip + /// halfway along it. A last segment whose tip halfway along it changed since it was taken (a pen + /// turned or tilted in place at its end) takes the new tip, also where the tip at its end stays + /// the same (a size held at its least). + pub(super) fn step(&mut self, pts: &[Point], middle: &dyn Fn(usize) -> Tip) { self.work = AreaWork::default(); let mut changed = BTreeSet::new(); if self.key.varies && let Some(j) = self.sq.len().checked_sub(2) - && self.last_tip.is_some_and(|t| t != tip(j + 1)) + && self.last_middle.is_some_and(|t| t != middle(j)) { let k = self.piece_of(j); let old = self.radius[j]; - self.set_tip(j, middle(j)); - self.last_tip = Some(tip(j + 1)); + let tip = middle(j); + self.set_tip(j, tip); + self.last_middle = Some(tip); changed.insert(k); // The pieces near the old tip or the new one are checked again. let new = self.radius[j]; @@ -266,13 +268,12 @@ impl AreaPreview { self.sq.push(self.squash * pts[i]); self.last = pts[i]; self.work.points += 1; - if self.key.varies { - self.last_tip = Some(tip(i)); - } let Some(j) = i.checked_sub(1) else { continue }; if self.key.varies { self.radius.push(0.0); - self.set_tip(j, middle(j)); + let tip = middle(j); + self.set_tip(j, tip); + self.last_middle = Some(tip); } else { self.radius.push(self.key.size / 2.0); } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 87d18ca4b4..1ffcf1c37b 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -3622,6 +3622,73 @@ fn the_eraser_drag_area_takes_the_tip_halfway_along_each_step() { t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) }); } +/// A step of a round Eraser drag whose Size follows the pen shows as wide as the tip halfway along +/// it, as the release erases: with Size 10 pt on Pressure by up to 20 pt, a step from no pressure +/// (the tip at its 0.1 pt least) to full pressure (30 pt) shows 10 pt wide, not the 15.05 pt +/// halfway between the tips at its ends. +#[test] +fn a_round_eraser_drag_step_is_as_wide_as_the_tip_halfway_along_it() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(10)), ("sizeMode", json!("pressure")), ("sizeVariation", json!(20))] { + t.set_option(k, &v); + } + t.pointer(&cx, &PointerEvent { pressure: 0.0, ..PointerEvent::new(PointerKind::Down, 50.0, 150.0) }); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Drag, 150.0, 150.0) }); + let o = t.overlays(&cx); + assert!(matches!(&o[..], [Overlay::Path { width, .. }] if (*width - 10.0).abs() < 1e-4), "{o:?}"); + t.pointer(&cx, &PointerEvent { pressure: 1.0, ..PointerEvent::new(PointerKind::Up, 150.0, 150.0) }); +} + +/// A pen tilted in place at the last point of an Eraser drag gives the last step the new tip halfway +/// along it, even where the tip at that point stays the same: with Size 10 pt on Tilt by up to 20 pt, +/// the tip at a pen leaning 80° and at one leaning 85° is the 0.1 pt least, while halfway along a +/// step from an upright pen it goes from 12.22 pt to 11.11 pt. +#[test] +fn the_eraser_drag_area_takes_the_new_tip_halfway_along_a_step_whose_end_tip_stays() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) }; + let bounds = |t: &GestureTool| { + drain_area(t, &cx); + let o = t.overlays(&cx); + o.iter() + .filter_map(|o| match o { + Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + Overlay::SharedPath { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(&**path)), + _ => None, + }) + .reduce(|a, b| a.union(b)) + .unwrap_or_else(|| panic!("{o:?}")) + }; + // The tip lying level, 4 times as long as it is wide: a step from x 50 to x 150 with a tip + // `size` long reaches `size` / 2 before and after it and `size` / 8 above and below. + let near = |b: vectorcraft_geom::Rect, size: f64| { + let want = (50.0 - size / 2.0, 150.0 - size / 8.0, 150.0 + size / 2.0, 150.0 + size / 8.0); + assert!([b.x0 - want.0, b.y0 - want.1, b.x1 - want.2, b.y1 - want.3].iter().all(|e| e.abs() < 0.01), "{b:?} vs {want:?}"); + }; + let mut t = GestureTool::new("eraser"); + for (k, v) in [("size", json!(10)), ("roundness", json!(25)), ("sizeMode", json!("tilt")), ("sizeVariation", json!(20))] { + t.set_option(k, &v); + } + let press = |t: &mut GestureTool, lean: f32, kind: PointerKind, x: f64| { + let pen = Some(PenPose { tilt: Some([lean, 0.0]), rotation: None, wheel: None }); + t.pointer(&cx, &PointerEvent { pen, pressure: 1.0, ..PointerEvent::new(kind, x, 150.0) }); + }; + press(&mut t, 0.0, PointerKind::Down, 50.0); + press(&mut t, 80.0, PointerKind::Drag, 150.0); + // Tilt reads 1 upright and 1/9 at 80°, 5/9 halfway: 10 + 20 × (2 × 5/9 − 1) pt. + near(bounds(&t), 10.0 + 20.0 / 9.0); + // At 85° Tilt reads 1/18, 19/36 halfway. + press(&mut t, 85.0, PointerKind::Drag, 150.0); + near(bounds(&t), 10.0 + 20.0 / 18.0); + press(&mut t, 85.0, PointerKind::Up, 150.0); +} + /// The outline of a long Eraser drag whose tip turns and changes shape with the pen is built a /// bounded amount per frame, and once finished it shows nothing inside the area: no point of it /// lies well inside the area of any step, each step with the tip halfway along it. From 34c961a5cee80d602573722a2fc3b71b8e268a4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:49:07 -0800 Subject: [PATCH 051/126] Tests: the widget order benchmark checks editability once in its baseline The baseline of widget_order_perf kept the selection's editable objects and then asked each widget about the whole selection in the same document, so a widget that checks editability itself (corners of any path on 128 rectangles on a locked artboard) measured each object twice. The baseline now asks the widget about the kept objects in a copy of the document with everything editable, as the_widgets_are_the_same_as_when_editability_came_first does. --- crates/tools/src/widget_order_tests.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/widget_order_tests.rs b/crates/tools/src/widget_order_tests.rs index afe52c6f73..545a74e211 100644 --- a/crates/tools/src/widget_order_tests.rs +++ b/crates/tools/src/widget_order_tests.rs @@ -287,9 +287,11 @@ fn cpu_time(f: impl FnOnce()) -> std::time::Duration { } /// 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 the -/// widgets made before their kind check (the same calls, on the same ids), and without it. 7 runs -/// each, in turn. Ignored by default; it prints the median per call and sets no bound on it: +/// 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"] @@ -317,6 +319,9 @@ fn widget_order_perf() { } 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; @@ -325,8 +330,8 @@ fn widget_order_perf() { let before = || { for _ in 0..CALLS { let editable = doc.editable(); - std::hint::black_box(sel.objects.iter().filter(|id| editable(**id)).count()); - std::hint::black_box(f(std::hint::black_box(doc), sel, p)); + 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 = || { From 2ea35324b7acc9c1150c56a11cbcd631b89071bb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:53:47 -0800 Subject: [PATCH 052/126] Pathfinder: Outline of a compound shape with no fill adds no stroke of its own The paint source for a compound shape's area held every painting item of the shape, strokes included. When the shape had no fill, Outline fell back to that stroke and gave the edges a 1 pt stroke in its paint, while the shape's own appearance stroked the result again. The area now takes only the shape's top painting fill, so an unfilled compound shape's Outline edges carry no paint of their own. --- crates/effects/src/group.rs | 5 +++-- crates/effects/src/group/tests.rs | 19 +++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index aeffaacfb6..eaaf6a99e8 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -583,9 +583,10 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option Option { diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 1c62508347..345bb4a0bd 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -263,6 +263,25 @@ fn outline_strokes_a_compound_shapes_area_in_its_fill() { } } +/// Outline of a compound shape with no fill gives the edges no paint of their own when Remove +/// Unpainted Artwork is off. The shape's own appearance strokes the result, so the shape's stroke +/// is not copied onto the edges. +#[test] +fn outline_of_an_unfilled_compound_shape_adds_no_stroke() { + let mut g = compound_shape(ShapeMode::Add); + let mut a = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 4.0); + if let Some(AppearanceItem::Stroke(s)) = a.items.last_mut() { + s.opacity = 0.5; + } + g.appearance = a.into(); + g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({"removeUnpainted": false}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + assert!(!out.is_empty(), "{out:#?}"); + for n in &out { + assert!(!n.appearance.items.iter().any(paints), "{n:#?}"); + } +} + /// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's /// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out /// the member's segments either way. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..f696d61045 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6218,7 +6218,8 @@ Each Effect › Pathfinder effect (`pathfinder.add` … `pathfinder.softMix`, no in its params: `precision` (a number, 0.001–10 pt), `removeRedundantPoints` and `removeUnpainted` (true or false), which mean what they mean for the panel's operations; the other operations ignore `removeUnpainted`. With `removeUnpainted` on, a compound shape's area counts as filled when the shape has a visible fill of its own, and Divide keeps every piece -when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill. `effect.apply` +when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill, and gives +the edges no paint when the shape has no fill (the shape's own strokes still draw over the result). `effect.apply` fills the ones `params` leave out from the current Pathfinder Options, and the values join its journal entry. An effect saved without them evaluates with precision 0.01 and both switches off, as before effects kept them. `effect.setParams {index, params: {precision?, removeRedundantPoints?, removeUnpainted?}}` edits them as one undo step; values the From 9455a3f10e4f16178753337974d3665e4318fe71 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:56:57 -0800 Subject: [PATCH 053/126] Dimension: a first Linear point keeps its link when the art moves before the second click A first point picked on a corner of a path's preview bounds was linked to the path only at the second click, by fitting the coordinate from the first click to the path's anchors as they were then. When the path moved in between, the dimension measured from where the corner had been: picking the upper-left corner of a stroked rectangle, moving the rectangle 20 points right and picking its upper-right corner measured 121 points instead of 101. The tool now records the first point's link at its click (held against the corner's path, or on the segment under it) and keeps that link for the dimension while it still resolves. The first point, the rubber band, Shift and the dimension start from where the art puts the point now, and a first point on an anchor follows its anchor the same way. A link that no longer resolves falls back to the point as picked. --- crates/tools/src/dimension.rs | 143 +++++++++++++++++++++++++++++++--- docs/dimensions.md | 5 +- 2 files changed, 135 insertions(+), 13 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 5e2e179bdf..46cc0694e8 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -77,6 +77,10 @@ pub struct DimensionTool { /// The path that holds the first Linear point, when it was picked on a corner of that path's /// preview bounds. first_corner: Option, + /// The link the first Linear point took at its click when it was not on an anchor: held + /// against the path whose preview-bounds corner it was picked on, or on the segment under it. + /// When the art moves before the second click, the first point moves with it. + first_link: Option, /// Whether the press under way began on an anchor a Linear click picks. press_on_anchor: bool, /// The second point clicked for the Linear dimension being placed, and where the pointer was @@ -564,28 +568,34 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option { /// point, so that it moves with that path. None when neither point has a path to link to. /// `held_a` and `held_b` name the path holding a point picked on a corner of that path's /// preview bounds: such a point is held against that path, however far its strokes or effects -/// put the corner from the path and whatever other segment lies there. +/// put the corner from the path and whatever other segment lies there. `link_a` is the link the +/// first point took at its own click ([`own_link`]): while it still resolves, the point keeps it, +/// whatever other art lies there now. fn points_source( cx: &ToolContext, (a, ra, held_a): (Point, &Option, Option), (b, rb, held_b): (Point, &Option, Option), + link_a: Option, ) -> Option { // A path deleted since the pick holds nothing. let holder = |held: Option| held.filter(|node| cx.doc.node(*node).is_some()); let (corner_a, corner_b) = (holder(held_a), holder(held_b)); + let link_a = link_a.filter(|link| ra.is_none() && link.position(cx.doc).is_some()); let edge = |p: Point, corner: Option| if corner.is_some() { None } else { pick(cx, p) }; - let (edge_a, edge_b) = (edge(a, corner_a), edge(b, corner_b)); + let (edge_a, edge_b) = (if link_a.is_some() { None } else { edge(a, corner_a) }, edge(b, corner_b)); let node = |r: &Option, corner: Option, e: &Option| { r.as_ref().map(|r| r.node).or(corner).or_else(|| e.as_ref().map(|e| e.node)) }; - let (path_a, path_b) = (node(ra, corner_a, &edge_a), node(rb, corner_b, &edge_b)); + let path_a = link_a.as_ref().map(FreePoint::node).or_else(|| node(ra, corner_a, &edge_a)); + let path_b = node(rb, corner_b, &edge_b); let free = |p: Point, r: &Option, edge: &Option, own: Option, other: Option| { if r.is_some() { return None; } edge.as_ref().and_then(|e| FreePoint::on_segment(cx.doc, e, p)).or_else(|| own.or(other).and_then(|node| FreePoint::on(cx.doc, node, p))) }; - let (free_a, free_b) = (free(a, ra, &edge_a, path_a, path_b), free(b, rb, &edge_b, path_b, path_a)); + let free_a = link_a.or_else(|| free(a, ra, &edge_a, path_a, path_b)); + let free_b = free(b, rb, &edge_b, path_b, path_a); (ra.is_some() || rb.is_some() || free_a.is_some() || free_b.is_some()).then(|| DimensionSource::Points { a: ra.clone(), b: rb.clone(), @@ -595,6 +605,17 @@ fn points_source( }) } +/// The link a point picked at `p` off any anchor takes from its own pick, as [`points_source`] +/// links it: held against `corner`'s path when it was picked on a corner of that path's preview +/// bounds, else on the segment under it, or held against that segment's path. None when nothing +/// under it holds it. +fn own_link(cx: &ToolContext, p: Point, corner: Option) -> Option { + match corner.filter(|node| cx.doc.node(*node).is_some()) { + Some(node) => FreePoint::on(cx.doc, node, p), + None => pick(cx, p).and_then(|e| FreePoint::on_segment(cx.doc, &e, p).or_else(|| FreePoint::on(cx.doc, e.node, p))), + } +} + impl DimensionTool { /// Where a Linear pick at `p` lands: with Use Preview Bounds on, on the nearest corner of a /// path's preview bounds within reach, where they differ from its anchors, unless another @@ -610,6 +631,7 @@ impl DimensionTool { /// A point the guides leave where the pointer is (right on a guide line) stays there, and with /// Snap to Pixel or Snap to Grid on a point stays where they place it. fn snap_linear(&mut self, cx: &ToolContext, p: Point) -> (Point, Option) { + self.follow_first(cx); let leave = self.points.last().map(|(first, anchor)| match anchor { Some(_) => crate::guides::Leave::segment(cx, *first, false), None => crate::guides::Leave::contact(*first), @@ -652,6 +674,26 @@ impl DimensionTool { None => (p, None), } } + /// Moves the first Linear point to where its link puts it in the document as it is now: on + /// its anchor, or where [`Self::first_link`] holds it. A point whose link no longer resolves, + /// or that has none, stays where it was picked. + fn follow_first(&mut self, cx: &ToolContext) { + if let Some(now) = self.first_now(cx) + && let [(at, _)] = self.points.as_mut_slice() + { + *at = now; + } + } + /// Where the first Linear point is in the document as it is now ([`Self::follow_first`]), + /// while it is the only point picked. + fn first_now(&self, cx: &ToolContext) -> Option { + let [(at, reference)] = self.points.as_slice() else { return None }; + let now = match reference { + Some(r) => r.position(cx.doc), + None => self.first_link.as_ref().and_then(|link| link.position(cx.doc)), + }; + Some(now.unwrap_or(*at)) + } fn target(&self, cx: &ToolContext, p: Point) -> Option { let edge = pick(cx, p)?; match self.kind { @@ -800,6 +842,7 @@ impl DimensionTool { self.on_end = false; self.corner = None; self.first_corner = None; + self.first_link = None; self.points.clear(); self.lines.clear(); self.dragging = false; @@ -824,12 +867,13 @@ impl DimensionTool { reference = reference.filter(|r| r.position(cx.doc) == Some(at)); corner = corner.filter(|_| at.distance(snapped) <= 1e-9); } - self.points.push((at, reference)); - if self.points.len() == 1 { + if self.points.is_empty() { self.first_corner = corner; + self.first_link = reference.is_none().then(|| own_link(cx, at, corner)).flatten(); } + self.points.push((at, reference)); if let [(a, ra), (b, rb)] = self.points.as_slice() { - let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner)); + let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner), self.first_link.take()); self.first_corner = None; let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source); if d.resolve(cx.doc).is_ok() { @@ -1041,8 +1085,10 @@ impl Tool for DimensionTool { None => {} } } + // The first point where the art puts it now, also when the art moved without a pointer move. + let first = self.first_now(cx); for (p, _) in &self.points { - out.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 }); + out.push(Overlay::Anchor { p: first.unwrap_or(*p), color, filled: true, size: 6.0 }); } for edge in &self.lines { segment(edge, &mut out); @@ -1057,10 +1103,10 @@ impl Tool for DimensionTool { let on_anchor = reference.is_some() || self.on_end; out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } }); } - if let Some((p, _)) = self.points.last() { + if let Some(p) = first.or_else(|| self.points.last().map(|(p, _)| *p)) { let target = snapped.map_or(self.at, |(q, _)| q); - let b = if self.shift { constrained(cx, *p, target) } else { target }; - out.push(Overlay::Line { a: *p, b, color, dashed: true }); + let b = if self.shift { constrained(cx, p, target) } else { target }; + out.push(Overlay::Line { a: p, b, color, dashed: true }); } // The Smart Guides of the point the next click picks (after the rubber band). if linear_pick { @@ -1814,7 +1860,7 @@ mod tests { let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; let (corner, b) = (Point::new(99.5, 99.5), Point::new(250.0, 99.5)); for (held, node) in [(Some(id), id), (None, line)] { - let source = points_source(&c, (corner, &None, held), (b, &None, None)); + let source = points_source(&c, (corner, &None, held), (b, &None, None), None); let Some(DimensionSource::Points { free_a: Some(free), .. }) = &source else { panic!("{source:?}") }; let linked = match free { FreePoint::Anchors { node, .. } => *node, @@ -1824,6 +1870,79 @@ mod tests { } } + /// A first point keeps its link when the art moves before the second click: a point picked on + /// a corner of the preview bounds, on a segment or on an anchor is measured, shown and + /// constrained by Shift from where the art puts it now. + #[test] + fn a_first_point_follows_art_moved_before_the_second_click() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + let moved = |by: (f64, f64)| { + let mut m = d.clone(); + m.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::translate(by), false); + m + }; + let click = |t: &mut DimensionTool, c: &ToolContext, (x, y): (f64, f64), shift: bool| { + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + let mut ev = PointerEvent::new(kind, x, y); + ev.mods.shift = shift; + t.pointer(c, &ev); + } + }; + let base = |doc| ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(doc, &s, &p) }; + // A corner of the preview bounds, then the rectangle moved 20 points right. + let right = moved((20.0, 0.0)); + let mut t = DimensionTool::default(); + click(&mut t, &base(&d), (101.0, 101.0), false); + let c = ToolContext { revision: (0, 1), ..base(&right) }; + let shown = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Anchor { p, filled: true, .. } if near(p, Point::new(119.5, 99.5)))); + assert!(shown, "the first point shows at the moved corner before the pointer moves"); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 219.0, 101.0)); + let band = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Line { a, dashed: true, .. } if near(a, Point::new(119.5, 99.5)))); + assert!(band, "the rubber band starts at the moved corner"); + click(&mut t, &c, (219.0, 101.0), false); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(119.5, 99.5)) && near(pending.b, Point::new(220.5, 99.5)), "{:?} {:?}", pending.a, pending.b); + assert!((pending.length - 101.0).abs() < 1e-9, "{}", pending.length); + let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; + assert!(free.position(&right).is_some_and(|q| near(q, Point::new(119.5, 99.5))), "{free:?}"); + // A point on the top segment, then the rectangle moved 20 points down. + let down = moved((0.0, 20.0)); + let mut t = DimensionTool::default(); + let unbounded = |doc| ToolContext { preview_bounds: false, ..base(doc) }; + click(&mut t, &unbounded(&d), (150.0, 100.0), false); + click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 300.0), false); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(150.0, 120.0)), "{:?}", pending.a); + let Some(DimensionSource::Points { free_a: Some(FreePoint::OnSegment { edge, .. }), .. }) = &pending.source else { + panic!("{:?}", pending.source) + }; + assert_eq!(edge.node, id); + // The same, with a line drawn on top along the moved segment before the second click: the + // point keeps the segment it was picked on, where a pick there now finds the line. + let mut covered = down.clone(); + let (l, line) = (covered.layers[0].id, covered.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 120.0), Point::new(300.0, 120.0)], false)); + covered.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line"); + let c = unbounded(&covered); + let at = Point::new(150.0, 120.0); + assert_eq!(pick(&c, at).map(|e| e.node), Some(line)); + let link = own_link(&unbounded(&d), Point::new(150.0, 100.0), None); + assert!(matches!(&link, Some(FreePoint::OnSegment { edge, .. }) if edge.node == id), "{link:?}"); + let source = points_source(&c, (at, &None, None), (Point::new(300.0, 300.0), &None, None), link); + let Some(DimensionSource::Points { free_a: Some(FreePoint::OnSegment { edge, .. }), .. }) = &source else { panic!("{source:?}") }; + assert_eq!(edge.node, id, "the line on top does not take the point"); + // An anchor, then the rectangle moved 20 points down: Shift constrains from the anchor's + // new place. + let mut t = DimensionTool::default(); + click(&mut t, &unbounded(&d), (100.0, 100.0), false); + click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 124.0), true); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(100.0, 120.0)) && (pending.b.y - 120.0).abs() < 1e-9, "{:?} {:?}", pending.a, pending.b); + } + /// Hovering right on the end of a dimension's line shows the anchor ring there. #[test] fn hovering_right_on_a_dimension_lines_end_shows_the_anchor_ring() { diff --git a/docs/dimensions.md b/docs/dimensions.md index 7acc2155f6..389154d0a8 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -31,7 +31,10 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers anchor, guide, grid or pixel snapping places lands on the closest point of a segment, or of a line of a dimension already drawn, within 8 pixels. With Smart Guides and Anchor/Path Labels on, a point on an anchor or a line end shows the "anchor" label, and a point on a segment or - line shows the "path" label. These rules apply to the Linear points. + line shows the "path" label. These rules apply to the Linear points. A first point picked on + an anchor, on a segment or on a corner of preview bounds moves with that art when the art moves + before the second click: the rubber band, Shift and the dimension start from where the art puts + the point then. With Use Preview Bounds on (Preferences › General), a Linear point can land on a corner of the preview bounds of a path or compound path whose strokes or effects reach past its anchors. The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) From 7884babf0a2722ed7edac310d10dee320dbcdbe0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:00:24 -0800 Subject: [PATCH 054/126] Path Precision Tools: the Tangent Circle Tool finds both circles where two second segments touch close together With a radius, each second segment is searched on its own, and each circle is then checked against all of them. Before, one search over the nearest of the second segments found one circle where two segments touched circles between the same two places tried along the first segment, so the tool could not pick the other. Follows #8526. --- .../addons/pathtools/tangent_circle/on_segments.rs | 14 ++++++++++++-- .../src/addons/pathtools/tangent_circle/tests.rs | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) 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..f5d4df2647 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,17 @@ 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(); + ts.sort_by(f64::total_cmp); + 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))]); From 5721f9693195d2e0a55e68537a74aad96680336a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:14:07 -0800 Subject: [PATCH 055/126] Expand Appearance: Safe Mode checks symbol art that a group's raster effect draws A plain symbol instance does not expand on its own, so the Safe Mode plug-in check skipped its symbol's art. When a group or layer around the instance has a raster effect (its own, or on one of its fills or strokes), the group's image draws that art, plug-in effect included, and Expand Appearance committed pixels without the plug-in effect instead of returning the Safe Mode error. The check now looks into every object of such a group or layer, symbol art included. --- crates/engine/src/cmd/effectcmd.rs | 10 ++++-- crates/engine/tests/plugin_safe_mode.rs | 43 +++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index edb5561796..cb399eca1c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -1611,13 +1611,18 @@ fn expanded_node( /// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that /// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an -/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does). A symbol's +/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does +/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's /// art counts where an instance of it expands. `seen` holds the symbols already looked into. fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet) -> bool { let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); let mut symbols = vec![]; + let mut drawn = vec![]; let mut holds = false; n.walk(&mut |c| { + if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() { + drawn.push(c); + } if !in_art && !expandable(c) { return; } @@ -1627,6 +1632,7 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col } }); holds + || drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen)) || symbols.into_iter().any(|name| { seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen)) }) diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 9ff0d0668a..a469e68f20 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -463,6 +463,49 @@ fn expand_appearance_keeps_a_plug_in_effect_safe_mode_skips() { s.execute("effect.expandAppearance", &json!({})).unwrap(); } +/// In Safe Mode, Expand Appearance refuses a group whose raster effect makes an image of a plain +/// instance in it when the instance's symbol art holds a plug-in effect. +#[test] +fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.sym", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.sym"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 100})).unwrap()["id"].clone(); + let refused = |s: &mut Session, group: &Value| { + let before = s.execute("document.inspect", &json!({})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let err = s.execute("effect.expandAppearance", &json!({"ids": [group]})).unwrap_err().to_string(); + safe_mode::set_active(None); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + assert_eq!(s.execute("document.inspect", &json!({})).unwrap(), before, "nothing changes"); + }; + // A Gaussian Blur of the group's own. + let group = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap(); + refused(&mut s, &group); + // A Gaussian Blur on a fill of a group around a group that holds another plain instance. + let blurred_fill = { + let t = s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [t], "item": 0, "params": {"radius": 2}})).unwrap(); + s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(t)).unwrap().appearance.items[0].clone() + }; + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 100, "y": 20})).unwrap()["id"].clone(); + let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + let outer = s.execute("object.group", &json!({"ids": [inner]})).unwrap()["id"].as_u64().unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) + .node_mut(vectorcraft_engine::doc::NodeId(outer)) + .unwrap() + .appearance + .items + .push(blurred_fill); + refused(&mut s, &json!(outer)); +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..44c8d11c38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13212,7 +13212,8 @@ session and refuses `--connect`. In Safe Mode no plug-in loads or runs: `plugin.install`, `plugin.run`, `plugin.reload` and exporters return an error, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect: `effect.list` gives that effect `skipped: true`, and the Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an -error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. `vectorcraft` rejects an option it does not know (such as +error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a +plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or From 91e2551f47f89fc511bd1f024764749fecfc4d8a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:38:04 -0800 Subject: [PATCH 056/126] Kinsoku sets: tests for pasted type and shaped lines under a custom set Pasted type whose custom set was edited after the copy is checked against a fresh layout by its line ends, which move from A to B while the line count stays the same, so the test fails without the relayout in Relink. The every-line composer's first-word measure is checked in a frame whose top is narrower than the word the custom set's Cannot End Line makes, so the test fails when that measure uses the built-in setting instead. --- crates/engine/src/cmd/kinsokusets/tests.rs | 30 +++++++++++++ crates/text/src/layout/wrapping_tests.rs | 52 ++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/crates/engine/src/cmd/kinsokusets/tests.rs b/crates/engine/src/cmd/kinsokusets/tests.rs index 1d1c8980c0..04456872b2 100644 --- a/crates/engine/src/cmd/kinsokusets/tests.rs +++ b/crates/engine/src/cmd/kinsokusets/tests.rs @@ -332,6 +332,36 @@ fn pasted_type_brings_its_kinsoku_sets() { assert_eq!(style_set(&s), Value::Null); } +/// Type pasted back after its set was edited breaks its lines by the set as it is now: with B in +/// Cannot End Line the first line of `A B C` ends at A, and once the set holds nothing, it ends at B. +#[test] +fn pasted_type_relayouts_after_its_kinsoku_set_was_edited() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotEnd": "B"}]})).unwrap(); + let create = json!({"x": 10, "y": 10, "text": "A B C", "size": 20, "font": "JetBrains Mono", "area": {"width": 40, "height": 120}}); + let id = s.execute("text.create", &create).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap(); + let lines = |t: &vectorcraft_doc::TextObject| t.baselines().collect::>(); + let first_width = |t: &vectorcraft_doc::TextObject| t.baselines().next().map(|(a, b)| b.x - a.x).unwrap_or_default(); + let copied = text(&s, id); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight"}]})).unwrap(); + // The set's edit lays the type in the document out anew, and its first line takes B. + let edited = text(&s, id); + assert_eq!(lines(&edited).len(), 2); + assert!(first_width(&edited) > first_width(&copied), "{:?} against {:?}", lines(&edited), lines(&copied)); + + let v = s.execute("edit.paste", &json!({})).unwrap(); + let t = text(&s, v["ids"][0].as_u64().unwrap()); + let now = s.doc().unwrap().doc.kinsoku_sets[0].clone(); + assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now)); + let mut fresh = t.clone(); + crate::cmd::typecmd::refresh_bounds(&mut fresh); + assert_eq!(lines(&t), lines(&fresh), "the pasted type is laid out with the edited set"); + assert_eq!(first_width(&t), first_width(&edited)); +} + /// A pasted set whose name, at the longest a name can be, the document's set with other /// characters already has comes in under a free name that fits: the number takes the place of the /// name's last characters, and a space left at the end of them is dropped. A second paste uses diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index 96ccc3e5c7..225e58a053 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -1312,6 +1312,58 @@ fn shaped_composition_searches_share_the_frame_budget() { assert_eq!(three.steps_left.get(), breaking::MAX_TOTAL_STEPS, "the layout's own steps"); } +/// The every-line composer places a line where its first word fits, and measures that word by the +/// paragraph's custom Kinsoku set: with A in the set's Cannot End Line, the first word of `A BC` +/// runs past the space to the end, so the line `A` skips the frame's 20 pt top and takes the +/// 50 pt band below it. Without the set the word is `A` alone and the top holds it. +#[test] +fn shaped_first_word_uses_the_custom_kinsoku_set() { + use super::shaped::{Budget, Shaped}; + use crate::composer::Measure; + use std::cell::Cell; + use std::rc::Rc; + let text = "A BC"; + let glyphs = full_width(text); + let set = custom_set("", "A", "", &[]); + assert_eq!(breaking::word_width(&glyphs, 0, &[], breaking::KinsokuRules::Custom(&set), Burasagari::None), 40.0); + assert_eq!(breaking::word_width(&glyphs, 0, &[], Kinsoku::Hard, Burasagari::None), 10.0); + // 20 pt wide down to 40 pt, and 50 pt wide below. + let frame = BezPath::from_vec(vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((20.0, 0.0).into()), + PathEl::LineTo((20.0, 40.0).into()), + PathEl::LineTo((50.0, 40.0).into()), + PathEl::LineTo((50.0, 120.0).into()), + PathEl::LineTo((0.0, 120.0).into()), + PathEl::ClosePath, + ]); + let regions = region::Region::cells(&frame, &LayoutOptions::default(), &[]); + let pen = breaking::Pen { + regions: Some(®ions), + ri: 0, + prev: None, + pending: 0.0, + fb: FirstBaseline::Ascent, + fb_min: 0.0, + queued: vec![], + above: Default::default(), + model: LeadingModel::default(), + next_top: None, + no_room_for: f64::INFINITY, + steps_left: Rc::new(Cell::new(breaking::MAX_TOTAL_STEPS)), + search: Rc::new(Budget::default()), + }; + let first_line = |para: &ParaStyle| { + let mut measure = Shaped::new(&glyphs, &[], para, &|_| 0.0, false, false, &pen); + let state = measure.first(); + measure.line(&state, 0, 1).ok().flatten().map(|(width, _)| width) + }; + let hard = ParaStyle { kinsoku: Kinsoku::Hard, ..ParaStyle::default() }; + let custom = ParaStyle { kinsoku_set: Some(Arc::new(set)), ..hard.clone() }; + assert_eq!(first_line(&hard), Some(20.0), "the frame's top holds the word A"); + assert_eq!(first_line(&custom), Some(50.0), "the word A BC needs the band below"); +} + /// The glyphs of `text`, each 10 pt wide, with Korean words kept whole unless `anywhere` (Korean /// Line Break Anywhere on). fn korean(text: &str, anywhere: bool) -> Vec { From 4df95ec51f5ae6b3f2f308090125c767f673efb6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:06:34 -0800 Subject: [PATCH 057/126] Flare: a lone x2 or y2 in shape.flare is an error shape.flare took the rings' end point only when both x2 and y2 were numbers. Given one of them alone, it dropped it and placed the end point from pathLength and direction instead. It now refuses the call with "missing number `y2`" (or `x2`), as shape.editFlare already does, draws nothing and adds no undo step. With neither, or both null, pathLength and direction still place the end point. Saved flare settings that hold only one of x2 and y2 are no longer read as an editable flare; the group stays as art. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/create.rs | 2 +- crates/engine/src/cmd/flare.rs | 4 ++- crates/engine/src/tests.rs | 59 +++++++++++++++++++++++++++++++++ docs/mcp.md | 3 ++ docs/target-app-parity.md | 1 + 5 files changed, 67 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..e248f2bbc3 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Flare", [], None, - "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", + "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end, both or neither: one alone is an error; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", has_doc, super::flare::flare ), diff --git a/crates/engine/src/cmd/flare.rs b/crates/engine/src/cmd/flare.rs index 8871ddf921..17a566e29c 100644 --- a/crates/engine/src/cmd/flare.rs +++ b/crates/engine/src/cmd/flare.rs @@ -65,12 +65,14 @@ fn settings_of(p: &Value, cmd: &str) -> Result { }; let rays = count_or(p, "rays", 15, cmd)?.min(50); let rings = count_or(p, "rings", 10, cmd)?.min(50); + // The end point is given whole or not at all: a lone `x2` or `y2` is refused. let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) { (Some(x), Some(y)) => Point::new(x, y), - _ => { + (None, None) => { let a = f64_or(p, "direction", 45.0).to_radians(); finite_end(c + Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0), cmd)? } + _ => Point::new(f64_req(p, "x2", cmd)?, f64_req(p, "y2", cmd)?), }; let mut v = json!({ "cx": c.x, "cy": c.y, "x2": end.x, "y2": end.y, "rays": rays, "rings": rings, "seed": seed }); if let Some(r) = ring_seed { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c39c88cbbb..3d5cd0f82d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3491,6 +3491,65 @@ fn flare_counts_are_whole_numbers() { assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err()); } +/// `shape.flare` given only one of `x2` and `y2`, the other left out or null, refuses the call +/// naming the missing one, draws nothing and adds no undo step. +#[test] +fn flare_requires_both_endpoint_coordinates() { + let mut s = session(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.node_count(), st.history.undo.len(), st.history.redo.len()) + }; + let before = state(&s); + for (p, key) in [ + (json!({"cx": 100, "cy": 100, "x2": 300}), "y2"), + (json!({"cx": 100, "cy": 100, "x2": 300, "y2": null}), "y2"), + (json!({"cx": 100, "cy": 100, "y2": 300}), "x2"), + (json!({"cx": 100, "cy": 100, "x2": null, "y2": 300}), "x2"), + ] { + let err = s.execute("shape.flare", &p).expect_err(&p.to_string()).to_string(); + assert_eq!(err, format!("invalid parameters for `shape.flare`: missing number `{key}`"), "{p}"); + assert_eq!(state(&s), before, "{p}"); + } +} + +/// `shape.flare` with neither `x2` nor `y2` (left out or null) places the rings' end point from +/// `pathLength` and `direction`; with both it uses them. +#[test] +fn flare_omitted_or_null_endpoint_coordinates_use_path_fallback() { + let mut s = session(); + let mut end = |p: serde_json::Value| { + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + let spec = flare_settings(&s.doc().unwrap().doc, id).expect("a flare"); + Point::new(spec.params["x2"].as_f64().unwrap(), spec.params["y2"].as_f64().unwrap()) + }; + for p in [ + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0}), + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": null}), + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "y2": null}), + json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": null, "y2": null}), + ] { + let e = end(p.clone()); + assert!((e.x - 300.0).abs() < 1e-9 && (e.y - 100.0).abs() < 1e-9, "{p}: {e:?}"); + } + assert_eq!(end(json!({"cx": 100, "cy": 100, "pathLength": 200, "direction": 0, "x2": 40, "y2": 70})), Point::new(40.0, 70.0)); +} + +/// Settings a file holds with only one of `x2` and `y2` are not a flare's: the group stays as art, +/// but is not a flare that can be edited. +#[test] +fn flare_settings_with_a_lone_endpoint_coordinate_are_not_a_flare() { + let mut s = session(); + let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + let mut d = (*s.doc().unwrap().doc).clone(); + assert!(flare_settings(&d, id).is_some()); + let mut extras = d.node_mut(id).unwrap().extras_mut(); + let spec = extras.flare.as_deref_mut().expect("flare settings"); + spec.params.as_object_mut().unwrap().remove("y2"); + drop(extras); + assert!(flare_settings(&d, id).is_none()); +} + /// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that, /// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps /// its settings. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..8a876ec69c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2412,6 +2412,9 @@ and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gra `paint.freeform.splitLine`; `tolerance` and `gap` in `shapeBuilder.merge`; `gap` in `shapeBuilder.regions` and `shapeBuilder.copyRegion`; and `width` and `tolerance` in `livePaint.strokeEdge`. A null is read as a key left out. A gradient stop that names a swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. +`shape.flare` takes the rings' end point as both `x2` and `y2` or neither: given only one of them, with the other left +out or null, it answers `` missing number `y2` `` (or `` missing number `x2` ``), draws nothing and adds no undo step. +With neither, `pathLength` and `direction` place the end point. The Edit, document, guide and slice commands also check the type of each param and change nothing when one is wrong. A value that is not a number gets `` `dx` must be a number, not "10" ``: `dx` and `dy` in `edit.duplicate`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..9a8f155f43 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1307,6 +1307,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - An Alt-click (Option-click on macOS) with the Flare tool draws a flare centered at the click at once, without opening the Flare Tool Options, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf) describes for a default flare. As VectorCraft's own rules, the flare takes the tool's current options (the defaults until they are changed), Alt counts when it is held as the button goes down, a drag with Alt still draws the flare in two stages, and on the active perspective plane the flare is the one the click dialog's OK draws there (`alt_click_draws_a_flare_with_the_options_at_once`, `alt_click_draws_on_the_active_perspective_plane`, `an_alt_click_with_the_flare_tool_draws_the_flare_the_click_dialog_draws`). - While a flare's center is dragged out, Ctrl (Command on macOS) keeps the center's size and the drag sizes the halo; while its rings' end point is placed, Up/Down Arrow add and remove rings and ~ places them anew (`shape.flare`'s `ringSeed`) ([Draw and edit flares](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-and-edit-flares.html); `flare_arrows_change_the_rays_then_the_rings`, `flare_tilde_places_the_rings_anew`, `flare_ctrl_keeps_the_center_and_the_drag_sizes_the_halo`). - Flare ring placement accepts small `ringSeed` values, including 0, without concentrating the first ring at the center; the same seed and parameters reproduce the same positions. This seed mapping is VectorCraft's own (`flare_small_ring_seeds_spread_the_first_ring_along_the_path`, `flare_ring_seed_moves_only_the_rings`). + - `shape.flare` takes the rings' end point as `x2` and `y2` together: one given alone is an error that draws nothing and adds no undo step, and with neither, `pathLength` and `direction` place it. Saved flare settings that hold only one of them are not read as an editable flare. These are VectorCraft's own rules (`flare_requires_both_endpoint_coordinates`, `flare_omitted_or_null_endpoint_coordinates_use_path_fallback`, `flare_settings_with_a_lone_endpoint_coordinate_are_not_a_flare`). - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. - The Pattern Options panel's Name field and the name fields that a double-click opens in the Layers, Artboards and Asset Export panels take Shift+Enter (Shift+Return) the same way: it applies the name and keeps the field active with the name selected. From 873a5562a75579fd8b0fb3c80064e445f0b6bac6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:07:31 -0800 Subject: [PATCH 058/126] Gradient: a freeform line stays open over its object's stroke on a layer with Preview off The check for whether the pointer is still on the object hit the object's painted art with outline off, but the hit test turned outline back on for a layer with Preview off, so a move onto the stroke past the fill ended the line. A new HitOptions field, ignore_layer_preview, keeps the point hit tests from switching to outline for such layers, and the freeform check sets it. the_stroke_counts_as_the_object now runs with the layer's Preview on and off. --- crates/doc/src/hit.rs | 12 ++++++-- crates/doc/src/hit/tests.rs | 1 + crates/tools/src/context.rs | 1 + crates/tools/src/xform/freeform.rs | 44 ++++++++++++++++++------------ 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fcbe2f9db1..7c0de44cab 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -78,6 +78,9 @@ pub struct HitOptions { /// Off, the empty part of the frame (away from its edge and its lines of type) takes no /// clicks, so they reach the art behind (#7274). pub area_type_interior: bool, + /// The point hit tests ([`hit_test`], [`hit_test_visible`] and [`hit_test_visible_skipping`]) + /// hit the art on a layer whose Preview is off as painted, not in outline. + pub ignore_layer_preview: bool, } impl Default for HitOptions { @@ -90,6 +93,7 @@ impl Default for HitOptions { skip_guides: false, clip_outlines: false, area_type_interior: false, + ignore_layer_preview: false, scope: None, } } @@ -847,7 +851,7 @@ fn hit_test_skipping(doc: &Document, p: Point, opt: HitOptions, skip: &dyn Fn(No continue; } chain.push(layer.id); - let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; + let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt }; if let Some(h) = hit_children(layer, p, opt, &symbols, skip, &mut chain, editable_only) { return Some(finish(h)); } @@ -1211,7 +1215,9 @@ fn hit_children( chain.push(c.id); let hit = plain(i == 0 && clip.is_some(), || match &c.kind { // A sublayer whose Preview is off is clicked in outline, like an outline view. - NodeKind::Layer { preview: false, .. } => hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only), + NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => { + hit_children(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, editable_only) + } NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } => { hit_children(c, p, opt, symbols, skip, chain, editable_only) } @@ -1325,7 +1331,7 @@ fn art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, accept: & match &n.kind { NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } | NodeKind::Intertwine { children } => { // A layer with Preview off is clicked in outline, as [`hit_children`] clicks it. - let opt = HitOptions { outline: opt.outline || previews_off(n), ..opt }; + let opt = HitOptions { outline: opt.outline || !opt.ignore_layer_preview && previews_off(n), ..opt }; if n.clips() && let Some(clip) = children.first() { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index e94b2b8ba8..ad037931a0 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1463,6 +1463,7 @@ const SELECTING: HitOptions = HitOptions { skip_guides: false, clip_outlines: true, area_type_interior: false, + ignore_layer_preview: false, scope: None, }; diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 50553a87bc..1a37860179 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -451,6 +451,7 @@ impl ToolContext<'_> { skip_guides: !self.guides, clip_outlines: false, area_type_interior: false, + ignore_layer_preview: false, } } diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rs index 8a5a461a2b..3e3eef28b2 100644 --- a/crates/tools/src/xform/freeform.rs +++ b/crates/tools/src/xform/freeform.rs @@ -216,8 +216,9 @@ fn on_object(cx: &ToolContext, id: NodeId, p: Point) -> bool { keep.insert(c.id); }); keep.extend(ancestry); - // The art as painted, whatever the view and the path-only selection preferences. - let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ..cx.hit_options() }; + // The art as painted, whatever the view, the layers' Preview and the path-only selection + // preferences. + let opt = HitOptions { outline: false, path_only: false, type_path_only: false, ignore_layer_preview: true, ..cx.hit_options() }; hit_test_visible_skipping(cx.doc, p, opt, &|n| !keep.contains(&n)).is_some_and(|h| h.leaf == id || h.ancestry.contains(&id)) } @@ -530,23 +531,32 @@ mod tests { } /// The object's stroke is part of the object: moving onto it past the filled area keeps the - /// line open, and moving past the stroke ends it. + /// line open, and moving past the stroke ends it. The same holds on a layer with Preview off. #[test] fn the_stroke_counts_as_the_object() { - let (mut d, s) = doc(FreeformMode::Lines); - let id = s.objects[0]; - d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().width = 20.0; - let p = paint(); - let mut cx = cx(&d, &s, &p); - let mut t = GradientTool::default(); - let add = |x: f64, y: f64, line: bool| Action::Exec("paint.freeform.addPoint".into(), json!({"at": [x, y], "line": line, "stroke": false})); - assert_eq!(click(&mut t, &cx, 140.0, 150.0), vec![add(140.0, 150.0, false)]); - cx.freeform_point = Some(2); - t.pointer(&cx, &ev(PointerKind::Move, 206.0, 150.0)); - assert!(t.claims_key(&cx, ToolKey::Escape), "on the stroke the line stays open"); - assert_eq!(click(&mut t, &cx, 160.0, 150.0), vec![add(160.0, 150.0, true)]); - t.pointer(&cx, &ev(PointerKind::Move, 230.0, 150.0)); - assert!(!t.claims_key(&cx, ToolKey::Escape), "past the stroke the line has ended"); + for preview in [true, false] { + let (mut d, s) = doc(FreeformMode::Lines); + let id = s.objects[0]; + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().width = 20.0; + let l = d.layers[0].id; + if let vectorcraft_doc::NodeKind::Layer { preview: p, .. } = &mut d.node_mut(l).unwrap().kind { + *p = preview; + } + let p = paint(); + let mut cx = cx(&d, &s, &p); + let mut t = GradientTool::default(); + cx.freeform_point = Some(2); + // The line starts from the existing point. + assert!(click(&mut t, &cx, 150.0, 180.0).is_empty()); + t.pointer(&cx, &ev(PointerKind::Move, 206.0, 150.0)); + assert!(t.claims_key(&cx, ToolKey::Escape), "on the stroke the line stays open (Preview {preview})"); + if preview { + let add = Action::Exec("paint.freeform.addPoint".into(), json!({"at": [160.0, 150.0], "line": true, "stroke": false})); + assert_eq!(click(&mut t, &cx, 160.0, 150.0), vec![add]); + } + t.pointer(&cx, &ev(PointerKind::Move, 230.0, 150.0)); + assert!(!t.claims_key(&cx, ToolKey::Escape), "past the stroke the line has ended (Preview {preview})"); + } } /// In a clipping mask, the part of the object the mask hides is outside it: moving there ends From 0d1009fab020003e461891d8d95bdbaf691b5b1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:25:58 -0800 Subject: [PATCH 059/126] Dimension: a first Linear point goes back to its pick when its art is deleted The first point followed its moved art by overwriting the stored point, so when that art was then deleted the point stayed at the moved position instead of where it was picked. The tool now keeps the pick separately and falls back to it for the marker, the rubber band, Shift and the dimension. A first anchor whose path is deleted is dropped from the point, so the second click still places the dimension. --- crates/tools/src/dimension.rs | 44 +++++++++++++++++++++++++++++++---- docs/dimensions.md | 3 ++- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 46cc0694e8..a2a27e0510 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -81,6 +81,9 @@ pub struct DimensionTool { /// against the path whose preview-bounds corner it was picked on, or on the segment under it. /// When the art moves before the second click, the first point moves with it. first_link: Option, + /// Where the first Linear point was picked. The point goes back there when its anchor or + /// [`Self::first_link`] no longer resolves. + first_pick: Option, /// Whether the press under way began on an anchor a Linear click picks. press_on_anchor: bool, /// The second point clicked for the Linear dimension being placed, and where the pointer was @@ -676,12 +679,16 @@ impl DimensionTool { } /// Moves the first Linear point to where its link puts it in the document as it is now: on /// its anchor, or where [`Self::first_link`] holds it. A point whose link no longer resolves, - /// or that has none, stays where it was picked. + /// or that has none, stays where it was picked, and an anchor that no longer resolves is + /// dropped from it. fn follow_first(&mut self, cx: &ToolContext) { if let Some(now) = self.first_now(cx) - && let [(at, _)] = self.points.as_mut_slice() + && let [(at, reference)] = self.points.as_mut_slice() { *at = now; + if reference.as_ref().is_some_and(|r| r.position(cx.doc).is_none()) { + *reference = None; + } } } /// Where the first Linear point is in the document as it is now ([`Self::follow_first`]), @@ -692,7 +699,7 @@ impl DimensionTool { Some(r) => r.position(cx.doc), None => self.first_link.as_ref().and_then(|link| link.position(cx.doc)), }; - Some(now.unwrap_or(*at)) + Some(now.or(self.first_pick).unwrap_or(*at)) } fn target(&self, cx: &ToolContext, p: Point) -> Option { let edge = pick(cx, p)?; @@ -843,6 +850,7 @@ impl DimensionTool { self.corner = None; self.first_corner = None; self.first_link = None; + self.first_pick = None; self.points.clear(); self.lines.clear(); self.dragging = false; @@ -870,11 +878,13 @@ impl DimensionTool { if self.points.is_empty() { self.first_corner = corner; self.first_link = reference.is_none().then(|| own_link(cx, at, corner)).flatten(); + self.first_pick = Some(at); } self.points.push((at, reference)); if let [(a, ra), (b, rb)] = self.points.as_slice() { let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner), self.first_link.take()); self.first_corner = None; + self.first_pick = None; let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source); if d.resolve(cx.doc).is_ok() { self.second = Some((*b, p)); @@ -1907,10 +1917,36 @@ mod tests { assert!((pending.length - 101.0).abs() < 1e-9, "{}", pending.length); let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) }; assert!(free.position(&right).is_some_and(|q| near(q, Point::new(119.5, 99.5))), "{free:?}"); + // The same corner, the rectangle moved 20 points right with the pointer moving, then + // deleted: the first point goes back to where it was picked. + let mut gone = right.clone(); + gone.remove(id).expect("the rectangle"); + let (l, line) = (gone.layers[0].id, gone.alloc_id()); + let path = + vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 300.0), Point::new(400.0, 300.0)], false)); + gone.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line"); + let mut t = DimensionTool::default(); + click(&mut t, &base(&d), (101.0, 101.0), false); + let c = ToolContext { revision: (0, 1), ..base(&right) }; + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 219.0, 101.0)); + let c = ToolContext { revision: (0, 2), ..base(&gone) }; + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 300.0, 300.0)); + let shown = t.overlays(&c).into_iter().any(|o| matches!(o, Overlay::Anchor { p, filled: true, .. } if near(p, Point::new(99.5, 99.5)))); + assert!(shown, "the first point shows where it was picked once its rectangle is deleted"); + click(&mut t, &c, (300.0, 300.0), false); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(99.5, 99.5)), "{:?}", pending.a); + // An anchor, then its rectangle deleted: the dimension starts where the anchor was picked. + let mut t = DimensionTool::default(); + let unbounded = |doc| ToolContext { preview_bounds: false, ..base(doc) }; + click(&mut t, &unbounded(&d), (100.0, 100.0), false); + click(&mut t, &ToolContext { revision: (0, 2), ..unbounded(&gone) }, (300.0, 300.0), false); + let pending = t.pending.take().expect("both points were picked"); + assert!(near(pending.a, Point::new(100.0, 100.0)), "{:?}", pending.a); + let Some(DimensionSource::Points { a: None, .. }) = &pending.source else { panic!("{:?}", pending.source) }; // A point on the top segment, then the rectangle moved 20 points down. let down = moved((0.0, 20.0)); let mut t = DimensionTool::default(); - let unbounded = |doc| ToolContext { preview_bounds: false, ..base(doc) }; click(&mut t, &unbounded(&d), (150.0, 100.0), false); click(&mut t, &ToolContext { revision: (0, 1), ..unbounded(&down) }, (300.0, 300.0), false); let pending = t.pending.take().expect("both points were picked"); diff --git a/docs/dimensions.md b/docs/dimensions.md index 389154d0a8..bf6cf78653 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -34,7 +34,8 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers line shows the "path" label. These rules apply to the Linear points. A first point picked on an anchor, on a segment or on a corner of preview bounds moves with that art when the art moves before the second click: the rubber band, Shift and the dimension start from where the art puts - the point then. + the point then. When that art is deleted before the second click, the point goes back to where + it was picked. With Use Preview Bounds on (Preferences › General), a Linear point can land on a corner of the preview bounds of a path or compound path whose strokes or effects reach past its anchors. The [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) From 2adc433f5e09407d0c70468ed6ffeba149aec26a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:22:32 -0800 Subject: [PATCH 060/126] Plug-ins: the plug-ins folder can't block startup on a special file A folder load checked each .wasm path and then opened it with a blocking open. When a named pipe replaced the file between the two, the open held the load until something wrote to the pipe, and with it startup or a prefs.set of the folder. On Unix the file is now opened without waiting and without making a terminal the controlling terminal, and the opened file is checked again: anything that is not a regular file, or is over the module limit, is refused and listed in the folder report. A folder load still reads at most 1,000 .wasm files, the first by file name, and now holds only those paths while it lists the folder. The files past the first 1,000 were dropped and not reported; plugin.reload and plugin.list now return their count as leftOut. An error while the folder is listed fails the load, as an error opening the folder does, instead of dropping the entries after it. --- Cargo.lock | 1 + crates/engine/src/cmd/plugin.rs | 6 +- crates/plugins/Cargo.toml | 5 + crates/plugins/src/registry.rs | 209 ++++++++++++++++++++++++++++---- docs/plugins.md | 7 +- 5 files changed, 201 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 59e5fec9bb..ee8426623f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7057,6 +7057,7 @@ dependencies = [ "craft-image-codecs", "craft-vectorcraft-format", "log", + "rustix 1.1.6", "serde", "serde_json", "sha2", 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/plugins/Cargo.toml b/crates/plugins/Cargo.toml index 28b972d679..1f388b85b0 100644 --- a/crates/plugins/Cargo.toml +++ b/crates/plugins/Cargo.toml @@ -27,5 +27,10 @@ wasmi = { 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/docs/plugins.md b/docs/plugins.md index 09bb7c8dbd..5265255845 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 From 6db229c28458a9489024ae6ebce0b7c76bd44415 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:46:30 -0800 Subject: [PATCH 061/126] Pathfinder: an Intersect effect with a group that has no area at its precision draws nothing A group operand whose members have no area left at the effect's precision was left out of the operation, so Intersect returned the other operand as it was. Intersect now draws nothing in that case, as do Minus Back when that group is the front operand and Subtract when it is the back operand. Add, Exclude and Subtract with the group in front still leave it out. --- crates/effects/src/group.rs | 20 +++++++++++++- crates/effects/src/group/tests.rs | 43 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index aeffaacfb6..ed34fa5426 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -644,13 +644,19 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option = vec![]; let mut shapes: Vec = vec![]; + // Keys of the group operands whose art has no area left at the precision. + let mut collapsed: Vec = vec![]; for mut lv in all { if shape_mode && lv.len() > 1 { let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(geometry).collect(); let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect(); let key = sources.len() as u64; if let Some(top) = lv.pop() { - shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key)); + let united = po::unite_all_with(&refs, options.precision); + if united.is_empty() && !parts.is_empty() { + collapsed.push(key); + } + shapes.push(po::Shape::new(united, FillRule::NonZero, key)); sources.push(top); } } else { @@ -662,6 +668,18 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option shapes.iter().any(is_collapsed), + PathfinderOp::MinusFront => shapes.first().is_some_and(is_collapsed), + PathfinderOp::MinusBack => shapes.last().is_some_and(is_collapsed), + _ => false, + }; + if nothing_left { + return Some(vec![]); + } shapes.retain(|s| !s.path.is_empty() && s.path.subpaths.iter().all(|sp| sp.anchors.iter().all(|a| a.p.x.is_finite() && a.p.y.is_finite()))); if shapes.is_empty() { return Some(vec![]); diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 1c62508347..94c71e936b 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -196,6 +196,49 @@ fn shape_modes_follow_the_pathfinder_panel() { assert_eq!(div.len(), 3); } +/// An Intersect effect draws nothing when a group member's art has no area left at the effect's +/// precision, and so do Minus Back when that group is in front and Subtract when it is at the +/// back. Add, and Subtract with the group in front, leave such a member out. +#[test] +fn intersect_with_a_group_that_collapses_at_its_precision_draws_nothing() { + let thin_pair = |width: f64| { + let bar = |id: u64, x: f64| { + let fill = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(x, 10.0, x + width, 30.0)), fill)) + }; + Node::group(NodeId(5), vec![bar(3, 10.0), bar(4, 50.0)]) + }; + let with_precision = |front: Node, effect: &str| { + let mut g = square_and(Some(front), effect); + g.appearance.effects[0].params = serde_json::json!({"precision": 1.0}); + g + }; + let int = results(&with_precision(thin_pair(0.5), "pathfinder.intersect")); + assert!(int.is_empty(), "{int:#?}"); + // Bars wider than the precision keep their area. + let int = results(&with_precision(thin_pair(2.0), "pathfinder.intersect")); + let total: f64 = int.iter().map(|n| area(n)).sum(); + assert!((total - 80.0).abs() < 1.0, "{total}: {int:#?}"); + // Add keeps the square alone. + let add = results(&with_precision(thin_pair(0.5), "pathfinder.add")); + assert_eq!(add.len(), 1); + assert!((area(&add[0]) - 10_000.0).abs() < 1.0, "{add:#?}"); + // Minus Back cuts the square from the empty group in front, and Subtract cuts nothing from + // the square. + let minus_back = results(&with_precision(thin_pair(0.5), "pathfinder.minusBack")); + assert!(minus_back.is_empty(), "{minus_back:#?}"); + let subtract = results(&with_precision(thin_pair(0.5), "pathfinder.subtract")); + assert_eq!(subtract.len(), 1); + assert!((area(&subtract[0]) - 10_000.0).abs() < 1.0, "{subtract:#?}"); + // With the group at the back, Subtract cuts the square from it and leaves nothing. + let mut back = with_precision(thin_pair(0.5), "pathfinder.subtract"); + if let NodeKind::Group { children, .. } = &mut back.kind { + children.reverse(); + } + let subtract = results(&back); + assert!(subtract.is_empty(), "{subtract:#?}"); +} + /// Divide and Outline draw no piece of a member without fill or stroke, the same as when such /// pieces are left out. #[test] From 417ed9443192ea08878b3e583dfad2dc4504c2d1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 17:22:26 -0800 Subject: [PATCH 062/126] Script checker: setting a File's length, hidden or readonly counts as a file write Setting a File object's length truncates or pads the file, and setting readonly or hidden changes it, but script.check reported no outside category for those assignments. It now reports file.write and filesWritten for them: plain and compound assignment, ++ and -- before or after, and the property name as a string literal in brackets. A new integration test lists every global and member the script host adds to the JavaScript engine (the own properties of the global object, of each object or function it holds and of each function's prototype, compared with a plain engine) and fails when one has no row. Each name that reaches outside the document has a probe script, and the test checks that script.check gives it the expected outside id. vc is listed as not checked: script.check reads scripts written for the reference app's scripting, and what vc.run does depends on the command. The test also checks that the checker lists every preprocessor directive the host reads, through the new DirectiveName::ALL. File object properties: https://extendscript.docsforadobe.dev/file-system-access/file-object/ --- crates/engine/tests/it/main.rs | 1 + .../tests/it/script_host_vs_scriptcheck.rs | 167 ++++++++++++++++++ crates/js/src/token.rs | 20 ++- crates/scriptcheck/src/analyze.rs | 4 + crates/scriptcheck/src/analyze/features.rs | 55 +++++- crates/scriptcheck/src/catalog.rs | 3 + crates/scriptcheck/src/tests.rs | 34 ++++ docs/mcp.md | 8 +- 8 files changed, 273 insertions(+), 19 deletions(-) create mode 100644 crates/engine/tests/it/script_host_vs_scriptcheck.rs diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 836190aca6..9a4644575d 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -32,6 +32,7 @@ mod pen_rubber_band; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; +mod script_host_vs_scriptcheck; mod selection_commands; mod stroke_visibility; mod text_stroke_scale; diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs new file mode 100644 index 0000000000..aaf3f8acda --- /dev/null +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -0,0 +1,167 @@ +//! Every global and member the script host (`script.run`) adds to the JavaScript engine is in one of +//! the tables below, and each name that reaches outside the document has the `outside` id +//! `script.check` (`vectorcraft-scriptcheck`) gives it. The names are read from a run: the own +//! properties of the global object, of each object or function it holds and of each function's +//! `prototype`, with a setter listed again as `name=`. The names a plain `vectorcraft_js::Realm` also +//! has are the language's, which reach files and other apps only through the host; `eval` and +//! `Function` still have rows, since they run code the checker can't read. A name the host adds +//! without a row fails the test. + +use std::collections::BTreeSet; + +use serde_json::json; +use vectorcraft_engine::Session; +use vectorcraft_js::{DirectiveName, JsValue, Realm}; +use vectorcraft_scriptcheck::{Limits, check}; + +/// The names that reach outside the document: each with a script that uses it and the `outside` id +/// the checker gives that script. +const OUTSIDE: &[(&str, &str, &str)] = &[ + ("eval", "eval(s);", "unseenCode"), + ("Function", "var g = new Function(s);", "unseenCode"), + ("$.evalFile", "$.evalFile(p);", "unseenCode"), + ("$.getenv", "var h = $.getenv(n);", "environment"), + ("$.setenv", "$.setenv(n, v);", "environment"), + ("File.prototype.open", "var f = new File(p); f.open('w');", "filesWritten"), + ("File.prototype.write", "var f = new File(p); f.write(s);", "filesWritten"), + ("File.prototype.writeln", "var f = new File(p); f.writeln(s);", "filesWritten"), + ("File.prototype.copy", "var f = new File(p); f.copy(q);", "filesWritten"), + ("File.prototype.createAlias", "var f = new File(p); f.createAlias(q);", "filesWritten"), + ("File.prototype.remove", "var f = new File(p); f.remove();", "filesWritten"), + ("File.prototype.rename", "var f = new File(p); f.rename(q);", "filesWritten"), + ("File.prototype.length=", "var f = new File(p); f.length = 0;", "filesWritten"), + ("File.prototype.hidden=", "var f = new File(p); f.hidden = true;", "filesWritten"), + ("File.prototype.readonly=", "var f = new File(p); f.readonly = true;", "filesWritten"), + ("File.prototype.execute", "var f = new File(p); f.execute();", "filesOpened"), + ("Folder.prototype.create", "var d = new Folder(p); d.create();", "filesWritten"), + ("Folder.prototype.remove", "var d = new Folder(p); d.remove();", "filesWritten"), + ("Folder.prototype.rename", "var d = new Folder(p); d.rename(q);", "filesWritten"), + ("Folder.prototype.execute", "var d = new Folder(p); d.execute();", "filesOpened"), +]; + +/// The names the host adds that stay inside the document and the run, by the object that has them. +/// Reading a file or a folder, a file dialog and a message to the person do not change anything +/// outside it. +const INSIDE: &[(&str, &str)] = &[ + ("", "$ File Folder alert confirm localize prompt toSource"), + ("Object.prototype.", "toSource"), + ("localize.", "length"), + ("toSource.", "length"), + ( + "$.", + "about appEncoding appEncoding= bp build buildDate colorPicker decimalPoint engineName error fileName flags \ + flags= gc global hiresTimer includePath level line locale locale= localize localize= memCache memCache= os screens \ + sleep stack strict version write writeln", + ), + ("File.", "decode encode fs isEncodingAvailable openDialog saveDialog length prototype"), + ( + "File.prototype.", + "absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \ + exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= modified name openDlg parent path read \ + readch readln readonly relativeURI resolve saveDlg seek tell toString type", + ), + ( + "Folder.", + "appData appPackage commonFiles current current= decode desktop encode fs isEncodingAvailable length myDocuments \ + prototype selectDialog startup system temp trash userData", + ), + ( + "Folder.prototype.", + "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ + getRelativeURI modified name parent path relativeURI resolve selectDlg toString", + ), +]; + +/// The name the checker does not read, which also stands for its members: `script.check` reads +/// scripts written for the reference app, `vc` is VectorCraft's own API, and what `vc.run` does +/// depends on the command it runs. +const NOT_CHECKED: &str = "vc"; + +/// An expression whose value is the list of names, one to a line. +const LIST: &str = r#"(function () { + var out = []; + function add(o, prefix) { + var own = Object.getOwnPropertyNames(o); + for (var i = 0; i < own.length; i++) { + out.push(prefix + own[i]); + var d = Object.getOwnPropertyDescriptor(o, own[i]); + if (d && d.set) out.push(prefix + own[i] + "="); + } + } + var g = (function () { return this; })(); + var globals = Object.getOwnPropertyNames(g); + add(g, ""); + for (var i = 0; i < globals.length; i++) { + var v = g[globals[i]]; + if (v !== null && (typeof v == "object" || typeof v == "function")) { + add(v, globals[i] + "."); + if (typeof v == "function" && v.prototype !== null && typeof v.prototype == "object") add(v.prototype, globals[i] + ".prototype."); + } + } + return out.join("\n"); +})()"#; + +/// The names a script run by the host has. +fn host_names() -> BTreeSet { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": format!("vc.log({LIST});"), "name": "list.js"})).unwrap(); + let text = r["log"][0].as_str().unwrap_or_else(|| panic!("no list in {r}")); + text.lines().map(str::to_string).collect() +} + +/// The names a plain JavaScript engine has. +fn language_names() -> BTreeSet { + match Realm::new().run(LIST) { + Ok(JsValue::String(text)) => text.lines().map(str::to_string).collect(), + other => panic!("no list: {other:?}"), + } +} + +fn table_names() -> BTreeSet { + let inside = INSIDE.iter().flat_map(|(prefix, names)| names.split_whitespace().map(move |n| format!("{prefix}{n}"))); + OUTSIDE.iter().map(|(n, ..)| n.to_string()).chain(inside).chain([NOT_CHECKED.to_string()]).collect() +} + +#[test] +fn every_name_the_host_adds_has_a_row() { + let host = host_names(); + let language = language_names(); + let table = table_names(); + let not_checked = |n: &&String| n.starts_with(&format!("{NOT_CHECKED}.")); + let missing: Vec<_> = host.difference(&language).filter(|n| !table.contains(*n) && !not_checked(n)).collect(); + assert!(missing.is_empty(), "the host adds these names, which no table here lists: {missing:?}"); + let gone: Vec<_> = table.difference(&host).collect(); + assert!(gone.is_empty(), "the tables list these names, which a script run by the host does not have: {gone:?}"); +} + +#[test] +fn every_name_that_reaches_outside_has_its_checker_id() { + for (name, script, id) in OUTSIDE { + let r = check("probe.jsx", script.as_bytes(), None, &Limits::default()); + let ids: Vec<_> = r.outside.iter().map(|o| o.id).collect(); + assert!(ids.contains(id), "{name}: the checker gives {ids:?} for {script:?}, not {id}"); + } +} + +/// A line with the directive `d`. The match has no catch-all, so a new directive needs a row, and +/// [`DirectiveName::from_name`] reads only the directives in [`DirectiveName::ALL`]. +fn directive_line(d: DirectiveName) -> &'static str { + match d { + DirectiveName::Include => "#include \"lib.jsxinc\"", + DirectiveName::IncludePath => "#includepath \"lib\"", + DirectiveName::Script => "#script Tidy", + DirectiveName::Strict => "#strict on", + DirectiveName::Target => "#target vectorcraft", + DirectiveName::TargetEngine => "#targetengine session", + } +} + +#[test] +fn the_checker_lists_every_directive_the_host_reads() { + for d in DirectiveName::ALL { + let line = directive_line(d); + let r = check("probe.jsx", format!("{line}\nvar a = 1;\n").as_bytes(), None, &Limits::default()); + let listed: Vec<_> = r.directives.iter().map(|d| d.name.to_string()).collect(); + assert_eq!(listed, [d.as_str()], "{line}"); + } +} diff --git a/crates/js/src/token.rs b/crates/js/src/token.rs index 7998822e53..304ea0e0ab 100644 --- a/crates/js/src/token.rs +++ b/crates/js/src/token.rs @@ -288,17 +288,19 @@ pub enum DirectiveName { } impl DirectiveName { + /// Every directive a preprocessor line can name. + pub const ALL: [DirectiveName; 6] = [ + DirectiveName::Include, + DirectiveName::IncludePath, + DirectiveName::Script, + DirectiveName::Strict, + DirectiveName::Target, + DirectiveName::TargetEngine, + ]; + /// The directive named `name`, compared without case. pub fn from_name(name: &str) -> Option { - const NAMES: [(&str, DirectiveName); 6] = [ - ("include", DirectiveName::Include), - ("includepath", DirectiveName::IncludePath), - ("script", DirectiveName::Script), - ("strict", DirectiveName::Strict), - ("target", DirectiveName::Target), - ("targetengine", DirectiveName::TargetEngine), - ]; - NAMES.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, d)| *d) + DirectiveName::ALL.into_iter().find(|d| d.as_str().eq_ignore_ascii_case(name)) } pub fn as_str(self) -> &'static str { diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b8f887ff37..b7c70345d0 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -239,6 +239,10 @@ enum Pending<'s> { MenuString(Option, &'s str), /// `.open(`: a string literal with the open mode may follow. Open(Option), + /// A File object's `length`, `hidden` or `readonly` (`f.length`, `f['length']`): an assignment + /// or an update (`++`, `--`) that sets it may follow. With `true`, a prefix update came before + /// the receiver, and it sets the property unless a member or a call follows it. + Setter(Option, bool), /// A platform name where a property key or a label may stand (first, or after `{`, `,`, `;` or /// `}`): it is a key or a label when `:` follows. Name(&'s str, Option), diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index b5dd2299eb..7bf8c9d203 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -1,6 +1,6 @@ //! The platform features, menu commands and later syntax the analysis recognises. -use super::{Analyzer, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word}; +use super::{Analyzer, COMPOUND, FeatureId, NEWER, OutsideId, Pending, Sig, T, catalog, is, member_mark, newer_number, report, unquote, word}; /// A global name of the platform the report looks for (`$`, `File`, `Socket`, `alert`, `eval`…). pub(super) fn platform_name(n: &str) -> bool { @@ -72,6 +72,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.open_mode(&unquote(t.text, 2), l); } } + Pending::Setter(l, prefix) => { + let sets = if prefix { + !t.is(".") && !t.is("[") && !t.is("(") + } else { + // An update operator after a line break belongs to the next line's operand. + t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || (matches!(t.text, "++" | "--") && !t.nl)) + }; + if sets { + self.file_setter(l); + } + } } match t.kind { T::Ident => self.name(t, line), @@ -113,7 +124,29 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { match pending { Pending::Window(l) | Pending::WindowType(l) => self.acc.feature(FeatureId::ScriptuiWindow, l), Pending::Menu(l) | Pending::MenuString(l, _) => self.menu(None, l), - Pending::Open(_) | Pending::Name(..) | Pending::None => {} + Pending::Setter(l, true) => self.file_setter(l), + Pending::Open(_) | Pending::Setter(_, false) | Pending::Name(..) | Pending::None => {} + } + } + + /// A File object's `length`, `hidden` or `readonly` set at `line`: the file changes. + fn file_setter(&mut self, line: Option) { + self.acc.feature(FeatureId::FileWrite, line); + self.acc.outside(OutsideId::FilesWritten, line, None); + } + + /// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before` + /// coming before the receiver: when it is a File object's setter, the next token says whether it + /// is set ([`Pending::Setter`]). An update operator in `before` is a prefix (`++f.length`) when + /// the receiver is on its line, or when it starts a line or comes where an expression may start; + /// otherwise it ends the operand before it (`i++` and a line break, then `f.length`). + fn setter(&mut self, name: &str, receiver: Option>, before: Option>, line: Option) { + if catalog::FILE_SETTERS.contains(&name) && self.file_receiver(receiver, before) { + // Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the + // parentheses. + let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident)); + let prefix = update.is_some_and(|b| b.nl || b.expr || receiver.is_some_and(|r| !r.nl)); + self.pending = Pending::Setter(line, prefix); } } @@ -170,6 +203,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if n == catalog::REFLECT { self.acc.feature(FeatureId::Reflection, line); } + self.setter(n, h1, h2, line); return; } if member_mark(h0) { @@ -231,6 +265,11 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn punct(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, h3] = self.h; match t.text { + // `f['length']`: a File object's setter may follow. + "]" if is(h1, "[") && h0.is_some_and(|s| s.kind == T::Str) => { + let name = h0.map(|s| unquote(s.text, 16)).unwrap_or_default(); + self.setter(&name, h2, h3, line); + } "(" => self.call(line), // `Name.prototype["+"] = …` defines an operator. "=" => { @@ -251,10 +290,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let Some(callee) = h0.filter(|s| s.kind == T::Ident) else { return }; let n = callee.text; if is(h1, ".") { - // The receiver is a variable holding a File or Folder object (not a property of the same - // name), or a File or Folder object made in place or held in grouping parentheses - // ([`Sig::file`]). - let file = h2.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(h3) && self.files.contains(r.text))); + let file = self.file_receiver(h2, h3); if n == catalog::MENU_COMMAND { self.pending = Pending::Menu(line); } else if n == catalog::OPEN && file { @@ -288,6 +324,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// Whether `receiver`, which `before` comes before, is a variable holding a File or Folder object + /// (not a property of the same name), or a File or Folder object made in place or held in + /// grouping parentheses ([`Sig::file`]). + fn file_receiver(&self, receiver: Option>, before: Option>) -> bool { + receiver.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(before) && self.files.contains(r.text))) + } + fn string(&mut self, t: &Sig<'s>, line: Option) { let [h0, h1, h2, _] = self.h; if t.text.contains(catalog::ACTION_TEXT) { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 8954736d25..6f25fe6df3 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -32,6 +32,9 @@ pub(crate) const FOLDER: &str = "Folder"; pub(crate) const FILE_READS: &[&str] = &["read", "readch", "readln"]; pub(crate) const FOLDER_READS: &[&str] = &["getFiles"]; pub(crate) const FILE_WRITES: &[&str] = &["write", "writeln", "remove", "rename", "copy", "createAlias", "create"]; +/// The properties of a File object whose setting changes the file: its length, and its hidden and +/// read-only flags. +pub(crate) const FILE_SETTERS: &[&str] = &["length", "hidden", "readonly"]; pub(crate) const FILE_DIALOGS: &[&str] = &["openDialog", "saveDialog"]; pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"]; pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"]; diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 853f212c11..cf71cefc0f 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -530,6 +530,40 @@ fn the_scripts_own_platform_names_are_not_the_platforms() { assert_eq!(r.outside.iter().map(|o| o.id).collect::>(), ["filesWritten"]); } +/// Setting a File object's length, hidden or read-only flag changes the file; reading them, comparing +/// them and setting them on another object does not. +#[test] +fn setting_a_files_length_or_flags_writes_it() { + let r = report(concat!( + "var f = new File(p);\n", + "f.length = 0;\n", + "f.readonly = true;\n", + "f.hidden |= 1;\n", + "f.length++;\n", + "new File(q).length = 4;\n", + "if (x) --f.length;\n", + "f['readonly'] = false;\n", + "++\n", + "f.length;\n", + "var k = ++\n", + "f['length'];\n", + "++f.length.x; var z = new File(i++).length;\n", + "var n = f.length;\n", + "if (f.readonly == true) {}\n", + "o.length = 0;\n", + "o.f.length = 0;\n", + "var s = [1]; s.length = 0;\n", + "var m = f['length'];\n", + "i++\n", + "f.length;\n", + "f.length\n", + "++i;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2, 3, 4, 5, 6, 7, 8, 10, 12][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4, 5, 6, 7, 8, 10, 12][..])); +} + #[test] fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() { let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n"); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..25ac2afa31 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2556,10 +2556,10 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, - `menuCommands.strings` lists the string literals the script passes to `executeMenuCommand` (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. -- `outside` lists what the script does outside the document: `filesWritten` (with the open modes used), - `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), - `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and - `preferences` (the reference app's preferences changed). +- `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a + File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, + `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, + `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, template literals and XML literals that aren't closed, brackets that don't match, syntax newer than ES3 and unknown directives) and notes on its text (bytes that aren't valid UTF-8, mixed line endings, and nesting deeper From b2e77841607351cfbe93aeea9342baa982789053 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:05:54 -0800 Subject: [PATCH 063/126] Docs: progress line for the script checker's File setters and host test docs/target-app-parity.md gets a line for the file.write report on a File object's length, hidden and readonly and for the test that lists every name the script host adds, with the tests that cover them. The test's comment on vc no longer names another app. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 5 ++--- docs/target-app-parity.md | 1 + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index aaf3f8acda..660433b800 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -72,9 +72,8 @@ const INSIDE: &[(&str, &str)] = &[ ), ]; -/// The name the checker does not read, which also stands for its members: `script.check` reads -/// scripts written for the reference app, `vc` is VectorCraft's own API, and what `vc.run` does -/// depends on the command it runs. +/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's +/// own API, and what `vc.run` does depends on the command it runs. const NOT_CHECKED: &str = "vc"; /// An expression whose value is the list of names, one to a line. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..9933a858b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1071,6 +1071,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. From ce2fd222674b6c81783fe78819d3873f325c3702 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:15:06 -0800 Subject: [PATCH 064/126] Path Precision Tools: the Tangent Circle Tool works out its circle again after a canceled live edit A live edit changes the document without an undo step, so the tool was not told about it. Circles found while a preview moved the second segment stayed cached under the same segment key, and a click after the preview was canceled drew the cached circle instead of one touching the segment where it is again. A first segment picked during a preview kept its old shape the same way. The cache key now holds the shapes of the first segment and of the segments a circle may touch, so moving along an unchanged segment still reuses the search. The first segment is forgotten when its shape no longer matches the document, and a press on the second segment follows the segments as they are at the release; a pressed segment that is gone leaves nothing to touch. --- crates/tools/src/addons/tangent_circle.rs | 125 +++++++++++++++++++--- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 3 files changed, 114 insertions(+), 19 deletions(-) diff --git a/crates/tools/src/addons/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs index a8d24d8853..1ab964988e 100644 --- a/crates/tools/src/addons/tangent_circle.rs +++ b/crates/tools/src/addons/tangent_circle.rs @@ -12,8 +12,10 @@ //! three points can draw, a note says so. The circle is a new ellipse with the current paint, drawn //! with `shape.circleThroughPoints` in one undo step, so Align New Objects to Pixel Grid leaves it //! in place; the first segment stays picked until the circle is drawn, also when drawing fails or the -//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, or another -//! document forgets the first segment. +//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, another +//! document, or a change to the first segment that leaves no undo step (a live preview, or one that +//! was canceled) forgets the first segment. The circles are looked for again whenever either +//! segment's shape differs from the one they were found on. use kurbo::{CubicBez, Shape}; use serde_json::{Value, json}; @@ -55,7 +57,8 @@ struct Pick { /// A press on the second segment, kept while the button is down. #[derive(Clone, Debug, PartialEq)] struct Press { - /// The segments a circle may touch. + /// The segment pressed on, and the segments a circle may touch. + pick: Pick, second: Vec, /// Where the press was. at: Point, @@ -78,12 +81,13 @@ pub struct TangentCircleTool { found: Option, looked: bool, pointer: Point, - /// The circles the last second segment gave (its path, subpath and segment, and the radius - /// asked for), so that moving along it only picks among them. + /// The circles the last second segment gave (its path, subpath and segment, the radius asked + /// for, and the shapes of the first segment and of the segments a circle may touch), so that + /// moving along it only picks among them. cache: Option<(CacheKey, Vec)>, } -type CacheKey = (NodeId, usize, usize, Option); +type CacheKey = (NodeId, usize, usize, Option, CubicBez, Vec); impl Default for TangentCircleTool { fn default() -> Self { @@ -102,6 +106,17 @@ fn pick_at(cx: &ToolContext, p: Point) -> Option { Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve }) } +/// The document's segment at `pick` as it is now: none when its path, subpath or segment is gone. +fn segment_now(cx: &ToolContext, pick: &Pick) -> Option { + let sp = cx.doc.node(pick.id)?.path_data()?.subpaths.get(pick.subpath)?; + (pick.segment < sp.segment_count()).then(|| sp.segment(pick.segment)) +} + +/// Whether the document's segment at `pick` still has the shape it had when it was picked. +fn unchanged(cx: &ToolContext, pick: &Pick) -> bool { + segment_now(cx, pick) == Some(pick.curve) +} + /// The segments a circle may touch when `second` is picked: it and the segments on either side of /// it, without `first`. None when `second` is the first segment again. fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { @@ -192,24 +207,35 @@ impl TangentCircleTool { } /// The circles `pick` gives as the second segment, with Shift's `radius`: worked out again only - /// when the segment or the radius changes. + /// when the segment, the radius or the shape of either segment changes. fn circles_on(&mut self, cx: &ToolContext, pick: &Pick, radius: Option) -> Vec { - let key = (pick.id, pick.subpath, pick.segment, radius.map(f64::to_bits)); + let Some(first) = &self.first else { return vec![] }; + let second = second_set(cx, first, pick); + let key = (pick.id, pick.subpath, pick.segment, radius.map(f64::to_bits), first.curve, second); if let Some((k, found)) = &self.cache && *k == key { return found.clone(); } - let Some(first) = &self.first else { return vec![] }; - let found = circles(first, &second_set(cx, first, pick), radius); + let found = circles(first, &key.5, radius); self.cache = Some((key, found.clone())); found } + /// Forget the first segment when the document's no longer has the shape it was picked with: a + /// live preview, or one that was canceled, changes it without an undo step, so the tool is not + /// told ([`Tool::history_moved`]). + fn forget_if_changed(&mut self, cx: &ToolContext) { + if self.first.as_ref().is_some_and(|f| !unchanged(cx, f)) { + self.forget(); + } + } + /// Look for the circle the pointer at `p` would give over `hover`, before any press. fn look(&mut self, cx: &ToolContext, p: Point, mods: Mods) { self.found = None; self.looked = false; + self.forget_if_changed(cx); let Some(hover) = self.hover.clone().filter(|_| self.first.is_some()) else { return }; let found = self.circles_on(cx, &hover, mods.shift.then_some(self.radius)); self.found = nearest_to(found, p, cx.tol(DRAW_PX)); @@ -219,15 +245,25 @@ impl TangentCircleTool { /// The pointer at `ev` during a press on the second segment: once it is far enough from the /// press, the radius follows it (Cmd/Ctrl: a tenth of its movement; Shift: round steps). fn drag_to(&mut self, cx: &ToolContext, ev: &PointerEvent) { + if self.press.is_none() { + return; + } + // A change without an undo step since the press: a changed first segment is forgotten (the + // press then draws nothing), and the circle follows the segments it may touch as they are now. + self.forget_if_changed(cx); let radius = self.radius; let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return }; + // A pressed segment that is gone leaves nothing to touch. + let second = if segment_now(cx, &press.pick).is_some() { second_set(cx, first, &press.pick) } else { vec![] }; + let moved = second != press.second; + press.second = second; let reach = ev.pos.distance(press.at); let gear = if ev.mods.cmd { SLOW } else { 1.0 }; let r = match press.radius { None if reach <= cx.tol(DRAG_PX) => { - // Shift pressed or let go before the drag starts: the click's circle, with or - // without the tool's radius. - if ev.mods.shift != press.shift { + // Shift pressed or let go before the drag starts, or the segments changed: the + // click's circle, with or without the tool's radius. + if moved || ev.mods.shift != press.shift { press.shift = ev.mods.shift; let found = circles(first, &press.second, press.shift.then_some(radius)); self.found = nearest_to(found, press.at, cx.tol(DRAW_PX)); @@ -273,6 +309,7 @@ impl Tool for TangentCircleTool { } PointerKind::Down => { let Some(pick) = pick_at(cx, ev.pos) else { return vec![] }; + self.forget_if_changed(cx); let Some(first) = self.first.clone() else { self.first = Some(pick); self.picking = true; @@ -286,7 +323,7 @@ impl Tool for TangentCircleTool { self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX)); self.looked = true; self.hover = None; - self.press = Some(Press { second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); + self.press = Some(Press { pick, second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); vec![] } PointerKind::Drag => { @@ -431,10 +468,14 @@ mod tests { /// Two open lines, (100, 100)–(300, 100) and (100, 140)–(300, 140), and an L from (100, 300) /// over to (300, 300) and down to (300, 400). fn doc() -> Document { + doc_at(100.0, 140.0) + } + + /// [`doc`] with the two open lines at heights `a` and `b`, with the same ids. + fn doc_at(a: f64, b: f64) -> Document { let mut d = Document::new(500.0, 500.0); let l = d.layers[0].id; - let lines: [&[(f64, f64)]; 3] = - [&[(100.0, 100.0), (300.0, 100.0)], &[(100.0, 140.0), (300.0, 140.0)], &[(100.0, 300.0), (300.0, 300.0), (300.0, 400.0)]]; + let lines: [&[(f64, f64)]; 3] = [&[(100.0, a), (300.0, a)], &[(100.0, b), (300.0, b)], &[(100.0, 300.0), (300.0, 300.0), (300.0, 400.0)]]; for pts in lines { let id = d.alloc_id(); let pts: Vec = pts.iter().map(|(x, y)| Point::new(*x, *y)).collect(); @@ -676,6 +717,58 @@ mod tests { assert!(t.first.is_some()); } + #[test] + fn a_change_without_an_undo_step_is_not_drawn_from_the_old_shapes() { + let (sel, p) = (Selection::default(), paint()); + let (d, previewed, first_previewed) = (doc(), doc_at(100.0, 180.0), doc_at(80.0, 140.0)); + let (cx, during, first_during) = (cx(&d, &sel, &p), cx(&previewed, &sel, &p), cx(&first_previewed, &sel, &p)); + let mut t = TangentCircleTool::default(); + // A live preview moves the second line down to 180, and the pointer over it shows a 40 pt + // circle. The preview is canceled, which leaves no undo step: the click draws the 20 pt circle + // touching the line where it is again, not the one found during the preview. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&during, &ev(PointerKind::Move, 200.0, 179.0)); + assert!(t.overlays(&during).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 40.00")))); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + // The same for a press made during the preview and released after it was canceled. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&during, &ev(PointerKind::Down, 200.0, 179.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 179.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + // A first segment picked during a preview that moved it, canceled since: forgotten, with no + // circle shown from where it was. + t.pointer(&first_during, &ev(PointerKind::Down, 150.0, 81.0)); + t.pointer(&first_during, &ev(PointerKind::Up, 150.0, 81.0)); + assert!(t.first.is_some()); + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0)); + assert!(t.first.is_none() && t.found.is_none() && !t.looked); + // A press on a first segment that the preview changed since the press draws nothing. + t.pointer(&first_during, &ev(PointerKind::Down, 150.0, 81.0)); + t.pointer(&first_during, &ev(PointerKind::Up, 150.0, 81.0)); + t.pointer(&first_during, &ev(PointerKind::Down, 200.0, 139.0)); + assert!(t.busy()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)).is_empty()); + assert!(t.first.is_none() && !t.busy()); + // A press on the L's second segment, which a preview then removes: nothing to touch, so the + // release draws no circle against the segment left beside it. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + let l = t.press.as_ref().map(|p| (p.pick.id, p.pick.segment)); + assert!(matches!(l, Some((_, 1))), "{l:?}"); + let mut cut = doc(); + if let Some(path) = l.and_then(|(id, _)| cut.node_mut(id)).and_then(|n| n.path_data_mut()) { + path.subpaths[0] = SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(300.0, 300.0)], false); + } + let cut_cx = crate::testutil::cx(&cut, &sel, &p); + assert!(t.pointer(&cut_cx, &ev(PointerKind::Up, 300.0, 350.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some(), "the first segment stays for another try"); + } + #[test] fn a_circle_the_three_points_cannot_draw_keeps_the_first_segment() { // A circle the geometry found, moved to (x, 0) and given radius `r`. diff --git a/docs/mcp.md b/docs/mcp.md index 3cb8d1d239..fe69653330 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14500,8 +14500,10 @@ Tools: 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 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, or another document forgets - the first segment. + 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 + segment. The circle is looked for again whenever either segment no longer has the shape it was found on, so a + canceled preview does not leave a circle worked out on the previewed paths. Option (`tool.setOption`, or a double-click on the tool): `radius` (pt, 0.01 to 1000000, 36). `tool.setOption` gives an error for a value outside that range or one that is not a number, and for any other option. - **Trim at Crossings Tool** (`trimAtCrossings`): removes stretches of paths between the places where they are crossed, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e8483f80a..eeb3a0c818 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2991,7 +2991,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. 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 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, 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. ## Path Precision Tools add-on: Trim at Crossings (2026-11-13) From f4b114ae781a950939c3471701e83985bd49108e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:16:06 -0800 Subject: [PATCH 065/126] Path Precision Tools: check each place along the first segment once When the same segment appears more than once among the second segments, its roots were found once per copy, and each copy's places were checked against every second segment. The sorted places now drop exact repeats before they are checked. Places that differ, however close, are all kept, so the circles found do not change. --- .../pathops/src/addons/pathtools/tangent_circle/on_segments.rs | 2 ++ 1 file changed, 2 insertions(+) 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 f5d4df2647..82d2f2c7a0 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs @@ -265,7 +265,9 @@ pub fn circles_of_radius(first: CubicBez, second: &[CubicBez], radius: f64) -> V 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) From 318d1ed6e250eb78588a4d3cdf5cc4f70c70a1e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:27:36 -0800 Subject: [PATCH 066/126] Selection: an Alt-drag copy in Draw Behind goes directly below its original In Draw Behind, an Alt-drag of whole objects with the Selection or Direct Selection tool now puts each copy directly below its own original, in the original's group or layer, and selects the copies, as the drawing modes help page lists duplicating by Alt-drag among the actions Draw Behind applies to (https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html). The copy of a clip group's or clipping layer's clipping path goes directly above it, so the clipping path stays the bottom object. - object.transform takes drawBehind (with copy); the tools send it while Alt is held. A value that is not true or false is refused. - Draw Normal, Draw Inside, object.move, the transform dialogs' Copy, Duplicate and Transform Again keep putting copies above. - Document::insert_below puts nodes directly below their anchors in one pass. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/doc/src/document.rs | 15 ++ crates/doc/src/tests/lookups.rs | 24 ++- .../engine/src/cmd/distortcmds/perspective.rs | 4 +- crates/engine/src/cmd/edit.rs | 51 +++++- crates/engine/src/cmd/object.rs | 2 +- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/transform.rs | 45 +++-- crates/engine/src/interaction.rs | 2 + crates/engine/src/session/edit.rs | 3 +- crates/engine/src/tests/xform.rs | 164 ++++++++++++++++++ crates/tools/src/direct.rs | 10 +- crates/tools/src/direct/tests.rs | 13 +- crates/tools/src/select.rs | 4 + docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- 15 files changed, 308 insertions(+), 42 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 608902756b..d102716866 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -659,6 +659,21 @@ impl Document { Ok(()) } + /// Put each list of nodes in `items` directly below its anchor, in list order, in one pass over + /// the children of each parent. It fails as [`Document::insert_beside`] does. + pub fn insert_below(&mut self, items: Vec<(NodeId, Vec)>) -> Result<(), DocError> { + let anchors: Vec = items.iter().map(|(id, _)| *id).collect(); + let places = self.places(&anchors)?; + let mut lists: Vec> = items.into_iter().map(|(_, nodes)| nodes).collect(); + self.edit_children(places, |k, anchor, children| { + let nodes = lists.get_mut(k).map(std::mem::take).unwrap_or_default(); + children.extend(nodes.into_iter().map(Arc::new)); + children.push(anchor); + })?; + self.index.clear(); + Ok(()) + } + /// Where each of `ids` is ([`Places`]). Fails with `NoNode` for an id that is not in the tree, /// is listed twice or lies inside another listed node. fn places(&self, ids: &[NodeId]) -> Result { diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 9c5c278a53..d7c24934e0 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -1,6 +1,6 @@ //! The batched lookups ([`Document::index_paths`], `node_at`, `node_mut_at`, `ancestry_at`) agree //! with the one-id ones on nested trees with missing and duplicated ids, and the edits of many nodes -//! ([`Document::remove_many`], `wrap`, `insert_beside`) leave the tree that `remove`, `insert` and +//! ([`Document::remove_many`], `wrap`, `insert_beside`, `insert_below`) leave the tree that `remove`, `insert` and //! `move_node` leave one node at a time. use crate::*; use vectorcraft_geom::shapes; @@ -290,6 +290,26 @@ fn insert_beside_matches_inserting_one_at_a_time() { } } +#[test] +fn insert_below_matches_inserting_one_at_a_time() { + for seed in 1..40 { + let (mut d, mut ids) = tree(seed); + let picked = picks(&d, seed); + // None to three new nodes for each anchor. + let items: Vec<(NodeId, Vec)> = picked.iter().enumerate().map(|(k, id)| (*id, (0..k % 4).map(|_| square(&mut d)).collect())).collect(); + ids.extend(items.iter().flat_map(|(_, new)| new.iter().map(|n| n.id))); + let (mut a, mut b) = (d.clone(), d.clone()); + for (id, new) in items.clone() { + let (parent, at, _) = a.position(id).unwrap(); + for (k, n) in new.into_iter().enumerate() { + a.insert(parent, at + k, n).unwrap(); + } + } + b.insert_below(items).unwrap(); + same(&a, &b, &ids, &format!("seed {seed}")); + } +} + #[test] fn wrap_matches_inserting_a_group_and_moving_the_nodes_into_it_one_at_a_time() { for seed in 1..40 { @@ -331,6 +351,8 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { let items = list.iter().map(|id| (*id, vec![])).collect(); assert_eq!(b.insert_beside(items, replace).err(), Some(DocError::NoNode(bad)), "{what}"); } + let items = list.iter().map(|id| (*id, vec![])).collect(); + assert_eq!(b.insert_below(items).err(), Some(DocError::NoNode(bad)), "{what}"); assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index 90d58541a6..6589fd3468 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -231,7 +231,7 @@ fn persp_edit( let d = &s.doc()?.doc; fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none())) }; - let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None }; + let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false, false)? } else { None }; let edited = s.edit(label, |d, sel| { g.adopt_stored_attachments(d); let targets = match &kept { @@ -502,7 +502,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result { // lists attachments of its own (`stores_attachments`). let kept = if objects == "copy" && s.in_interaction() && !stores_attachments(&s.doc()?.doc) { let on = on_plane(&s.doc()?.doc); - crate::cmd::object::preview_copies(s, &on, false)? + crate::cmd::object::preview_copies(s, &on, false, false)? } else { None }; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccebbfac88..a20a6c47e4 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1828,7 +1828,19 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { /// Duplicate `roots` directly above each original, transform the copies, select them /// ([`copy_above`]). pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selection, roots: &[NodeId], xf: Affine) -> Result> { - let out = copy_above(d, roots, |_, _, c| { + duplicate_beside(d, sel, roots, xf, false) +} + +/// [`duplicate_in`], with each copy directly below its original when `below` is true +/// ([`copy_beside`]). +pub(crate) fn duplicate_beside( + d: &mut Document, + sel: &mut vectorcraft_doc::Selection, + roots: &[NodeId], + xf: Affine, + below: bool, +) -> Result> { + let out = copy_beside(d, roots, below, |_, _, c| { c.transform(xf, true); super::object::keep_pixel_aligned(c, true.into()); })?; @@ -1841,20 +1853,42 @@ pub(crate) fn duplicate_in(d: &mut Document, sel: &mut vectorcraft_doc::Selectio /// tree as it is. The copies take new ids in the order of `roots`. Roots listed twice, or inside /// another root, are copied one at a time: each copy is made from the document as the copies /// before it left it. Copied type whose layout caches [`Document::reid`] dropped has them again. -pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result> { +pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], change: impl FnMut(&mut Document, &Node, &mut Node)) -> Result> { + copy_beside(d, roots, false, change) +} + +/// [`copy_above`], with each copy directly below its original, in the same parent, when `below` +/// is true. The clipping path of a clip group or a clipping layer stays the bottom child: its copy +/// goes directly above it. +pub(crate) fn copy_beside( + d: &mut Document, + roots: &[NodeId], + below: bool, + mut change: impl FnMut(&mut Document, &Node, &mut Node), +) -> Result> { let paths = d.index_paths(roots.iter().copied()); let mut found: Vec<_> = roots.iter().filter_map(|id| paths.get(id)).collect(); found.sort_unstable(); + // The bottom child of a parent that clips is its clipping path. + let clips_at = |d: &Document, up: &[usize], i: usize| i == 0 && !up.is_empty() && d.node_at(up).is_some_and(Node::clips); let out = if found.windows(2).all(|w| !w[1].starts_with(w[0])) { - let mut copies = Vec::with_capacity(roots.len()); + let (mut copies, mut above) = (Vec::with_capacity(roots.len()), vec![]); + let mut out = Vec::with_capacity(roots.len()); for id in roots { - let Some(n) = paths.get(id).and_then(|p| d.node_at(p)).cloned() else { continue }; + let Some(p) = paths.get(id) else { continue }; + let Some(n) = d.node_at(p).cloned() else { continue }; let mut c = d.reid(&n); change(d, &n, &mut c); - copies.push((*id, vec![c])); + out.push(c.id); + let on_floor = below && p.split_last().is_some_and(|(i, up)| clips_at(d, up, *i)); + if !below || on_floor { above.push((*id, vec![c])) } else { copies.push((*id, vec![c])) } + } + if !copies.is_empty() { + d.insert_below(copies)?; + } + if !above.is_empty() { + d.insert_beside(above, false)?; } - let out: Vec = copies.iter().flat_map(|(_, c)| c.iter().map(|n| n.id)).collect(); - d.insert_beside(copies, false)?; out } else { let mut out = vec![]; @@ -1863,7 +1897,8 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn let Some(n) = d.node(*id).cloned() else { continue }; let mut c = d.reid(&n); change(d, &n, &mut c); - out.push(d.insert(par, idx + 1, c)?); + let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); + out.push(d.insert(par, if below { idx.max(floor) } else { idx + 1 }, c)?); } out }; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index fd0aece164..b2d857a464 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -12,7 +12,7 @@ use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, Vec2}; use vectorcraft_render::effects; -use super::edit::{duplicate_in, outermost, selected_roots, selected_roots_to_transform}; +use super::edit::{duplicate_beside, outermost, selected_roots, selected_roots_to_transform}; use super::opacitymask::percent; use super::{ CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, f64_or, f64_req, has_doc, has_multi, has_selection, diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0bc08c748e..9082850dff 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Transform", [], None, - "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", + "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints), drawBehind?: bool (with copy: in Draw Behind, view.drawMode, each copy goes directly below its original instead of above it, as the Selection and Direct Selection tools' Alt-drags send; default false)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", has_doc, transform ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index f86d777e71..536dcf9c98 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -1,7 +1,7 @@ use super::align::choice; use super::{ Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad, - bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param, + bool_or, check_numbers, check_switches, duplicate_beside, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param, selected_roots_to_transform, }; @@ -91,12 +91,22 @@ pub(crate) fn transform_node(n: &mut Node, xf: Affine, sc: Scaling, objects: boo /// `anchors` (`ids` being the selection): with anchors selected with Direct Selection and no /// copy, only those anchors transform, their handles with them, and the objects selected whole. pub(crate) fn apply_transform(s: &mut Session, label: &str, ids: Vec, xf: Affine, p: &Value, anchors: bool) -> Result { - apply_transform_moving_guides(s, label, ids, xf, p, anchors, None) + apply_transform_moving_guides(s, label, ids, xf, p, anchors, Placing::default()) } -/// [`apply_transform`], with the selected ruler guides moved by `guides` instead of by the +/// Where [`apply_transform_moving_guides`] puts the selected ruler guides and the copies. +#[derive(Clone, Copy, Default)] +struct Placing { + /// The selected ruler guides move by this instead of by the transform's translation. + guides: Option, + /// Each copy goes directly below its original instead of above it. + below: bool, +} + +/// [`apply_transform`], with the selected ruler guides moved by `placing.guides` instead of by the /// translation `xf` when given (a nudge along a turned Constrain Angle moves the art along it and -/// the guides along the page's axes). +/// the guides along the page's axes), and with each copy directly below its original with +/// `placing.below`. fn apply_transform_moving_guides( s: &mut Session, label: &str, @@ -104,8 +114,9 @@ fn apply_transform_moving_guides( xf: Affine, p: &Value, anchors: bool, - guides: Option, + placing: Placing, ) -> Result { + let Placing { guides, below } = placing; let copy = bool_or(p, "copy", false); let areas = bool_or(p, "typeAreas", false); let objects = transforms_objects(p); @@ -138,7 +149,7 @@ fn apply_transform_moving_guides( } else if none || (!copy && xf == Affine::IDENTITY) { if copy { vec![] } else { ids } } else { - let kept = if copy { preview_copies(s, &ids, with_guides)? } else { None }; + let kept = if copy { preview_copies(s, &ids, with_guides, below)? } else { None }; s.edit(label, |d, sel| { let targets = match &kept { // The document becomes the snapshot with the kept copies, untransformed, and the @@ -155,7 +166,7 @@ fn apply_transform_moving_guides( } else { None }; - let new_ids = duplicate_in(d, sel, &ids, Affine::IDENTITY)?; + let new_ids = duplicate_beside(d, sel, &ids, Affine::IDENTITY, below)?; if let Some(copies) = guide_copies { sel.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect(); } @@ -212,11 +223,12 @@ fn apply_transform_moving_guides( /// Returns the copies of `roots` for a transform or a perspective edit with `copy` in an interaction /// whose document is still its snapshot, as in a preview ([`Session::preview`] puts the snapshot /// back first). These are the copies the interaction keeps when they were made of that snapshot for -/// the same `roots`; otherwise this copies `roots` with [`duplicate_in`] in a clone of the snapshot, -/// untransformed, and the interaction keeps that clone. It returns `None` outside an interaction, +/// the same `roots` on the same side (`below`: directly below each original); otherwise this copies +/// `roots` with [`duplicate_beside`] in a clone of the snapshot, untransformed, and the interaction +/// keeps that clone. It returns `None` outside an interaction, /// and when the document is no longer the snapshot, as for a command run in a typing session or a /// script batch after an earlier edit there: the command then copies the current document. -pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool) -> Result>> { +pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: bool, below: bool) -> Result>> { let st = s.doc_mut()?; let Some(it) = &mut st.interaction else { return Ok(None) }; if !Arc::ptr_eq(&st.doc, &it.doc) { @@ -226,19 +238,20 @@ pub(crate) fn preview_copies(s: &mut Session, roots: &[NodeId], with_guides: boo if let Some(k) = &it.copies && Arc::ptr_eq(&k.from, &it.doc) && k.roots == roots + && k.below == below && (k.selection.guides.is_empty() != has_guide_copies) { return Ok(Some(k.clone())); } let mut doc = it.doc.clone(); let mut selection = st.selection.clone(); - let ids = duplicate_in(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY)?; + let ids = duplicate_beside(Arc::make_mut(&mut doc), &mut selection, roots, Affine::IDENTITY, below)?; if has_guide_copies { let d = Arc::make_mut(&mut doc); let copies: Vec<_> = st.selection.guides.iter().filter_map(|&i| d.ruler_guide(i)).collect(); selection.guides = copies.iter().map(|g| d.add_ruler_guide(g)).collect(); } - let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), doc, selection, ids }); + let k = Arc::new(crate::PreviewCopies { from: it.doc.clone(), roots: roots.to_vec(), below, doc, selection, ids }); it.copies = Some(k.clone()); Ok(Some(k)) } @@ -256,7 +269,9 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool { pub(super) fn transform(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?; - check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?; + check_switches(p, &["anchors", "releaseOutside", "interpolate", "drawBehind"], "object.transform")?; + // An Alt-drag copy in Draw Behind goes directly below its original. + let below = bool_or(p, "drawBehind", false) && bool_or(p, "copy", false) && s.draw_mode == crate::DrawMode::Behind; let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?; // An object selected in a symbol instance's art stays where the symbol puts it: the selection // is left as it is, and the reply's warning goes to the status bar. @@ -280,7 +295,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result { if grouped { s.begin_named_undo_group(None); } - let r = apply_transform(s, "Transform", ids, m, p, anchors); + let r = apply_transform_moving_guides(s, "Transform", ids, m, p, anchors, Placing { guides: None, below }); let released = match &r { Ok(_) if !moved.is_empty() => crate::cmd::shaper::release_outside(s, &moved), _ => Ok(false), @@ -358,7 +373,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { return ok(); } } - apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Some(Vec2::new(gx, gy))) + apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Placing { guides: Some(Vec2::new(gx, gy)), below: false }) } pub(super) fn about(o: Point, a: Affine) -> Affine { diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 99a2569005..06cc86859e 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -55,6 +55,8 @@ pub(crate) struct PreviewCopies { pub(crate) from: Arc, /// The transform or perspective edit copied these objects. pub(crate) roots: Vec, + /// Each copy is directly below its original, not above it. + pub(crate) below: bool, /// This is `from` with the copies added, untransformed. pub(crate) doc: Arc, /// This is the selection after copying, with the copies selected. diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index bbd20fa5bb..e2ba1715b9 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -433,11 +433,12 @@ impl Session { let m = cmd::matrix_param(&preview.1, "matrix"); if let Some(m) = m { // The options are the last preview's params with the values it noted, without the - // matrix and the ids. + // matrix, the ids and `drawBehind` (Transform Again puts its copies above). let mut options = preview.1.clone(); if let Some(o) = options.as_object_mut() { o.remove("matrix"); o.remove("ids"); + o.remove("drawBehind"); } st.last_transform = Some(LastTransform::Matrix(m, options)); st.last_perspective = None; diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 89c3b28b13..8d0d037022 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -254,6 +254,170 @@ fn canceling_an_alt_drag_leaves_the_document_as_it_was() { assert!(s.doc().unwrap().interaction.is_none()); } +/// Returns the ids of the children of the document's layer `layer` (0 is the bottom one). +fn layer_kids(s: &Session, layer: usize) -> Vec { + s.doc().unwrap().doc.layers[layer].children().unwrap().iter().map(|n| n.id).collect() +} + +/// Returns a session with three squares side by side, `a`, `b` and `c` from the bottom of the +/// stack up, and `b` selected; and their ids. +fn three_squares() -> (Session, [NodeId; 3]) { + let mut s = session(); + let ids = [100.0, 200.0, 300.0].map(|x| rect(&mut s, x, 100.0, 40.0, 40.0)); + s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap(); + (s, ids) +} + +/// Alt-drags the selection 80 pt down with `tool`, pressing at `press`. +fn alt_drag(s: &mut Session, tool: &str, press: (f64, f64)) { + s.select_tool(tool, ViewInfo::default()).unwrap(); + drag_at(s, PointerKind::Down, press, true); + for dy in [20.0, 50.0, 80.0] { + drag_at(s, PointerKind::Drag, (press.0, press.1 + dy), true); + } + drag_at(s, PointerKind::Up, (press.0, press.1 + 80.0), true); +} + +/// In Draw Behind, an Alt-drag with the Selection tool, or with Direct Selection on an object +/// selected whole, puts the copy directly below its original, selected, in one undo step. In Draw +/// Normal and Draw Inside the copy goes directly above it, as before. +#[test] +fn an_alt_drag_in_draw_behind_puts_the_copy_directly_below_its_original() { + for (tool, press) in [("selection", (220.0, 120.0)), ("directSelection", (200.0, 100.0))] { + for mode in ["behind", "normal", "inside"] { + let (mut s, [a, b, c]) = three_squares(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + alt_drag(&mut s, tool, press); + let what = format!("{tool}, {mode}"); + let kids = layer_kids(&s, 0); + let copy = s.doc().unwrap().selection.objects.clone(); + assert_eq!(copy.len(), 1, "{what}: the copy is selected"); + let want = if mode == "behind" { vec![a, copy[0], b, c] } else { vec![a, b, copy[0], c] }; + assert_eq!(kids, want, "{what}"); + assert!(close(bounds(&s, copy[0]), Rect::new(200.0, 180.0, 240.0, 220.0)), "{what}: {:?}", bounds(&s, copy[0])); + assert!(close(bounds(&s, b), Rect::new(200.0, 100.0, 240.0, 140.0)), "{what}: the original stays"); + assert_eq!(undo_len(&s), undo + 1, "{what}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(*s.doc().unwrap().doc == *before, "{what}: Undo gives back the document"); + } + } +} + +/// In Draw Behind, an Alt-drag of several objects puts each copy directly below its own original, +/// in the original's group or layer: objects side by side in one layer, a group (copied whole) and +/// an object in another layer. +#[test] +fn an_alt_drag_in_draw_behind_puts_each_copy_below_its_own_original() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 40.0, 40.0); + let x = rect(&mut s, 200.0, 100.0, 40.0, 40.0); + let y = rect(&mut s, 260.0, 100.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [x.0, y.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let c = rect(&mut s, 400.0, 100.0, 40.0, 40.0); + s.execute("layer.new", &json!({})).unwrap(); + let d = rect(&mut s, 500.0, 100.0, 40.0, 40.0); + assert_eq!(layer_kids(&s, 0), vec![a, g, c]); + assert_eq!(layer_kids(&s, 1), vec![d]); + s.execute("select.set", &json!({"ids": [a.0, g.0, c.0, d.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let undo = undo_len(&s); + alt_drag(&mut s, "selection", (120.0, 120.0)); + let (bottom, top) = (layer_kids(&s, 0), layer_kids(&s, 1)); + assert_eq!(bottom.len(), 6, "{bottom:?}"); + assert_eq!([bottom[1], bottom[3], bottom[5], top[1]], [a, g, c, d], "the originals keep their order"); + let copies = [bottom[0], bottom[2], bottom[4], top[0]]; + let mut selected = s.doc().unwrap().selection.objects.clone(); + selected.sort_unstable(); + let mut want = copies.to_vec(); + want.sort_unstable(); + assert_eq!(selected, want, "the copies are selected"); + let group_copy = s.doc().unwrap().doc.node(copies[1]).unwrap().children().map(Vec::len); + assert_eq!(group_copy, Some(2), "the group is copied whole, once"); + assert_eq!(undo_len(&s), undo + 1); +} + +/// `drawBehind` puts the copies of an interaction's previews below their originals only in Draw +/// Behind and only with `copy`: a later preview without it does not reuse the copies made below, +/// and a transform with `copy` but without `drawBehind`, `object.move` with `copy`, and Transform +/// Again after an Alt-drag in Draw Behind put their copies above. A `drawBehind` that is not true or +/// false is refused, and the document and its undo history stay as they were. +#[test] +fn only_an_alt_drag_copy_follows_draw_behind() { + let (mut s, [a, b, c]) = three_squares(); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + s.begin_interaction("Copy").unwrap(); + let below = json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true}); + s.preview("object.transform", &below).unwrap(); + let first = s.doc().unwrap().selection.objects.clone(); + assert_eq!(layer_kids(&s, 0), vec![a, first[0], b, c]); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 90], "copy": true})).unwrap(); + let second = s.doc().unwrap().selection.objects.clone(); + assert_eq!(layer_kids(&s, 0), vec![a, b, second[0], c], "a copy without `drawBehind` goes above"); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 90], "copy": false, "drawBehind": true})).unwrap(); + assert_eq!(layer_kids(&s, 0), vec![a, b, c], "without `copy`, nothing is copied"); + s.cancel_interaction().unwrap(); + + let (mut s, [a, b, c]) = three_squares(); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + for (cmd, params) in + [("object.transform", json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true})), ("object.move", json!({"dx": 0, "dy": 80, "copy": true}))] + { + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let copy = ids_of(&s.execute(cmd, ¶ms).unwrap()); + assert_eq!(layer_kids(&s, 0), vec![a, b, copy[0], c], "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + } + // An object listed twice is copied twice, each copy directly below it in turn. + let twice = + ids_of(&s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true, "ids": [b.0, b.0]})).unwrap()); + assert_eq!(layer_kids(&s, 0), vec![a, twice[0], twice[1], b, c]); + s.execute("edit.undo", &json!({})).unwrap(); + + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + alt_drag(&mut s, "selection", (220.0, 120.0)); + let copy = s.doc().unwrap().selection.objects.clone(); + assert_eq!(layer_kids(&s, 0), vec![a, copy[0], b, c]); + let Some(LastTransform::Matrix(_, options)) = s.doc().unwrap().last_transform.clone() else { panic!("the drag is kept for Transform Again") }; + assert!(options.get("drawBehind").is_none(), "{options}"); + let again = ids_of(&s.execute("object.transformAgain", &json!({})).unwrap()); + assert_eq!(layer_kids(&s, 0), vec![a, copy[0], again[0], b, c], "Transform Again copies above"); + + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute("object.transform", &json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": "yes"})).unwrap_err(); + assert!(e.to_string().contains("`drawBehind` must be true or false"), "{e}"); + assert!(Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(undo_len(&s), undo); +} + +/// In Draw Behind, the copy of a clip group's clipping path goes directly above it, so the clipping +/// path stays the group's bottom child; the copy of the clipped art goes below that art. +#[test] +fn a_copy_in_draw_behind_leaves_the_clipping_path_at_the_bottom() { + let mut s = session(); + let art = rect(&mut s, 100.0, 100.0, 80.0, 80.0); + rect(&mut s, 110.0, 110.0, 40.0, 40.0); + s.execute("select.all", &json!({})).unwrap(); + let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let kids = |s: &Session| -> Vec { s.doc().unwrap().doc.node(g).unwrap().children().unwrap().iter().map(|n| n.id).collect() }; + let [mask, clipped] = kids(&s)[..] else { panic!("{:?}", kids(&s)) }; + assert_eq!(clipped, art); + s.execute("view.drawMode", &json!({"mode": "behind"})).unwrap(); + let params = |ids: [NodeId; 2]| json!({"matrix": [1, 0, 0, 1, 0, 80], "copy": true, "drawBehind": true, "ids": [ids[0].0, ids[1].0]}); + let copies = ids_of(&s.execute("object.transform", ¶ms([mask, art])).unwrap()); + assert_eq!(kids(&s), vec![mask, copies[0], copies[1], art]); + s.execute("edit.undo", &json!({})).unwrap(); + // An object listed twice is copied one at a time, over the clipping path too. + let copies = ids_of(&s.execute("object.transform", ¶ms([mask, mask])).unwrap()); + assert_eq!(kids(&s), vec![mask, copies[1], copies[0], art]); +} + +/// Returns the `ids` of a command's reply. +fn ids_of(r: &Value) -> Vec { + r["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect() +} + /// Returns a session with the grid and the square of [`persp_session`], the grid shown with its /// right plane active, and a group of two squares attached to the right plane beside the square, /// with the square and the group selected; and the square's id. diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cd4432c3c8..cc27b25d2a 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1735,10 +1735,12 @@ impl DirectSelectionTool { } self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides); self.moved = Some(d); - out.push(Action::Preview( - "object.transform".into(), - json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(d)), "copy": ev.mods.alt}), - )); + let mut params = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(d)), "copy": ev.mods.alt}); + // An Alt-drag copy follows Draw Behind. + if ev.mods.alt { + params["drawBehind"] = json!(true); + } + out.push(Action::Preview("object.transform".into(), params)); out } fn release_move(&mut self, cx: &ToolContext, began: bool) -> Vec { diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 4f3b795921..87dc281405 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -1990,8 +1990,7 @@ fn alt_dragged_copies_snap_by_the_anchor_pressed() { whole.set([b]); let c = cx(&d, &whole, &p); let mut t = DirectSelectionTool::new(false); - let copy = - |dx: f64, dy: f64| json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": true}); + let copy = |dx: f64, dy: f64| json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": true, "drawBehind": true}); // B's top-left corner, pressed 1 pt off, onto A's bottom-right one. let (v, labels) = drag(&mut t, &c, (301.0, 301.0), (203.0, 199.0), alt); assert_eq!((v, labels), (copy(-100.0, -100.0), vec!["anchor".to_string()])); @@ -2016,11 +2015,13 @@ fn alt_during_a_drag_by_an_anchor_toggles_the_copy() { whole.set([b]); let c = cx(&d, &whole, &p); let mut t = DirectSelectionTool::new(false); + // A copy follows Draw Behind (`drawBehind`); a move sends no such key. let preview = |dx: f64, dy: f64, copy: bool| { - Action::Preview( - "object.transform".into(), - json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": copy}), - ) + let mut params = json!({"matrix": matrix_json(vectorcraft_geom::Affine::translate(vectorcraft_geom::Vec2::new(dx, dy))), "copy": copy}); + if copy { + params["drawBehind"] = json!(true); + } + Action::Preview("object.transform".into(), params) }; assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 300.0, 300.0)).is_empty()); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 250.0, 250.0)), vec![Action::Begin("Move".into()), preview(-50.0, -50.0, false)]); diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index fc18a978e6..27c57323dd 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1980,6 +1980,10 @@ impl SelectionTool { self.state = State::Moving { start, press, hold, grip, began: true, deselect: None, key: None, exclude: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); + // An Alt-drag copy follows Draw Behind. + if m.alt { + params["drawBehind"] = json!(true); + } if backquote { params["objects"] = json!(false); params["patterns"] = json!(true); diff --git a/docs/mcp.md b/docs/mcp.md index fe69653330..da69c215db 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2349,7 +2349,7 @@ The transform, Align, Object Properties and Live Shape Properties commands refus that is not true or false with `` `strokes` must be true or false ``, naming the key, and leave the document and its undo history as they were: the options `copy`, `strokes`, `corners`, `patterns`, `objects` and `typeAreas` in `object.transform`, `object.move`, `object.nudge`, `object.rotate`, `object.scale`, `object.reflect`, `object.shear`, -`object.transformAgain` and `object.setBounds`; `anchors` and `releaseOutside` in `object.transform`; `big` in `object.nudge`; +`object.transformAgain` and `object.setBounds`; `anchors`, `releaseOutside` and `drawBehind` in `object.transform`; `big` in `object.nudge`; `absolute` in `object.rotate`; `proportional` in `object.setBounds`; `patterns` in `object.align`, `object.distribute` and `object.distributeSpacing`; `visible`, `locked`, `isolate` and `knockoutShape` in `object.setProps`; and `invertPie`, `makeSidesEqual` and `relativeRadii` in `object.setLiveShape`. A null is read as a key left out. @@ -9137,7 +9137,12 @@ Drawing modes (`view.drawMode`) apply too: in Draw Inside, `edit.paste`, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put the objects inside the object drawn into (its clip group, made on the first paste), whatever Paste Remembers Layers says; in Draw Behind, `edit.pasteInPlace` and `edit.pasteOnAllArtboards` put them just below the selection. `edit.pasteInFront` and -`edit.pasteInBack` ignore the drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`, +`edit.pasteInBack` ignore the drawing mode. In Draw Behind, an Alt-drag (Option-drag on macOS) of whole objects with +the Selection or Direct Selection tool puts each copy directly below its own original, in the original's group or layer, +and selects the copies: the tools send `object.transform` with `copy` and `drawBehind: true`. The copy of the clipping +path of a clip group or a clipping layer goes directly above it, so the clipping path stays the bottom object. Without `drawBehind`, and +in Draw Normal and Draw Inside, the copies go directly above; `object.move` and the transform dialogs' Copy, +`edit.duplicate` and `object.transformAgain` put them above in every drawing mode. When the object drawn into is the one isolation mode isolates (`object.isolate`, or a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so the new art can be picked and isn't dimmed; `edit.undo` or `edit.redo` that removes the isolated object ends isolation mode. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eeb3a0c818..60b34b0644 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1422,7 +1422,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). From 0b5620cf787e9fec88f82416cd20c475917a24a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:25:52 -0800 Subject: [PATCH 067/126] Type: the font scan tells whether a family sets Thai as loading it does The system font scan built each face from its name, fvar, OS/2, head and post tables only, so a family that was found but not loaded never had Thai in its traits. The font menus' Thai filter left such families out, and Show Similar Fonts grouped them with the other scripts until they were loaded. - A face sets Thai when its OS/2 table allows it (no OS/2 table, the Thai Unicode range, bit 24, or the Thai code page, bit 16) and its character map has Thai, loaded or scanned. - The scan reads the cmap table of such a face only, up to 16 MiB. The search for a document's missing fonts reads no cmap table, so its byte limit covers the same tables as before. --- crates/text/src/fontdb/scan.rs | 46 ++++++++++++++++++++++--------- crates/text/src/fontdb/traits.rs | 19 +++++++++++-- crates/text/src/test_fonts.rs | 45 ++++++++++++++++++++++++++++++ crates/text/src/tests/sysfonts.rs | 33 ++++++++++++++++++++++ 4 files changed, 127 insertions(+), 16 deletions(-) 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 7a2a23f089..b515eb70a1 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -575,6 +575,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 ada5c45dd1..cef154c440 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -475,6 +475,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"); From 1106a8f667b9eccf81819c93625f61b8e090e14c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:28:51 -0800 Subject: [PATCH 068/126] Tests: check Revolve's surface alpha under colored lights in absolute terms colored_revolve_faces_leave_no_alpha_holes_at_one_to_one compared each representation only with its own 3x render, so a 60% opacity lost or applied twice by SVG or PDF import passed at both scales. The test now also reads the alpha inside the body: 153 within 3 levels with a fill opacity of 60%, 214 within 3 levels with 60% gradient stops (front and back faces at 60% each), and 255 when opaque. --- crates/engine/tests/it/three_d_light_color.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/it/three_d_light_color.rs b/crates/engine/tests/it/three_d_light_color.rs index 40752a2fce..be06539537 100644 --- a/crates/engine/tests/it/three_d_light_color.rs +++ b/crates/engine/tests/it/three_d_light_color.rs @@ -719,7 +719,9 @@ fn alpha_against_supersampled(d: &Document) -> (usize, usize, u8, usize, Vec 10_000, "{name} {of}: {measured} pixels inside"); + // The 3x comparison passes when an opacity is lost or doubled at both scales, so the + // surface's alpha is also checked against the value it should have. + // With 60% gradient stops, each face takes the stops' opacity, so where the front and + // back of the body overlap the alpha is 1 - 0.4 * 0.4 of 255. + let alpha = render(&d).pixel(150, 200)[3]; + let expected = if name.ends_with("fill at 60%") { + 150..=156 + } else if name.ends_with("gradient at 60%") { + 211..=217 + } else { + 255..=255 + }; + if !expected.contains(&alpha) { + failures.push(format!("{name} {of}: surface alpha {alpha}, expected {expected:?}")); + } if off > 0 || past > 0 { failures.push(format!("{name} {of}: of {measured} pixels, {off} off (at most {worst}), {past} past the outline: {first:?}")); } From 320c4d41468df89a96bd01117077b182dfab2f29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:29:36 -0800 Subject: [PATCH 069/126] Path Precision Tools: Common Tangents keeps both lines from a point close to a round path When two or more neighboring sampled normal angles all came out within the touching tolerance, the root search took the run as one place where the outlines touch and returned a single line at its middle. A point just outside a circle, with both of its tangents on neighboring samples, then got one line that misses the circle instead of two. The search now looks between each pair of those samples for a value that leaves the tolerance, and finds the roots between those places: a crossing where the sign changes, a dip where it does not. A run that stays within the tolerance, as at a corner, still gives one line. --- .../pathops/src/addons/pathtools/tangents.rs | 67 ++++++++++++++++--- 1 file changed, 57 insertions(+), 10 deletions(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index 655e84e311..e893a93997 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -576,15 +576,13 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result, s: f64, k: usize, lo: f64, hi: f64| { - let g = |t: f64| f(t, k); + // Between `lo` and `hi`, where `s * g` is positive at both ends: the least of `s * g`, a double + // root where it reaches zero, two roots where it goes past it, none where it stays above. + let dip = |out: &mut Vec, s: f64, g: &dyn Fn(f64) -> f64, lo: f64, hi: f64| { let (t, least) = golden(&|t| s * g(t), lo, hi); if least < -tol { - out.push(simple(bisect(&g, lo, t))); - out.push(simple(bisect(&g, t, hi))); + out.push(simple(bisect(g, lo, t))); + out.push(simple(bisect(g, t, hi))); } else if least <= tol { out.push(Root { angle: t, double: true }); } @@ -604,12 +602,45 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result = [(t_low, low), (t_high, -high)].into_iter().filter(|(_, v)| !zero(*v)).collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + marks.extend(found); + } + marks.push((ang(k, len + 1), val(k + len + 1))); + if marks.len() == 2 { + out.push(Root { angle: (ang(k, 1) + ang(k, len)) / 2.0, double: true }); + } else { + for pair in marks.windows(2) { + if let [(lo, a), (hi, b)] = *pair { + if a.signum() == b.signum() { + dip(&mut out, a.signum(), &piece, lo, hi); + } else { + out.push(simple(bisect(&piece, lo, hi))); + } + } + } + } } continue; } @@ -622,7 +653,7 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result = out.into_iter().map(|r| Root { angle: r.angle.rem_euclid(TAU), ..r }).collect(); @@ -1135,6 +1166,22 @@ mod tests { assert_eq!(at(1e-6).len(), 2); } + #[test] + fn a_point_whose_two_tangents_fall_on_neighboring_samples_keeps_both() { + // The point lies on the bisector of two neighboring sampled normals, at the distance where + // its two tangents touch the circle at exactly those normals. Both samples are zero, but + // between them the point is well outside the circle: two lines, not one. + let (r, half) = (10.0, TAU / SAMPLES as f64 / 2.0); + let p = (Vec2::new(half.cos(), half.sin()) * (r / half.cos())).to_point(); + let all = common_tangents(&Outline::point(p).unwrap(), &circle(0.0, 0.0, r)).unwrap(); + assert_eq!(all.len(), 2, "{all:?}"); + // Each runs from the point to where the circle's radius meets it square. + for angle in [0.0, 2.0 * half] { + let touch = (Vec2::new(angle.cos(), angle.sin()) * r).to_point(); + assert!(all.iter().any(|t| ends_within(t, p, touch, 1e-6)), "{angle}: {all:?}"); + } + } + #[test] fn open_concave_empty_and_identical_outlines_are_refused() { let open = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], false); From e14312ae59243d3cc089cce8c00fccd8693d7396 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:29:36 -0800 Subject: [PATCH 070/126] PDF export: a color-masked CMYK image with an image mask keeps its hidden colors hidden A CMYK image with an opacity mask on its own pixel grid is written with the mask's alpha as its soft mask. That path recoded the image's own pixels and ignored its color mask, so the colors the color mask hides were drawn wherever the mask's alpha was not zero. The soft mask is now the mask's alpha multiplied by the alpha of the pixels the color mask shows, and the cache key includes the shown pixels. A test covers a plain and a distorted image. --- crates/pdf/src/export/images.rs | 44 +++++++++++++++++++++++------- crates/pdf/src/export/nodes.rs | 6 +++- crates/pdf/src/images.rs | 15 ++++++++++ crates/pdf/src/tests/cmykimages.rs | 39 ++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 11 deletions(-) diff --git a/crates/pdf/src/export/images.rs b/crates/pdf/src/export/images.rs index 3da2079b9b..dfaf9a2c7c 100644 --- a/crates/pdf/src/export/images.rs +++ b/crates/pdf/src/export/images.rs @@ -183,22 +183,33 @@ impl Exporter<'_> { /// CMYK image `im` with the alpha of its opacity mask `m`, when the mask is a greyscale image /// on the image's own pixel grid (an image's soft mask as it opens): the alpha is written as the /// image's soft mask, as an RGBA image's is, rather than as a luminosity soft mask over it, - /// through which CoreGraphics draws CMYK images on black boxes (#2159). `None` for other - /// images and masks; cached like [`Self::load_image`], `interpolate` as there. - pub(super) fn masked_image(&mut self, im: &vectorcraft_doc::ImageObject, m: &vectorcraft_doc::OpacityMask, interpolate: bool) -> Option { + /// through which CoreGraphics draws CMYK images on black boxes (#2159). `shown` is `im` as it is + /// shown ([`vectorcraft_doc::Document::shown_image`]). When a color mask shows other pixels + /// that are not CMYK (`im`'s own pixels with the hidden colors clear), `im`'s inks are written + /// with the mask's alpha multiplied by the shown pixels' alpha, so the hidden colors stay + /// hidden; shown pixels that are CMYK are written themselves. `None` for other images and + /// masks, and for shown pixels of another size; cached like [`Self::load_image`], + /// `interpolate` as there. + pub(super) fn masked_image( + &mut self, + im: &vectorcraft_doc::ImageObject, + shown: &vectorcraft_doc::ImageObject, + m: &vectorcraft_doc::OpacityMask, + interpolate: bool, + ) -> Option { let art = &m.art; let NodeKind::Image(mi) = &art.kind else { return None }; // A color-masked image in the mask's art masks with the pixels it shows. - let shown = self.doc.shown_image(art, mi); - let mi = &*shown; + let shown_mask = self.doc.shown_image(art, mi); + let mi = &*shown_mask; let plain = art.opacity >= 1.0 && art.blend == BlendMode::Normal && art.extras().mask.is_none() && !art.appearance.effects.iter().any(|e| e.visible); if m.invert || !plain || (mi.xf, mi.width, mi.height) != (im.xf, im.width, im.height) { return None; } - let size = self.image_size(im); + let size = self.image_size(shown); let interpolate = interpolate && self.interpolate; - let mut cache = format!("{}\u{0}{}\u{0}{}", im.key, mi.key, m.clip); + let mut cache = format!("{}\u{0}{}\u{0}{}\u{0}{}", im.key, shown.key, mi.key, m.clip); if self.downsampled() { cache.push_str(&format!("\u{0}{:.3}x{:.3}", size.0, size.1)); } @@ -209,8 +220,20 @@ impl Exporter<'_> { return i.clone(); } let doc = self.doc; - let img = doc.image_blob(im).filter(|b| b.is_cmyk()).and_then(|blob| { - let alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; + // Pixels a color mask shows that are not CMYK carry the hidden colors as their alpha. + let shown_blob = doc.image_blob(shown); + let (source, hidden) = match shown_blob { + Some(b) if shown.key != im.key && !b.is_cmyk() => (doc.image_blob(im), Some(b)), + b => (b, None), + }; + let img = source.filter(|b| b.is_cmyk()).and_then(|blob| { + let mut alpha = crate::images::mask_alpha(doc.image_blob(mi)?, im.width, im.height, m.clip)?; + if let Some(hidden) = hidden { + let shown_alpha = crate::images::image_alpha(hidden, im.width, im.height)?; + for (a, s) in alpha.iter_mut().zip(shown_alpha) { + *a = ((u32::from(*a) * u32::from(s) + 127) / 255) as u8; + } + } let icc = self.out.cmyk_image_icc(blob); let tag = self.out.cmyk_tag(icc.as_deref()); let r = crate::images::recode_cmyk(blob, size, self.compression, interpolate, self.out.cmyk_pixels(), Some(alpha), tag); @@ -452,7 +475,8 @@ mod tests { assert!(exporter.colorized_image(&image("pic", scale), &paint, true).is_some(), "colorized at {scale}"); let art = vectorcraft_doc::Node::new(doc.layers[0].id, vectorcraft_doc::NodeKind::Image(Box::new(image("alpha", scale)))); let mask = vectorcraft_doc::OpacityMask::new(art, true); - assert!(exporter.masked_image(&image("inks", scale), &mask, true).is_some(), "masked at {scale}"); + let inks = image("inks", scale); + assert!(exporter.masked_image(&inks, &inks, &mask, true).is_some(), "masked at {scale}"); } assert_eq!(exporter.images.len(), 2, "{:?}", exporter.images.keys().collect::>()); } diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 94b1c819c5..d84e8f7124 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -375,7 +375,11 @@ impl Exporter<'_> { let mask = n.extras().mask.as_deref().filter(|m| !m.disabled); let alpha = match (&n.kind, mask) { // The mask's image shares the pixel grid only when it has the same corners (or none). - (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.masked_image(im, m, !n.extras().pixelated), + // A color-masked image keeps the colors it hides hidden. + (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => { + let shown = self.doc.shown_image(n, im); + self.masked_image(im, &shown, m, !n.extras().pixelated) + } _ => None, }; if let Some(m) = mask diff --git a/crates/pdf/src/images.rs b/crates/pdf/src/images.rs index eaff6c781f..d08f1069b4 100644 --- a/crates/pdf/src/images.rs +++ b/crates/pdf/src/images.rs @@ -840,6 +840,21 @@ pub(crate) fn mask_alpha(blob: &ImageBlob, width: u32, height: u32, clip: bool) Some(img.pixels().map(|p| ((u32::from(p[0]) * u32::from(p[3]) + back * (255 - u32::from(p[3])) + 127) / 255) as u8).collect()) } +/// The alpha of each pixel of image `blob` (255 for an image without alpha), when it is `width` × +/// `height` pixels. `None` for a CMYK image, another size, or one too large to hold as RGBA or +/// that can't be decoded; as in [`mask_alpha`], the size is read from the header first. +pub(crate) fn image_alpha(blob: &ImageBlob, width: u32, height: u32) -> Option> { + if blob.is_cmyk() { + return None; + } + let reader = ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().ok()?; + if reader.into_dimensions().ok()? != (width, height) || u64::from(width) * u64::from(height) * 4 > MAX_DECODE { + return None; + } + let img = decoded(&blob.bytes)?.into_rgba8(); + (img.dimensions() == (width, height)).then(|| img.pixels().map(|p| p[3]).collect()) +} + /// Opaque colour `samples` (grey, RGB, or CMYK ink amounts, as `space` says) as a JPEG at /// `quality`, tagged with ICC profile `icc` when given. CMYK JPEGs hold Adobe's inverted samples, /// which the PDF writer's Decode array undoes. diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index b5f6185ea9..9d333eecb3 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -1210,6 +1210,45 @@ fn a_distorted_cmyk_image_and_its_grid_mask_with_the_same_corners_write_it_as_it } } +/// A color-masked CMYK image with a gray mask of its grid keeps its inks and its hidden colors +/// hidden: the image's `/SMask` is the mask's alpha times the alpha of the pixels the color mask +/// shows, so a hidden pixel stays clear where the mask's alpha is not zero, for a distorted image +/// too. +#[test] +fn a_color_masked_cmyk_image_with_a_grid_mask_keeps_its_hidden_colors_hidden() { + for distorted in [false, true] { + let mut d = masked_doc(png(image::GrayImage::from_raw(2, 2, vec![255, 128, 0, 64]).unwrap()), true, false); + // The first pixel hidden, where the mask is fully opaque, and the last half shown. + let alpha = [0, 255, 255, 128]; + let shown = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([0, 90, 200, alpha[(y * 2 + x) as usize]])); + d.images.insert("shown".into(), ImageBlob::new("image/png", png(shown))); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(16.0, 0.0), (24.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y)); + let mut mask = d.node(id).unwrap().extras().mask.clone().unwrap(); + if distorted { + Arc::make_mut(&mut mask.art).set_image_corners(q).unwrap(); + } + let n = d.node_mut(id).unwrap(); + n.extras_mut().mask = Some(mask); + n.extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { + key: "shown".into(), + from: "img".into(), + background: vectorcraft_doc::color_mask::MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + if distorted { + n.set_image_corners(q).unwrap(); + } + let (bytes, smasks) = export_smasks(&d); + assert!(!smasks.is_empty() && smasks.iter().all(|m| m.as_deref() == Some(&[0, 128, 0, 32][..])), "{distorted}: {smasks:?}"); + assert!(distorted || !String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); + } +} + /// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden /// pixels are clear in the image's `/SMask`. #[test] From 2e6976e88482252e1fae6fb8fa7922d7d4099af3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:31:34 -0800 Subject: [PATCH 071/126] Tests: a selected group member's anchor is the point its move snaps by A press near an anchor of a member selected inside a group grabs the member by that anchor, with Smart Guides or Snap to Point on, and a drag lands that anchor on another object's anchor. The new test covers the snapping origin that #8091 gave such a press; it fails when hover_point stops reading selected art under the pointer. --- crates/tools/src/select/tests.rs | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index dd9c25b74d..71e206b806 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -3121,3 +3121,40 @@ fn a_press_on_a_selected_member_of_a_group_moves_the_selected_members() { let down = t.pointer(&c, &ev(PointerKind::Down, 125.0, 125.0)); assert!(!is_select(&down), "every anchor: {down:?}"); } + +/// A press near an anchor of a member selected inside a group grabs the member by that anchor, +/// so with Smart Guides or Snap to Point on that anchor is the point that snaps during the move. +#[test] +fn a_press_near_an_anchor_of_a_selected_group_member_grabs_it_by_that_anchor() { + use vectorcraft_doc::{Appearance, Document, Node}; + use vectorcraft_geom::shapes; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (outer, inner, a, b) = (d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()); + let path = |id: NodeId, x: f64| Node::path(id, shapes::rectangle(Rect::new(x, 100.0, x + 50.0, 150.0)), Appearance::default_art()); + d.insert(Some(l), 0, Node::group(outer, vec![])).unwrap(); + d.insert(Some(outer), 0, Node::group(inner, vec![])).unwrap(); + d.insert(Some(inner), 0, path(a, 100.0)).unwrap(); + d.insert(Some(outer), 1, path(b, 300.0)).unwrap(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + for (smart_guides, snap_to_point) in [(true, true), (true, false), (false, true)] { + // The bounding box hidden: its corner handle sits on the anchor and would take the press. + let c = ToolContext { smart_guides, snap_to_point, show_bbox: false, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + let down = t.pointer(&c, &ev(PointerKind::Down, 103.0, 103.0)); + assert!(down.is_empty(), "smart guides {smart_guides}, snap to point {snap_to_point}: {down:?}"); + assert!( + matches!(t.state, State::Moving { hold, grip: Grip::Anchor, .. } if hold == Point::new(100.0, 100.0)), + "smart guides {smart_guides}, snap to point {snap_to_point}: {:?}", + t.state + ); + // The grabbed anchor follows the pointer: dragged to (301.5, 101), the anchor at (100, 100) + // lands on the other member's anchor at (300, 100). + let a = t.pointer(&c, &ev(PointerKind::Drag, 301.5, 101.0)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("smart guides {smart_guides}, snap to point {snap_to_point}: {a:?}") }; + let moved = (v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()); + assert!((moved.0 - 200.0).abs() < 1e-9 && moved.1.abs() < 1e-9, "smart guides {smart_guides}, snap to point {snap_to_point}: {moved:?}"); + } +} From 0575c1604a04d3cd04625243eb5b73fe95818885 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:55:08 -0800 Subject: [PATCH 072/126] Swatch libraries: adding a pattern again reuses its numbered colors Since the change that brings a library pattern's global and spot colors under a numbered name ("Ink 2") when the document gives the name another color, adding the same pattern or color again added more copies, and Use Library Item still linked a pattern's art to the document's own color of that name. - A library color whose name the document gives another color is the document's numbered copy with the same color, so adding it again adds nothing. A numbered name that the same call also picks is not shared. - A pattern the document holds with its art linked to the document's own color of a name, as pasting with Merge leaves it, is reused instead of coming in again as "Squares 2". - `added` lists the colors a pattern brought, after the picked swatches. - A library tint added with its base color links to the base's name in the document, and a later add finds it there. - library.use brings a pattern's colors the same way. Docs: docs/mcp.md. --- crates/engine/src/cmd/clipboard/resources.rs | 5 +- crates/engine/src/cmd/library.rs | 32 +++- crates/engine/src/cmd/patternlib.rs | 56 ++++-- crates/engine/src/cmd/swatchlib.rs | 80 ++++++-- crates/engine/src/tests/library.rs | 86 +++++++++ crates/engine/src/tests/swatchlib.rs | 192 +++++++++++++++++++ docs/mcp.md | 11 +- 7 files changed, 426 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index c20c763495..4d1c3aa53a 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -623,8 +623,9 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } - /// Add for every conflict: each pasted swatch whose name the document gives another color - /// comes in renamed. + /// Add for every conflict, as a library pattern is added to a document: each global or spot + /// color of its art whose name the document gives another color comes in under a numbered + /// name, or as the document's numbered copy of that name with the same color. pub(crate) fn add_all() -> Self { Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4d562a76e7..6bbb4049e0 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -713,7 +713,7 @@ pub fn specs() -> Vec { "Use Library Item", [], None, - "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", + "{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}", has_doc, use_item ), @@ -1353,12 +1353,32 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result { if clip.nodes.is_empty() { return Err(damaged()); } - let choices = SwatchChoices::default(); + // A global or spot color the pattern's art links to keeps the library's color: when the + // document gives its name another color, it comes in under a numbered name ("Ink 2"), as + // Add to Swatches brings a library pattern's colors. + let mut choices = SwatchChoices::add_all(); // The pattern's name in the document, worked out on a copy: nothing to add is no edit. - let mut probe = (*s.doc()?.doc).clone(); - let imported = clip.import_into(&mut probe, &choices, false)?; - let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str()); - let target = renamed.unwrap_or(&name).to_string(); + let current = s.doc()?.doc.clone(); + let mut probe = (*current).clone(); + let mut imported = clip.import_into(&mut probe, &choices, false)?; + let pattern_of = |i: &super::clipboard::resources::Imported| { + i.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str()).unwrap_or(&name).to_string() + }; + // A pattern used before a color of its art kept the library's color has its art linked to the + // document's own color of that name: when merging those colors reuses a pattern of the document + // that keeping them would add again, they merge. + if current.pattern(&pattern_of(&imported)).is_none() + && imported.renamed.iter().any(|r| r["kind"] == "swatch") + && super::patternlib::has_candidate(¤t, &doc, &name) + { + let mut merged = (*current).clone(); + let found = clip.import_into(&mut merged, &SwatchChoices::default(), false)?; + if current.pattern(&pattern_of(&found)).is_some() { + (choices, probe, imported) = (SwatchChoices::default(), merged, found); + } + } + drop(current); + let target = pattern_of(&imported); let paint = vectorcraft_doc::pattern::pattern_paint(&target); // A pattern the document holds without a swatch (an imported SVG's) gets one. let has_swatch = diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 97351a27a2..84453f4268 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -90,10 +90,17 @@ pub fn swatch_source(w: &Swatch) -> Option> { /// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for /// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out. /// A global or spot color whose name `d` gives another color comes in under a free name, as Add -/// to Swatches adds such a color, so that the pattern keeps the library's colors. +/// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors +/// merge instead when that reuses a pattern of `d` that keeping them would add again +/// ([`merge_reuses`]). pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { + let gathered = gather(lib, name); + let merge = !gathered.swatches.is_empty() + && has_candidate(d, lib, name) + && probe(d, &gathered, &SwatchChoices::add_all()).and_then(|with_add| merge_reuses(d, &gathered, name, &with_add)).is_some(); + let choices = if merge { SwatchChoices::default() } else { SwatchChoices::add_all() }; let had: std::collections::HashSet = d.swatches_iter().map(|w| w.name.clone()).collect(); - let imported = gather(lib, name).import_into(d, &SwatchChoices::add_all(), false)?; + let imported = gathered.import_into(d, &choices, false)?; let from = |to: &str| { let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str()); renamed.unwrap_or(to).to_string() @@ -121,7 +128,8 @@ fn imported_name(imported: &Imported, name: &str) -> String { /// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding /// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as /// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted -/// with, is imported into a copy of `d`, so that those resources are compared too. +/// with, is imported into a copy of `d`, so that those resources are compared too, with the colors +/// of its art merged when [`merge_reuses`] says so. pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 @@ -131,23 +139,49 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio && gathered.char_styles.is_empty() && gathered.para_styles.is_empty() && gathered.brushes.is_empty() - && gathered.images.is_empty(); + && gathered.images.is_empty() + && gathered.graph_designs.is_empty(); if only_pattern { return existing_pattern(d, lib, name); } - // Importing reuses only a pattern under that name or a numbered copy of it with the same tile - // options and as many art objects; without one, the document is not copied. - let def = lib.pattern(name)?; + // Without a pattern to reuse, the document is not copied. + if !has_candidate(d, lib, name) { + return None; + } + let with_add = probe(d, &gathered, &SwatchChoices::add_all())?; + if with_add.added == 0 { + return Some(imported_name(&with_add, name)); + } + merge_reuses(d, &gathered, name, &with_add).filter(|m| m.added == 0).map(|m| imported_name(&m, name)) +} + +/// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name +/// or a numbered copy of it with the same tile options and as many art objects. +pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool { + let Some(def) = lib.pattern(name) else { return false }; let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() }; let copy = |n: &str| { n == name || n.strip_prefix(name).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit())) }; - if !d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) { + d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) +} + +/// What importing `gathered` into a copy of `d` with `choices` does. +fn probe(d: &Document, gathered: &Clipboard, choices: &SwatchChoices) -> Option { + let mut probe = d.clone(); + gathered.import_into(&mut probe, choices, false).ok() +} + +/// When importing `gathered` (pattern `name`) into `d` with Add (`with_add`) adds the pattern again +/// because a global or spot color of its art comes in numbered, while merging those colors reuses a +/// pattern of `d`, what merging does. Such a pattern has its art linked to the document's own colors +/// of those names, as pasting with Merge, or adding it from a library before, leaves it. +fn merge_reuses(d: &Document, gathered: &Clipboard, name: &str, with_add: &Imported) -> Option { + let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); + if reused(with_add) || !with_add.renamed.iter().any(|r| r["kind"] == "swatch") { return None; } - let mut probe = d.clone(); - let imported = gathered.import_into(&mut probe, &SwatchChoices::add_all(), false).ok()?; - (imported.added == 0).then(|| imported_name(&imported, name)) + probe(d, gathered, &SwatchChoices::default()).filter(reused) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index e4d89b9c13..bf564bcede 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1030,34 +1030,69 @@ fn add(s: &mut Session, p: &Value) -> Result { // The document's swatches by name (the first of a name wins, as in `Document::swatch`), looked // up once so that a large palette takes linear time. let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); + // The document's numbered copies ("Ink 2") by the name they are numbered after, in order. + let mut copies: std::collections::HashMap<&str, Vec<&Swatch>> = std::collections::HashMap::new(); for w in d.swatches_iter() { - by_name.entry(w.name.as_str()).or_insert(w); + let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue }; + e.insert(w); + if let Some((base, n)) = w.name.rsplit_once(' ') + && !n.is_empty() + && n.bytes().all(|b| b.is_ascii_digit()) + { + copies.entry(base).or_default().push(w); + } } - let there = |w: &Swatch| match (&w.paint, &patterns) { + // A numbered copy whose name a picked library swatch has stands for that swatch alone. + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // `paint` is `w`'s paint with a tint's base color under the name the base has in the document. + let there = |w: &Swatch, paint: &Paint| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } _ => match by_name.get(w.name.as_str()) { - Some(x) => x.paint == w.paint, - None => w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == w.paint), - } - .then(|| w.name.clone()), + Some(x) if x.paint == *paint => Some(w.name.clone()), + // A color whose name the document gives another color is the numbered copy of it that + // an earlier add or a pattern's art brought in, when that copy is the same color. + Some(_) => copies + .get(w.name.as_str()) + .and_then(|c| { + c.iter().find(|x| !picked_names.contains(x.name.as_str()) && x.paint == *paint && x.global == w.global && x.spot == w.spot) + }) + .map(|x| x.name.clone()), + None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), + }, }; // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; let mut fresh = vec![]; for &(group, w) in &picked { - match there(w) { + // A tint of a color the document has under a numbered name is compared linked to that name. + let relinked = match &w.paint { + Paint::Solid { swatch: Some(base), .. } => existing.iter().find(|(l, n)| l == base && n != base).map(|(_, n)| { + let mut paint = w.paint.clone(); + if let Paint::Solid { swatch: Some(b), .. } = &mut paint { + *b = n.clone(); + } + paint + }), + _ => None, + }; + match there(w, relinked.as_ref().unwrap_or(&w.paint)) { Some(name) => existing.push((w.name.clone(), name)), None => fresh.push((group, w)), } } let undo_before = s.doc()?.history.undo.len(); - // Library name → the name it got in the document. + // Library name → the name it got in the document. The colors the patterns brought that no + // library swatch of this call stands for are added too; they are listed after the others and + // are never the one `apply` paints with. + let mut brought_alone: Vec<(String, String)> = vec![]; + // Library name → the name of the document's swatch for it, for the tints added here. + let mut links: std::collections::HashMap = existing.iter().cloned().collect(); let added: Vec<(String, String)> = if fresh.is_empty() { vec![] } else { - let (added, reused) = s.edit("Add to Swatches", |d, _| { + let (added, reused, brought) = s.edit("Add to Swatches", |d, _| { let mut out = vec![]; // Library pattern swatches that stand for a swatch added earlier in this call. let mut reused = vec![]; @@ -1101,8 +1136,11 @@ fn add(s: &mut Session, p: &Value) -> Result { (name.clone(), Swatch { name, paint, global: false, spot: false }) } else { // A color a pattern added earlier in this call brought with its art is that - // swatch: it moves to the library swatch's place. - let at = brought.iter().position(|(from, _)| *from == w.name); + // swatch when it shows the library swatch's color: it moves to the library + // swatch's place. + let same = + |to: &str| d.swatch(to).is_some_and(|x| x.paint.color() == w.paint.color() && x.global == w.global && x.spot == w.spot); + let at = brought.iter().position(|(from, to)| *from == w.name && same(to)); let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| { let i = d.swatches.iter().position(|x| x.name == n)?; Some(d.swatches.remove(i)) @@ -1111,10 +1149,19 @@ fn add(s: &mut Session, p: &Value) -> Result { Some(sw) => (sw.name.clone(), sw), None => { let name = free_in(&mut taken, &w.name); - (name.clone(), Swatch { name, ..(*w).clone() }) + let mut sw = Swatch { name: name.clone(), ..(*w).clone() }; + // A tint links to its base color under the name the base has in the + // document. + if let Paint::Solid { swatch: Some(base), .. } = &mut sw.paint + && let Some(to) = links.get(base.as_str()) + { + *base = to.clone(); + } + (name, sw) } } }; + links.insert(w.name.clone(), name.clone()); match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); @@ -1135,13 +1182,16 @@ fn add(s: &mut Session, p: &Value) -> Result { } out.push((w.name.clone(), name)); } - Ok((out, reused)) + Ok((out, reused, brought)) })?; existing.extend(reused); + brought_alone = brought; added }; let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::>(); - let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)}); + let mut added_names = names(&added); + added_names.extend(names(&brought_alone)); + let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); s.execute(cmd, &json!({"swatch": name, "focus": focus}))?; diff --git a/crates/engine/src/tests/library.rs b/crates/engine/src/tests/library.rs index a75bc532bf..cf5fc3c269 100644 --- a/crates/engine/src/tests/library.rs +++ b/crates/engine/src/tests/library.rs @@ -456,6 +456,92 @@ fn a_pattern_item_adds_the_swatch_of_a_pattern_the_document_holds_without_one() assert!(!s.doc().unwrap().doc.swatches_iter().any(is_dots), "undone with the paint"); } +/// A pattern item whose art links to a global color that the document has under the same name in +/// another color keeps the item's color: the color comes in under a numbered name and the pattern +/// links to it. Used again, the pattern and that color are reused. A document whose pattern of +/// that name links to the document's own color (as pasting with Merge leaves it) reuses that one. +#[test] +fn a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color() { + let mut s = session(); + let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + make_pattern(&mut s, &dot, "Dots"); + let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]})); + run(&mut s, "select.set", json!({"ids": [a]})); + run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"})); + run(&mut s, "edit.copy", json!({})); + let names = |s: &Session, base: &str| -> Vec { + let d = &s.doc().unwrap().doc; + d.swatches_iter().filter(|w| w.name.starts_with(base)).map(|w| w.name.clone()).collect() + }; + let art_link = |s: &Session, pattern: &str| match s.doc().unwrap().doc.pattern(pattern).unwrap().art[0].appearance.fill_paint() { + vectorcraft_color::Paint::Solid { swatch, color, .. } => (swatch, color.to_hex()), + p => panic!("the pattern's art is not filled with a color: {p:?}"), + }; + // A document whose Ink is red. + let red_ink = |s: &mut Session| { + run(s, "file.new", json!({"width": 300, "height": 300})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let b = run(s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone(); + run(s, "select.set", json!({"ids": [b]})); + }; + red_ink(&mut s); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"})); + assert_eq!(r["pattern"], "Dots", "{r}"); + assert_eq!(art_link(&s, "Dots"), (Some("Ink 2".to_string()), "#0000ff".to_string())); + assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"]); + run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots", "to": "stroke"})); + assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused"); + assert_eq!(names(&s, "Ink"), ["Ink", "Ink 2"], "the color is reused"); + // Pasted with Merge, the pattern links to the document's red Ink. + red_ink(&mut s); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + assert_eq!(art_link(&s, "Dots"), (Some("Ink".to_string()), "#ff0000".to_string())); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"})); + assert_eq!(r["pattern"], "Dots", "{r}"); + assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused"); + assert_eq!(names(&s, "Ink"), ["Ink"]); +} + +/// A pattern pasted with Merge whose art uses a tint of a global color is reused by its pattern +/// item after the tint swatch is deleted: the tint swatch comes back and no copy of the pattern is +/// added. +#[test] +fn a_merged_pattern_whose_tint_swatch_was_deleted_is_reused() { + let mut s = session(); + let lib = run(&mut s, "library.create", json!({}))["id"].as_str().unwrap().to_string(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.ellipse", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]})); + make_pattern(&mut s, &dot, "Dots"); + let a = run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Dots", "ids": [a]})); + run(&mut s, "select.set", json!({"ids": [a]})); + run(&mut s, "library.add", json!({"library": lib, "kind": "fillPattern"})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 300, "height": 300})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let tints: Vec = + s.doc().unwrap().doc.swatches_iter().filter(|w| w.name != "Ink" && w.name.starts_with("Ink")).map(|w| w.name.clone()).collect(); + assert_eq!(tints.len(), 1, "the tint swatch comes with the paste: {tints:?}"); + run(&mut s, "swatch.delete", json!({"names": tints, "unlink": false})); + let b = run(&mut s, "shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 80}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [b]})); + let r = run(&mut s, "library.use", json!({"library": lib, "kind": "fillPattern", "item": "Dots"})); + assert_eq!(r["pattern"], "Dots", "{r}"); + assert_eq!(s.doc().unwrap().doc.patterns.len(), 1, "the pattern is reused"); + let restored = s.doc().unwrap().doc.swatch(&tints[0]).map(|w| w.paint.clone()); + assert!( + matches!(&restored, Some(vectorcraft_color::Paint::Solid { swatch: Some(base), tint, .. }) if base == "Ink" && (*tint - 0.5).abs() < 1e-6), + "the tint swatch comes back as a tint of the document's Ink: {restored:?}" + ); +} + /// Gradients and patterns go out to a library file and come back; read from a file, a gradient /// with too few stops is dropped, one out of range is put in range, and a pattern whose data is /// damaged or doesn't hold its pattern fails cleanly when used. diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 8036bf04c3..da044f78e6 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -516,6 +516,198 @@ fn a_library_pattern_keeps_its_global_color_when_the_document_has_that_name_in_a assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}"); } +/// A library with pattern swatch `Tiles`, whose pattern `Squares` is filled with global color +/// `Ink` (#0000ff), loaded into `s`, which is then left in a new document whose own global `Ink` +/// is #ff0000 → the library's id. The library document's square painted with `Tiles` is on the +/// clipboard. +fn squares_library_and_a_red_ink(s: &mut Session) -> Value { + use std::sync::Arc; + use vectorcraft_doc::pattern::pattern_paint; + run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + s.edit("Pattern", |d, _| { + let ink = Paint::Solid { color: Color::rgb8(0, 0, 0xff), swatch: Some("Ink".into()), tint: 1.0 }; + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 6.0, 6.0)); + let square = vectorcraft_doc::Node::path(d.alloc_id(), square, vectorcraft_doc::Appearance::basic(ink, Paint::None, 0.0)); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 8.0, 8.0); + d.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Squares", vec![Arc::new(square)]) }); + d.swatches.push(vectorcraft_color::Swatch { name: "Tiles".into(), paint: pattern_paint("Squares"), global: false, spot: false }); + Ok(()) + }) + .unwrap(); + let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(s, "select.set", json!({"ids": [r]})); + run(s, "edit.copy", json!({})); + run(s, "file.new", json!({"width": 100, "height": 100})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + id +} + +/// The names of the swatches of `s`'s document that are `base` or a numbered copy of it. +fn named_after(s: &Session, base: &str) -> Vec { + let copy = |n: &str| n == base || n.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|r| r.bytes().all(|b| b.is_ascii_digit())); + doc(s).swatches_iter().filter(|w| copy(&w.name)).map(|w| w.name.clone()).collect() +} + +/// A library color that the document has as a numbered copy of the same color ("Ink 2", brought by +/// the pattern added with it before) is that copy: adding the pattern and the color again adds +/// nothing. +#[test] +fn adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]})); + assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", "Ink 2"])), "{again}"); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); +} + +/// The colors a library pattern brings with its art are listed with the swatches added, the +/// numbered ones included, when the call adds the pattern swatch alone. +#[test] +fn the_colors_a_library_pattern_brings_are_listed_as_added() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); + assert_eq!(r["added"], json!(["Tiles", "Ink 2"]), "{r}"); +} + +/// A library pattern that is already in the document with its art linked to the document's own +/// color of that name (as pasting with Merge leaves it) is that pattern: adding its swatch adds no +/// numbered copy of the pattern or of the color. +#[test] +fn a_library_pattern_linked_to_the_documents_own_color_is_not_added_again() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Squares"]); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.iter().map(|p| p.name.as_str()).collect::>(), ["Squares"], "{r}"); + assert_eq!(named_after(&s, "Ink"), ["Ink"], "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles"])), "{again}"); +} + +/// With `apply`, the color picked first is the one applied, even when a pattern added in the same +/// call brings a numbered copy of its name. +#[test] +fn apply_paints_with_the_picked_color_not_one_a_pattern_brought() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + // The document's Ink is the library's color as a process color. + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"})); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"], "{r}"); + assert_eq!(r["applied"], "Ink", "{r}"); +} + +/// A numbered copy that another swatch of the same name hides (the document finds the first of a +/// name) is not taken for a library color, even when it has that color. +#[test] +fn a_hidden_numbered_copy_is_not_taken_for_a_library_color() { + let mut s = session(); + let id = squares_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.newGroup", json!({"name": "Blues", "swatches": ["Ink 2"]})); + s.edit("Green", |d, _| { + let green = Paint::Solid { color: Color::rgb8(0, 0xff, 0), swatch: None, tint: 1.0 }; + d.swatches.push(vectorcraft_color::Swatch { name: "Ink 2".into(), paint: green, global: true, spot: false }); + Ok(()) + }) + .unwrap(); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!(r["existing"], json!([]), "{r}"); + let name = r["added"][0].as_str().unwrap_or_default().to_string(); + let blue = doc(&s).swatch(&name).and_then(|w| w.paint.color()).map(|c| c.to_hex()); + assert_eq!(blue.as_deref(), Some("#0000ff"), "{r}"); +} + +/// The global color the swatch `name` of `s`'s document is a tint of. +fn tint_base(s: &Session, name: &str) -> Option { + match doc(s).swatch(name).map(|w| &w.paint) { + Some(Paint::Solid { swatch, .. }) => swatch.clone(), + _ => None, + } +} + +/// A library with global color `Ink` (#0000ff) and its tint `Ink half` loaded into `s`, which is +/// then left in a new document whose own global `Ink` is #ff0000 → the library's id. +fn tinted_ink_library_and_a_red_ink(s: &mut Session) -> Value { + run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(s, "file.new", json!({"width": 100, "height": 100})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + id +} + +/// A library tint added with its global color, which comes in under a numbered name, is a tint of +/// that numbered color, not of the document's own color of the library color's name. +#[test] +fn a_library_tint_follows_its_color_to_its_numbered_name() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!(r["added"], json!(["Ink 2", "Ink half"]), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 2", "Ink half"])), "{again}"); +} + +/// A numbered copy of a color's name that the library also has as a swatch of its own stands for +/// that swatch alone, even when both library swatches have its color. +#[test] +fn a_numbered_copy_the_library_also_names_is_not_shared() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}"); +} + +/// A library tint is not taken for the tint a pattern brought back in the library color's place +/// when that tint shows the document's own color (the pattern's art links to it, as pasting with +/// Merge leaves it): it comes in as a tint of the library color's numbered copy. +#[test] +fn a_library_tint_is_not_the_one_a_merged_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "the pasted tint follows the document's Ink"); + run(&mut s, "swatch.delete", json!({"names": ["Ink half"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Ink half"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); + let tint = r["added"][1].as_str().unwrap_or_default().to_string(); + assert!(tint.starts_with("Ink half"), "{r}"); + assert_eq!(tint_base(&s, &tint).as_deref(), Some("Ink 2"), "{r}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..bddbbe38e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5802,7 +5802,10 @@ From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes -in under a numbered name ("Ink 2") and the pattern links to that. A document with +in under a numbered name ("Ink 2") and the pattern links to that. A library color whose name the document gives +another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color +again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name +is used as it is. `added` lists the colors the pattern's art brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. @@ -6015,7 +6018,11 @@ swatch, else `Gradient`; `library.use` paints the selection's fill or stroke wit (else the default one, or the pattern swatch `swatch`) with the images, symbols, patterns, swatches, styles and brushes its art uses, and a thumbnail of one swatch's worth of it; `library.use` adds the pattern and its swatch to the document (the same pattern there is reused, and a name the document gives another pattern gets a number) and paints the selection's -fill or stroke with it, as one undo step, and returns the pattern's name in the document as `pattern`. `library.get` +fill or stroke with it, as one undo step, and returns the pattern's name in the document as `pattern`. A global or spot +color the pattern's art links to keeps the item's color, as with `swatch.library.add`: when the document gives its name +another color, it comes in under a numbered name ("Ink 2"), or as the document's numbered copy of the same color, and +the pattern links to it. A pattern the document holds with its art linked to the document's own color of that name is +reused. `library.get` lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`. Items can be put in user-named groups, which the panel shows as collapsible sections after the ungrouped items (its From 94f4d54b0482d739b377d2ef3dfe4b4571b7ee5e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:57:05 -0800 Subject: [PATCH 073/126] Width tool: an Alt-double-click on one of several selected points edits them all An Alt-press on a width point's center narrows the selection to that point, ready to drag a copy. A release without a drag kept it narrowed and did not remember the earlier selection, so an Alt-double-click on one of several selected points opened Width Point Edit for that point alone, where a plain double-click opens it for all of them. A release without a drag now remembers the earlier selection as a plain click does, and an Alt-drag still copies only the point under the pointer. --- crates/tools/src/distort/width.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index b2050dbbdf..792dff3b26 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -494,6 +494,18 @@ impl Tool for WidthTool { // Points moved together stay selected. (true, _, Some((id, ts))) if d.mode == Mode::Move => Some((id, ts.into_iter().map(|t| (t + dt).clamp(0.0, 1.0)).collect())), (true, _, sel) => sel, + // An Alt-click without a drag copies nothing: like a plain click on one of + // several selected points, it lets a double-click edit them all. + (false, false, _) if d.mode == Mode::Copy && !ev.mods.shift => { + if let Some(sel) = self + .before_press + .clone() + .filter(|(owner, ts)| *owner == d.spot.owner && ts.len() > 1 && ts.iter().any(|t| (t - d.spot.t).abs() <= SAME_T)) + { + self.before_click = Some((sel, false)); + } + Some((d.spot.owner, vec![d.t])) + } (false, _, _) => Some((d.spot.owner, vec![d.t])), }; vec![Action::Commit] @@ -1107,6 +1119,21 @@ mod tests { assert!(v.get("indices").is_none()); assert_eq!(t.selected_indices(&c, id), vec![2]); } + // With Alt held, a double-click without a drag edits every selected point too. + let alt = Mods { alt: true, ..Default::default() }; + let mut t = WidthTool::default(); + click(&mut t, 150.0, none); + click(&mut t, 250.0, shift); + let v = double_click(&mut t, 250.0, alt); + assert_eq!((&v["indices"], v.get("index")), (&json!([1, 3]), None)); + assert_eq!(t.selected_indices(&c, id), vec![1, 3], "the selection is kept"); + // An Alt-drag still copies the one point under the pointer, and selects the copy alone. + t.pointer(&c, &ev(PointerKind::Down, 250.0, 200.0, alt)); + let acts = t.pointer(&c, &ev(PointerKind::Drag, 270.0, 200.0, alt)); + let (cmd, v) = preview(&acts); + assert_eq!((cmd, &v["index"]), ("stroke.widthPoint.copy", &json!(3))); + t.pointer(&c, &ev(PointerKind::Up, 270.0, 200.0, alt)); + assert_eq!(t.selected.as_ref().map(|(_, ts)| ts.len()), Some(1)); // A discontinuous point among them keeps both halves, and double-clicking it keeps the others. let (mut d2, _) = doc_line(); let points = vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)]; From bd3f69f23347df3caa7007f9659d4b4892885fed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:09:25 -0800 Subject: [PATCH 074/126] Path Precision Tools: Common Tangents finds a run's sample by binary search The touching-run search looked up the sample before each angle with a linear scan over the run, so a long run of samples within the tolerance cost time in proportion to the square of its length. It now collects the run's sample angles once and uses partition_point, which gives the same sample at every angle. --- crates/pathops/src/addons/pathtools/tangents.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/pathops/src/addons/pathtools/tangents.rs b/crates/pathops/src/addons/pathtools/tangents.rs index e893a93997..e10d8df5b7 100644 --- a/crates/pathops/src/addons/pathtools/tangents.rs +++ b/crates/pathops/src/addons/pathtools/tangents.rs @@ -613,8 +613,10 @@ fn roots(at: &[f64], f: &dyn Fn(f64, usize) -> f64, tol: f64) -> Result = (1..=len + 1).map(|j| ang(k, j)).collect(); let piece = |t: f64| { - let j = (1..=len + 1).take_while(|j| ang(k, *j) <= t).count(); + let j = edges.partition_point(|a| *a <= t); f(t, (k + j) % n) }; let mut marks = vec![(theta, val(k))]; From 12fd6872cc8e469b71e28aee2e0d6b1b37137b25 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:22:14 -0800 Subject: [PATCH 075/126] Pathfinder: setting Soft Mix's Mixing Rate to the value it has records no undo step effect.setParams compared a Pathfinder effect's values other than its Pathfinder Options exactly, so a mixingRate of 50 over a stored 50.0 counted as an edit and recorded an undo step. A float now compares with any number by value, and two integers still compare exactly. --- crates/engine/src/cmd/effectcmd.rs | 11 ++++++++--- crates/engine/src/tests/pathops.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index edb5561796..5638f76749 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -927,7 +927,8 @@ fn bevel_effect(id: &str) -> bool { /// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their /// defaults is unchanged), each option given equal to the one it stores (a precision that Scale /// Strokes & Effects took past its range evaluates at the bound but is still edited), and every -/// other value given equal to the one it has? +/// other value given equal to the one it has (a number by its value, so a Soft Mix `mixingRate` of 50 +/// over a stored 50.0 is unchanged)? fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool { if !effects::takes_pathfinder_options(&e.id) { return false; @@ -938,8 +939,12 @@ fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool { if let Value::Object(m) = &mut after { m.extend(given.clone()); } - let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v)); - let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x)); + // Two integers compare exactly, and a float compares with any number by value. + let same_value = |a: &Value, b: &Value| a == b || ((a.is_f64() || b.is_f64()) && a.as_f64().is_some_and(|x| b.as_f64() == Some(x))); + let others_same = given + .iter() + .filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())) + .all(|(k, v)| current.get(k).is_some_and(|c| same_value(c, v))); let stored_same = given .iter() .filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())) diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index feb71e40ad..4ebc8206f5 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -2067,6 +2067,23 @@ fn a_precision_set_after_a_scale_past_its_range_is_kept() { assert_eq!(s.doc().unwrap().history.undo.len(), steps); } +/// Soft Mix's Mixing Rate is compared by value: 50 over a stored 50.0 records no undo step, and 51 +/// is an edit. +#[test] +fn a_soft_mix_rate_set_to_its_value_records_no_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"mixingRate": 50.0}})).unwrap(); + assert_eq!(first_effect_params(&s)["mixingRate"], json!(50.0)); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = steps(&s); + assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 50}})).unwrap(), json!({"ids": []})); + assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(50.0), before), "50 over 50.0: no step"); + assert_ne!(s.execute("effect.setParams", &json!({"index": 0, "params": {"mixingRate": 51}})).unwrap(), json!({"ids": []})); + assert_eq!((first_effect_params(&s)["mixingRate"].clone(), steps(&s)), (json!(51), before + 1), "51 is an edit"); +} + /// A single group containing multiple overlapping paths is accepted by Crop. #[test] fn crop_operates_on_a_single_selected_group_of_paths() { From c9d6c8f126763fe4cf4679c3c595e47349d35328 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:23:32 -0800 Subject: [PATCH 076/126] Docs: an Alt-drag copy of a clipping path in Draw Behind goes above it The progress line now says that in Draw Behind the copy of the clipping path of a clip group or a clipping layer goes directly above it, so the clipping path stays the bottom object, as docs/mcp.md and copy_beside already do. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3571998c8e..11e277809a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1423,7 +1423,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). In Draw Behind, an Alt-drag copy made with the Selection or Direct Selection tool goes directly below its original and is selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists duplicating by Alt-drag among the actions the mode applies to; with several objects, each copy goes below its own original in that original's group or layer, the copy of the clipping path of a clip group or a clipping layer goes directly above it so the clipping path stays the bottom object, and in Draw Normal and Draw Inside, and for the transform dialogs' Copy, Duplicate and Transform Again, copies still go above (VectorCraft's own rules). In Draw Behind, a placed symbol instance (Place Symbol Instance in the Symbols panel, and a symbol dragged onto the canvas from the Symbols panel or a symbol library) goes directly below the selected object, or at the bottom of the current layer with nothing selected, as [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) describes for placing symbols; below the bottommost of several selected objects, beside the compound path that holds a selected path, and above a clipping path are VectorCraft's own rules. Draw Normal and Draw Inside keep it on top of the current layer. - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). From f2eb016e9824a9d8b1225ce5d6e3bc9a85ed096c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:26:14 -0800 Subject: [PATCH 077/126] Tests: transform turns about the same pivot with a null or omitted origin transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing ran a rotate with a null origin and checked only that the call succeeded. It now compares the resulting path with the same rotate with origin left out, so a null origin that moved the pivot would fail the test. --- crates/mcp/src/tests.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 6a95469d92..c8756cefc7 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1710,8 +1710,16 @@ fn transform_rejects_a_mistyped_reflect_copy_or_origin_before_editing() { assert_eq!(applied["isError"], false, "{applied}"); let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); assert_eq!(applied["applied"], json!(["move"])); - let applied = call(&mut s, 21, "transform", json!({"ids": [second], "rotate": 90, "origin": null})); + let unturned = inspect(&mut s, 21)["layers"].clone(); + let applied = call(&mut s, 22, "transform", json!({"ids": [second], "rotate": 90, "origin": null})); assert_eq!(applied["isError"], false, "{applied}"); + let turned = inspect(&mut s, 23)["layers"].clone(); + assert_ne!(turned, unturned, "the rotation must change the path"); + // A null `origin` turns about the same default pivot as an omitted one. + assert_eq!(call(&mut s, 24, "undo", json!({}))["isError"], false); + let applied = call(&mut s, 25, "transform", json!({"ids": [second], "rotate": 90})); + assert_eq!(applied["isError"], false, "{applied}"); + assert_eq!(inspect(&mut s, 26)["layers"], turned); // The schema allows null for every argument but `ids`. let tools = tool_definitions(); let props = &tools.iter().find(|t| t["name"] == "transform").unwrap()["inputSchema"]["properties"]; From 479dd2753526590e86d6696df475560f8eba9f68 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:42:08 -0800 Subject: [PATCH 078/126] Dimension tool: a line at a slight angle or past the distance limit is not a level A linear dimension line placed near another dimension's line lands on its level only when that line is parallel. Before, the check compared the two directions only, so a long line at a slight angle passed it: with its first end within the snapping tolerance, the new line landed on a level the other line had already left, and the guide ran at an angle between the lines. A line is now parallel when it moves off its level by no more than 0.000001 pt across the span of both lines. A level that would put the line more than 1,000,000 pt from its points is passed over. Before, the tool took it, the preview failed validation and was not sent, and a click committed the earlier preview position. The next level within reach is taken instead, or the line goes where the pointer is. The level guide also needs Smart Guides on when it is drawn, so turning Smart Guides off before the next pointer move hides it. The nonparallel case in the placement test now puts the pointer within reach of the first line's end, so it fails without the parallel check, and the guide test expects exactly one guide. --- crates/engine/tests/it/dimensions.rs | 16 ++++--- crates/tools/src/dimension.rs | 72 ++++++++++++++++++++++++++-- docs/dimensions.md | 6 ++- 3 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 30f3ce2665..dc88673521 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2077,18 +2077,19 @@ fn a_dimension_line_placed_beside_another_lands_on_its_level() { run(&mut s, "object.lock", json!({})); assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); // A dimension of the right edge has a vertical line, which is not parallel to the first: the - // pointer 2.5 points below the first line's level places it where the pointer is. + // pointer 2.5 points right of the first line's left end, within reach across the vertical + // line, places it where the pointer is. let (mut s, _) = level_start(plain); linear_click(&mut s, plain, 300.0, 200.0); linear_click(&mut s, plain, 300.0, 300.0); - linear_click(&mut s, plain, 330.0, 172.5); + linear_click(&mut s, plain, 102.5, 172.5); let id = s.doc().unwrap().selection.objects[0].0; - assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0))); + assert_eq!(recipe(&s, id).line_ends(), (pt(102.5, 200.0), pt(102.5, 300.0))); } /// While a dimension is placed with its line on the level of another, one alignment guide runs -/// along the level across both lines. Off the level, after a dropped press and with Alignment -/// Guides off, no guide shows. +/// along the level across both lines. Off the level, after a dropped press and with Smart Guides +/// or Alignment Guides off, no guide shows. #[test] fn a_dimension_line_on_another_level_shows_one_guide_across_both() { let plain = ViewInfo::default(); @@ -2097,7 +2098,10 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() { linear_click(&mut s, plain, 200.0, 200.0); linear_click(&mut s, plain, 300.0, 200.0); let guides = guide_lines(&mut s, plain, 250.0, 172.5); - assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + assert!(matches!(guides.as_slice(), [(a, b)] if near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + // Smart Guides turned off before the next pointer move: the guide goes. + let off = ViewInfo { smart_guides: false, ..plain }; + assert!(s.overlays(off).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(off)); assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level"); // A press on the level that the app drops cancels the preview, and its guide goes with it. assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index a2a27e0510..5dbe1fd6ef 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -530,7 +530,10 @@ fn dimension_lines(doc: &vectorcraft_doc::Document, preview: (u64, [Point; 2])) /// Where the line of the linear dimension `d`, placed through `p`, lands on the level of one of /// the `levels` that runs parallel to it, within `reach` of `p` across the line: the point to /// place `d` through, and the ends of that other line. The nearest level wins, then the line -/// nearest `p` along it (none nearer than a line that `p` lies across). +/// nearest `p` along it (none nearer than a line that `p` lies across). A line runs parallel when +/// it moves off its level by no more than 1e-6 pt across the span that both lines cover, so a line +/// at a slight angle to `d` is not a level however near its first end lies. A level that would put +/// the line past the limits a dimension allows is passed over. fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> Option<(Point, (Point, Point))> { if d.mode != DimensionMode::Linear { return None; @@ -538,14 +541,20 @@ fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> let (u, normal) = (d.direction(), d.normal()); let mut best: Option<(f64, f64, f64, (Point, Point))> = None; for &(ends, direction) in levels { - if u.cross(direction).abs() > 1e-6 { + let span = [ends.1, d.a, d.b].iter().map(|q| (*q - ends.0).dot(u).abs()).fold(1.0, f64::max); + let drift = u.cross(direction).abs() * span; + if !drift.is_finite() || drift > 1e-6 { continue; } let shift = (ends.0 - p).dot(normal); let (s0, s1) = ((ends.0 - p).dot(u), (ends.1 - p).dot(u)); let along = if s0 * s1 <= 0.0 { 0.0 } else { s0.abs().min(s1.abs()) }; if shift.is_finite() && along.is_finite() && shift.abs() <= reach && best.is_none_or(|(s, a, _, _)| (shift.abs(), along) < (s, a)) { - best = Some((shift.abs(), along, shift, ends)); + let mut placed = d.clone(); + placed.place(p + normal * shift); + if placed.validate().is_ok() { + best = Some((shift.abs(), along, shift, ends)); + } } } best.map(|(_, _, shift, ends)| (p + normal * shift, ends)) @@ -1123,8 +1132,9 @@ impl Tool for DimensionTool { out.extend(self.snap.guides().iter().cloned()); } // A dimension line placed on the level of another: one alignment guide across both lines, - // unless Alignment Guides are off. - if cx.alignment_guides + // unless Smart Guides or Alignment Guides are off. + if cx.smart_guides + && cx.alignment_guides && let (Some(d), Some((c, e))) = (&self.pending, self.level_guide) { let (a, b) = d.line_ends(); @@ -1189,6 +1199,58 @@ mod tests { } } + /// A line at a slight angle is not a level, even where its first end lies within reach across + /// the line: it moves off the level by 9 pt across the span. A line exactly parallel is. + #[test] + fn a_line_at_a_slight_angle_is_not_a_level() { + let pt = Point::new; + let d = + DimensionTool::default().recipe(DimensionMode::Linear, pt(10_000_050.0, 200.0), pt(10_000_150.0, 200.0), pt(10_000_100.0, 200.0), None); + let (from, to) = (pt(100.0, 170.0), pt(10_000_100.0, 179.0)); + let slanted = ((from, to), (to - from) / (to - from).hypot()); + assert!(line_level(&[slanted], &d, pt(10_000_100.0, 168.0), 4.0).is_none()); + let parallel = ((from, pt(10_000_100.0, 170.0)), Vec2::new(1.0, 0.0)); + let (at, _) = line_level(&[parallel], &d, pt(10_000_100.0, 168.0), 4.0).expect("on the level"); + assert!(at.distance(pt(10_000_100.0, 170.0)) < 1e-9, "{at:?}"); + } + + /// A level that would put the line past the largest distance a dimension allows is passed + /// over: the preview goes where the pointer is, with no level guide, or onto a level further + /// off within reach that keeps the line within the limit. + #[test] + fn a_level_past_the_distance_limit_is_passed_over() { + use vectorcraft_doc::{Node, NodeKind}; + let pt = Point::new; + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let add_level = |d: &mut vectorcraft_doc::Document, y: f64| { + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = + Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(380.0, y), pt(340.0, y), None))); + d.insert(Some(l), usize::MAX, drawn).unwrap(); + }; + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + // The points are at y = 400, so a line at y = 1,000,401 is 1,000,001 pt from them. + add_level(&mut d, 1_000_401.0); + for (also, offset) in [(None, 999_999.0), (Some(1_000_396.0), 999_996.0)] { + if let Some(y) = also { + add_level(&mut d, y); + } + let c = cx(&d, &s, &p); + let mut t = DimensionTool::default(); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + let acts = t.pointer(&c, &ev(PointerKind::Move, 420.0, 1_000_399.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + assert_eq!(params["offset"], json!(offset)); + assert_eq!(t.level_guide.is_some(), also.is_some()); + } + } + /// The lines of the dimensions in the document are read only for a linear dimension. They are /// read with Smart Guides off too, so a line placed after Smart Guides are turned on lines up. #[test] diff --git a/docs/dimensions.md b/docs/dimensions.md index bf6cf78653..75388109fd 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -78,8 +78,10 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers tolerance of the level of a parallel line of a linear dimension already drawn has its line on that level. The other dimension, and every layer and group it is in, must be visible and unlocked. The tool reads at most 20,000 visible, unlocked layers, groups and objects, from the - frontmost back, so in a larger document a dimension past them is not a level. This is - VectorCraft's own rule. With + frontmost back, so in a larger document a dimension past them is not a level. A line that + moves off its level by more than 0.000001 pt across the span of both lines is not parallel. A + level that would put the line more than 1,000,000 pt from its points is passed over, and the + line goes where the pointer is. This is VectorCraft's own rule. With Smart Guides and Alignment Guides on, a guide runs along the level across both lines while the dimension is placed. - **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two From e70ec2f136428c5f9c073aa24a17d5f9ec638d50 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:03:13 -0800 Subject: [PATCH 079/126] Gradient: freeform Lines mode counts a symbol's stroke on a Preview-off layer of its art The walk of a symbol instance's art switched to outline for a layer of the art whose Preview is off without checking ignore_layer_preview, so with the option set a press on the art's stroke past the instance's box missed. FindPart::find now checks the option, as the other point hit paths do. --- crates/doc/src/hit.rs | 2 +- crates/doc/src/hit/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 7c0de44cab..5d1d617f1b 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1793,7 +1793,7 @@ impl FindPart<'_> { if !n.visible || !self.whole_instance && (n.locked || n.is_template()) || self.skips_guide(n) || ArtWalk::used_up() { return None; } - let outline = outline || previews_off(n); + let outline = outline || !self.opt.ignore_layer_preview && previews_off(n); let opt = HitOptions { outline, ..self.opt }; let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) }; if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index ad037931a0..a5cc3c4424 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -2831,6 +2831,32 @@ fn a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box() { assert_eq!(at(108.0, HitOptions { outline: true, ..HitOptions::default() }), None, "Outline view"); } +/// A symbol's art on a layer of the symbol whose Preview is off is hit in outline, unless the +/// click sets [`HitOptions::ignore_layer_preview`]: then the stroke past the instance's box hits. +#[test] +fn ignore_layer_preview_reaches_symbol_art_on_a_preview_off_layer() { + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + // A 20 pt stroke reaches 10 pt past the 0..100 square. + let look = Appearance::basic(Paint::solid(Color::BLACK), Paint::solid(Color::BLACK), 20.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), look); + let mut layer = Node::layer(d.alloc_id(), "Art", crate::LayerColor::Preset(2)); + if let NodeKind::Layer { children, preview, .. } = &mut layer.kind { + *children = vec![Arc::new(square)]; + *preview = false; + } + let art = Node::group(d.alloc_id(), vec![Arc::new(layer)]); + d.symbols.push(crate::Symbol { dynamic: false, name: "Stroked".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let xf = vectorcraft_geom::Affine::IDENTITY; + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Stroked".into(), xf })).unwrap(); + let at = |x: f64, opt: HitOptions| hit_test(&d, Point::new(x, 50.0), opt).map(|h| h.leaf); + let painted = HitOptions { ignore_layer_preview: true, ..HitOptions::default() }; + assert_eq!(at(108.0, HitOptions::default()), None, "Preview off: in outline"); + assert_eq!(at(108.0, painted), Some(inst), "ignore_layer_preview: on the stroke past the box"); + assert_eq!(at(116.0, painted), None, "past the stroke"); +} + /// Outside a symbol instance's box, an instance nested in its art counts where its own art is, not /// anywhere in its box: a click or a marquee on empty space in the nested box, where a moved /// clipping path shows the art past the outer box, selects nothing, and on art drawn there it From 992f6b3fafddab334de2f2acf73a249cc465ecdc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:55:25 -0800 Subject: [PATCH 080/126] Script checker: setting length, hidden or readonly on new Folder(...) or a Folder place is not a file write script.check reported file.write and filesWritten when a script set length, hidden or readonly on a Folder object as well as on a File object. It now leaves out only objects that are Folder objects whatever the path names: new Folder(...), new Folder, and the Folder places such as Folder.temp, except Folder.current, which a script can assign. Folder(...) without new gives a File object when the path names a file, and Folder.selectDialog() gives a File or Folder object, so setting those still counts. A variable counts as a Folder only when every assignment the check reads gives it one: an assignment in another branch, in a function body, or in an included file that gives it an object that may be a File object keeps it counting, and a variable assigned another variable counts as a possible File object. A File object assigned to a function's own variable or parameter, or to a catch block's parameter, ends with them. Calls such as remove() on a Folder object still count as writes. Folder object constructors and selectDialog: https://extendscript.docsforadobe.dev/file-system-access/folder-object/ --- crates/scriptcheck/src/analyze.rs | 239 +++++++++++++++------ crates/scriptcheck/src/analyze/features.rs | 28 ++- crates/scriptcheck/src/analyze/sig.rs | 5 +- crates/scriptcheck/src/catalog.rs | 2 + crates/scriptcheck/src/tests.rs | 89 ++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 7 files changed, 299 insertions(+), 69 deletions(-) diff --git a/crates/scriptcheck/src/analyze.rs b/crates/scriptcheck/src/analyze.rs index b7c70345d0..5d01cc8438 100644 --- a/crates/scriptcheck/src/analyze.rs +++ b/crates/scriptcheck/src/analyze.rs @@ -46,21 +46,25 @@ pub(crate) struct IncludeRef { } /// What variables hold, as a check learns it: the member chains assigned to them, and the ones -/// holding a File or Folder object. +/// holding a File or Folder object, with the ones of those that every assignment the check read gave +/// a Folder object ([`Analyzer::folders`]). #[derive(Clone, Debug, Default)] pub(crate) struct Known { pub bound: HashMap, pub files: HashSet, + pub folders: HashSet, } impl Known { - /// The names known. + /// The names known, a name that may hold a File object counting twice: a Folder that becomes a + /// possible File object ([`Known::add`]) changes it too. pub fn len(&self) -> usize { - self.bound.len() + self.files.len() + self.bound.len() + self.files.len().saturating_mul(2).saturating_sub(self.folders.len()) } /// What `other` adds, up to [`crate::Limits::entries`] names of each kind: a name already - /// bound keeps its chain. + /// bound keeps its chain. A name that holds a File or Folder object on both sides holds a Folder + /// object only when both sides say so; otherwise it may hold a File object. pub fn add(&mut self, other: Known, entries: usize) { for (name, chain) in other.bound { if self.bound.len() < entries || self.bound.contains_key(&name) { @@ -68,7 +72,14 @@ impl Known { } } for name in other.files { - if self.files.len() < entries { + if self.files.contains(&name) { + if !other.folders.contains(&name) { + self.folders.remove(&name); + } + } else if self.files.len() < entries { + if other.folders.contains(&name) { + self.folders.insert(name.clone()); + } self.files.insert(name); } } @@ -255,10 +266,11 @@ struct Assign { after_new: bool, } -/// What a value the check follows holds: a member chain, or a File or Folder object. +/// What a value the check follows holds: a member chain, or a File or Folder object (`folder` when it +/// is a Folder object whatever the path names: [`Operand::file_step`]). enum Held { Chain(String), - File, + File { folder: bool }, } /// `name = (`: a value in grouping parentheses. Its value is the last operand in each pair (ECMA-262 @@ -302,8 +314,9 @@ enum Operand { FileMember { folder: bool }, /// `File.openDialog`, `File.saveDialog` or `Folder.selectDialog` came first: its `(` is next. FileDialog, - /// A call of `File`, `Folder` or one of their dialogs came first, and its `)` is still to come. - FileCall, + /// A call of `File`, `Folder` or one of their dialogs came first, and its `)` is still to come + /// (`folder` for `new Folder(…)`). + FileCall { folder: bool }, /// Grouping parentheses came first, and their `)` is still to come ([`Paren`] only). Pair, /// A member chain came first and is still being read. @@ -320,15 +333,23 @@ impl Operand { /// `Folder.selectDialog(…)`, `Folder.` ([`catalog::FOLDER_PLACES`]) or a variable holding /// one. `file`: `t` is the platform's `File` or `Folder`; `alias`: `t` names a variable holding a /// File or Folder object. + /// + /// Only `new Folder(…)`, `new Folder` and `Folder.` are Folder objects whatever the path + /// names. `Folder(…)` gives a File object when the path names a file, `Folder.selectDialog(…)` + /// gives a File or Folder object for what the user picks, `Folder.current` is the one place a + /// script can assign, and a variable another variable was assigned to may hold a File object. fn file_step(self, t: &Sig, file: bool, alias: bool) -> Operand { match self { Operand::Start if t.word("new") => Operand::New, Operand::Start if file => Operand::FileName { new: false, folder: t.text == catalog::FOLDER }, Operand::New if file => Operand::FileName { new: true, folder: t.text == catalog::FOLDER }, - Operand::Start if alias => Operand::Done(Held::File), - Operand::FileName { .. } | Operand::FileDialog if t.is("(") => Operand::FileCall, + Operand::Start if alias => Operand::Done(Held::File { folder: false }), + Operand::FileName { new, folder } if t.is("(") => Operand::FileCall { folder: new && folder }, + Operand::FileDialog if t.is("(") => Operand::FileCall { folder: false }, Operand::FileName { new: false, folder } if t.is(".") => Operand::FileMember { folder }, - Operand::FileMember { folder: true } if catalog::FOLDER_PLACES.contains(&t.text) => Operand::Done(Held::File), + Operand::FileMember { folder: true } if catalog::FOLDER_PLACES.contains(&t.text) => { + Operand::Done(Held::File { folder: t.text != catalog::FOLDER_CURRENT }) + } Operand::FileMember { folder } if (if folder { catalog::FOLDER_DIALOGS } else { catalog::FILE_DIALOGS }).contains(&t.text) => { Operand::FileDialog } @@ -337,9 +358,13 @@ impl Operand { } /// The operand is a File or Folder object when the `)` of its parentheses comes next: a complete - /// one, or `new File` or `new Folder` without arguments. - fn holds_file(&self) -> bool { - matches!(self, Operand::Done(Held::File) | Operand::FileName { new: true, .. }) + /// one, or `new File` or `new Folder` without arguments. `Some(true)` for a Folder object whatever + /// the path names. + fn held_file(&self) -> Option { + match self { + Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } => Some(*folder), + _ => None, + } } } @@ -458,6 +483,14 @@ struct Saved { chain: Option, /// It held a File or Folder object. file: bool, + /// It held a Folder object. + folder: bool, + /// It was in [`Analyzer::maybe_files`]. + maybe_file: bool, + /// The function body or `catch` block declares it, so whether an assignment in it gave the name + /// a value that may be a File object is put back too. For an outer name an assignment emptied, + /// that stays. + local: bool, /// For a root of the document model: whether the script's own variable hid the root. shadowed: Option, /// It was a platform name the script had a meaning of its own for. @@ -525,6 +558,14 @@ struct Analyzer<'s, 'a, 'l> { bound: HashMap, /// Variables holding a File or Folder object. files: HashSet, + /// The variables in `files` holding a Folder object whatever the path names ([`Held::File`]). + folders: HashSet, + /// The variables that an assignment in this scan or in what the scan started with gave a value + /// that may be a File object. Assignments in a branch or a function body are read in order, so + /// such a variable never counts as holding a Folder object ([`Analyzer::folder`]). + maybe_files: HashSet, + /// `maybe_files` ran out of room: no variable counts as holding a Folder object. + maybe_files_full: bool, /// The platform names ([`platform_name`]) the script declares or assigns a meaning of its own /// for: they no longer stand for the platform's objects. own_names: HashSet, @@ -551,8 +592,8 @@ struct Analyzer<'s, 'a, 'l> { /// block it names. catch_names: HashMap, /// The calls of `File`, `Folder` and their dialogs still open, by the bracket depth outside their - /// `(`, up to [`crate::Limits::nesting`] of them. - file_calls: Vec, + /// `(`, up to [`crate::Limits::nesting`] of them, each true for a call that gives a Folder object. + file_calls: Vec<(usize, bool)>, /// The values in grouping parentheses, the values without them that may hold a File, and the /// values of compound assignments, being read, the innermost last, up to /// [`crate::Limits::nesting`] of them. @@ -593,6 +634,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { shadowed: [false; 4], bound: known.bound.clone(), files: known.files.clone(), + folders: known.folders.clone(), + maybe_files: known.files.difference(&known.folders).cloned().collect(), + maybe_files_full: false, own_names: HashSet::new(), scopes: vec![], declared, @@ -685,9 +729,12 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let consumed = self.continue_chain(&t); let before = self.depth(); if t.kind == T::Punct { - t.file = self.bracket(&t); + let held = self.bracket(&t); + t.file = held.is_some(); + t.folder = held == Some(true); } else { t.file = self.folder_place(&t); + t.folder = t.file && t.text != catalog::FOLDER_CURRENT; } self.conditional(&t); self.add_parameter(&t); @@ -793,19 +840,37 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn bind(&mut self, name: String, path: String) { self.files.remove(&name); + self.folders.remove(&name); if self.bound.contains_key(&name) || self.acc.room(self.bound.len()) { self.bound.insert(name, path); } } - /// `name` holds a File or Folder object. - fn hold_file(&mut self, name: String) { + /// `name` holds a File or Folder object (`folder` for a Folder object whatever the path names). + fn hold_file(&mut self, name: String, folder: bool) { self.bound.remove(&name); + self.folders.remove(&name); + if !folder && !self.maybe_files.contains(&name) { + if self.acc.room(self.maybe_files.len()) { + self.maybe_files.insert(name.clone()); + } else { + self.maybe_files_full = true; + } + } if self.files.contains(&name) || self.acc.room(self.files.len()) { + if folder { + self.folders.insert(name.clone()); + } self.files.insert(name); } } + /// `name` holds a Folder object whatever the path names, and no assignment the check read gave it + /// a value that may be a File object. + fn folder(&self, name: &str) -> bool { + !self.maybe_files_full && self.files.contains(name) && self.folders.contains(name) && !self.maybe_files.contains(name) + } + /// `t`, when it names a parameter of the function whose body's `{` is still to come: kept, up to /// [`crate::Limits::entries`] of them, for the body to declare. A `catch` block's parameter is /// kept for the block. @@ -848,6 +913,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } + /// `name` is declared in the innermost function body (`var name`, `function name`, a + /// parameter): what it held outside is kept ([`Analyzer::keep_outer`]) as the body's own, and + /// the body's variable starts with no assignment read. + fn keep_own(&mut self, name: &str) { + self.keep_outer(name); + if let Some(saved) = self.scopes.last_mut().and_then(|s| s.saved.get_mut(name)) { + saved.local = true; + self.maybe_files.remove(name); + } + } + /// The names [`Declared`] has for the function body whose `{` starts at `start`. fn declared_in(&mut self, start: usize) -> &'a [&'s str] { let declared = self.declared; @@ -865,7 +941,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// outside is kept to put back when the body closes. A name the body's table has no room for /// stays as it is. fn hoist(&mut self, name: &str) { - self.keep_outer(name); + self.keep_own(name); if self.scopes.last().is_some_and(|s| s.saved.contains_key(name)) { self.empty(name); } @@ -889,7 +965,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// What `name` holds now. fn saved(&self, name: &str) -> Saved { let shadowed = catalog::DOM_ROOTS.iter().position(|r| *r == name).and_then(|i| self.shadowed.get(i).copied()); - Saved { chain: self.bound.get(name).cloned(), file: self.files.contains(name), shadowed, own: self.own_names.contains(name) } + Saved { + chain: self.bound.get(name).cloned(), + file: self.files.contains(name), + folder: self.folders.contains(name), + maybe_file: self.maybe_files.contains(name), + local: false, + shadowed, + own: self.own_names.contains(name), + } } /// `name` holds `saved` again. @@ -908,6 +992,16 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } else { self.files.remove(&name); } + if saved.folder { + self.folders.insert(name.clone()); + } else { + self.folders.remove(&name); + } + if saved.local && saved.maybe_file { + self.maybe_files.insert(name.clone()); + } else if saved.local { + self.maybe_files.remove(&name); + } if saved.own { self.own_names.insert(name.clone()); } else { @@ -961,6 +1055,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.make_own(name); self.bound.remove(name); self.files.remove(name); + self.folders.remove(name); self.hide_root(name); } @@ -975,9 +1070,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // ---------- brackets ---------- - /// An open or close bracket: true for the `)` that ends a call of `File` or `Folder`, or grouping - /// parentheses that hold a File or Folder object ([`Analyzer::close_parens`]). - fn bracket(&mut self, t: &Sig<'s>) -> bool { + /// An open or close bracket: `Some` for the `)` that ends a call of `File` or `Folder`, or grouping + /// parentheses that hold a File or Folder object ([`Analyzer::close_parens`]), `Some(true)` when + /// the object is a Folder object. + fn bracket(&mut self, t: &Sig<'s>) -> Option { match t.text { "(" | "[" | "{" => { if std::mem::take(&mut self.suspend) @@ -997,17 +1093,20 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The first `{` after `catch` and its parentheses at this depth opens its block. let depth = self.depth(); let catch = if t.text == "{" { self.catch.take().filter(|(d, _)| *d == depth).and_then(|(_, name)| name) } else { None }; - let file_call = t.text == "(" && self.calls_for_file(); - if file_call && self.file_calls.len() < self.acc.limits.nesting { - self.file_calls.push(self.depth()); + let file_call = if t.text == "(" { self.calls_for_file() } else { None }; + if let Some(folder) = file_call + && self.file_calls.len() < self.acc.limits.nesting + { + self.file_calls.push((self.depth(), folder)); } self.open(t); if let Some(name) = catch && self.catches.len() < self.acc.limits.nesting { - let saved = self.saved(&name); + let saved = Saved { local: true, ..self.saved(&name) }; let outer = self.catch_names.insert(name.clone(), self.depth()); self.empty(&name); + self.maybe_files.remove(&name); self.catches.push(Catch { depth: self.depth(), name, saved, outer }); } if params { @@ -1021,7 +1120,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The parameters are the body's own names, and so are the names it declares. for name in params { self.acc.steps = self.acc.steps.saturating_add(1); - self.keep_outer(&name); + self.keep_own(&name); self.unbind(&name); } for &name in self.declared_in(t.start) { @@ -1042,16 +1141,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } self.close_scopes(); let grouped = self.close_parens(t); - if t.text == ")" && self.file_calls.last() == Some(&self.depth()) { - self.file_calls.pop(); - return true; + let depth = self.depth(); + if t.text == ")" + && let Some((_, folder)) = self.file_calls.pop_if(|(d, _)| *d == depth) + { + return Some(folder); } return grouped; } } _ => {} } - false + None } fn open(&mut self, t: &Sig<'s>) { @@ -1071,18 +1172,18 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// A `(` here calls something that gives a File or Folder object: `File` or `Folder` (with or /// without `new`), or `File.openDialog`, `File.saveDialog` or `Folder.selectDialog`, each the - /// platform's. - fn calls_for_file(&self) -> bool { + /// platform's. `Some(true)` when it gives a Folder object whatever the path names: only + /// `new Folder(…)` ([`Operand::file_step`]). + fn calls_for_file(&self) -> Option { let [h0, h1, h2, h3] = self.h; let platform = |s: Option, name: &str| word(s, name) && !self.own_names.contains(name); - let constructor = (platform(h0, catalog::FILE) || platform(h0, catalog::FOLDER)) && !member_mark(h1); - let dialog = h0.filter(|s| s.kind == T::Ident).is_some_and(|m| { - is(h1, ".") - && !member_mark(h3) - && ((platform(h2, catalog::FILE) && catalog::FILE_DIALOGS.contains(&m.text)) - || (platform(h2, catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&m.text))) - }); - constructor || dialog + if (platform(h0, catalog::FILE) || platform(h0, catalog::FOLDER)) && !member_mark(h1) { + return Some(word(h0, catalog::FOLDER) && word(h1, "new")); + } + let m = h0.filter(|s| s.kind == T::Ident && is(h1, ".") && !member_mark(h3))?; + ((platform(h2, catalog::FILE) && catalog::FILE_DIALOGS.contains(&m.text)) + || (platform(h2, catalog::FOLDER) && catalog::FOLDER_DIALOGS.contains(&m.text))) + .then_some(false) } /// `t` names one of the platform's `Folder` places after `Folder.` (`Folder.temp`): a Folder @@ -1113,7 +1214,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if self.in_catch(name.text) { self.declare_in_catch(name.text); } else if self.scopes.last().is_some_and(|s| !s.saved.contains_key(name.text)) { - self.keep_outer(name.text); + self.keep_own(name.text); self.unbind(name.text); } } @@ -1140,7 +1241,15 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } }; let Some(c) = self.catches.get_mut(i) else { return }; - let empty = Saved { chain: None, file: false, shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), own: platform_name(name) }; + let empty = Saved { + chain: None, + file: false, + folder: false, + maybe_file: false, + local: false, + shadowed: catalog::DOM_ROOTS.contains(&name).then_some(true), + own: platform_name(name), + }; let outside = std::mem::replace(&mut c.saved, empty); if let Some(scope) = self.scopes.last_mut() { scope.saved.insert(name.to_string(), outside); @@ -1159,8 +1268,8 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { self.assign = Some(a); } else if (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text) { self.start_value(a.name, Operand::FileName { new: a.after_new, folder: t.text == catalog::FOLDER }); - } else if !a.after_new && t.kind == T::Ident && self.files.contains(t.text) { - self.start_value(a.name, Operand::Done(Held::File)); + } else if !a.after_new && self.alias(t) { + self.start_value(a.name, Operand::Done(Held::File { folder: false })); } else if !a.after_new && t.is("(") { self.start_group(a.name); } else { @@ -1257,14 +1366,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn group_step(&mut self, t: &Sig<'s>, started: bool, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = t.kind == T::Ident && self.files.contains(t.text); + let alias = self.alias(t); let Some(g) = self.groups.last_mut().filter(|g| !g.closed) else { return }; if after < g.level { // The `)` of the innermost pair: the operand, when complete, is the pair's value and the // operand of the pair around it. let held = match std::mem::replace(&mut g.operand, Operand::Other) { Operand::Done(held) => Some(held), - Operand::FileName { new: true, .. } => Some(Held::File), + Operand::FileName { new: true, folder } => Some(Held::File { folder }), _ => None, }; g.operand = held.map_or(Operand::Other, Operand::Done); @@ -1275,8 +1384,10 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { if before > g.level { // Inside a bracket of the operand: the `)` back at the pair's depth ends a call of `File`, // `Folder` or one of their dialogs. - if after == g.level && matches!(g.operand, Operand::FileCall) { - g.operand = Operand::Done(Held::File); + if after == g.level + && let Operand::FileCall { folder } = g.operand + { + g.operand = Operand::Done(Held::File { folder }); } return; } @@ -1313,7 +1424,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { fn paren_step(&mut self, t: &Sig<'s>, before: usize) { let after = self.depth(); let file = (t.word(catalog::FILE) || t.word(catalog::FOLDER)) && !self.own_names.contains(t.text); - let alias = t.kind == T::Ident && self.files.contains(t.text); + let alias = self.alias(t); if let Some(p) = self.parens.last_mut() { if before == p.level { p.operand = match std::mem::replace(&mut p.operand, Operand::Other) { @@ -1325,7 +1436,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { // The `)` of a call of `File`, `Folder` or a dialog, or of grouping parentheses, ends a // File or Folder object when [`Analyzer::bracket`] set its [`Sig::file`]. p.operand = match p.operand { - Operand::FileCall | Operand::Pair if t.file => Operand::Done(Held::File), + Operand::FileCall { .. } | Operand::Pair if t.file => Operand::Done(Held::File { folder: t.folder }), _ => Operand::Other, }; } @@ -1335,11 +1446,17 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } } - /// The grouping parentheses that the bracket `t` closed, if any (a bracket closes one level): true - /// when `t` is their `)` and their operand is a File or Folder object. - fn close_parens(&mut self, t: &Sig<'s>) -> bool { + /// The grouping parentheses that the bracket `t` closed, if any (a bracket closes one level): `Some` + /// when `t` is their `)` and their operand is a File or Folder object, `Some(true)` for a Folder + /// object. + fn close_parens(&mut self, t: &Sig<'s>) -> Option { let depth = self.depth(); - self.parens.pop_if(|p| depth < p.level).is_some_and(|p| t.is(")") && p.operand.holds_file()) + self.parens.pop_if(|p| depth < p.level).filter(|_| t.is(")")).and_then(|p| p.operand.held_file()) + } + + /// `t` names a variable holding a File or Folder object. + fn alias(&self, t: &Sig<'s>) -> bool { + t.kind == T::Ident && self.files.contains(t.text) } /// `t` follows the last `)` of a grouped value, or ends a value without parentheses at the depth @@ -1365,7 +1482,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let complete = (g.closed || g.bare) && ends; match g.operand { Operand::Done(Held::Chain(path)) if complete => self.bind(g.name, path), - Operand::Done(Held::File) | Operand::FileName { new: true, .. } if complete => self.hold_file(g.name), + Operand::Done(Held::File { folder }) | Operand::FileName { new: true, folder } if complete => self.hold_file(g.name, folder), _ => self.unbind(&g.name), } } @@ -1449,7 +1566,9 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { let bracket: &str = bracket.encode_utf8(&mut buf); self.acc.problem(report::UNCLOSED_BRACKET, Some(line), self.file, Some(bracket)); } - let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files) }; + // A variable that any assignment gave a value that may be a File object leaves as one. + let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect(); + let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders }; (std::mem::take(&mut self.includes), module, known) } } diff --git a/crates/scriptcheck/src/analyze/features.rs b/crates/scriptcheck/src/analyze/features.rs index 7bf8c9d203..19806fb9ad 100644 --- a/crates/scriptcheck/src/analyze/features.rs +++ b/crates/scriptcheck/src/analyze/features.rs @@ -136,12 +136,14 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { } /// `name`, a property of `receiver` read with `.` or as a string literal in brackets, `before` - /// coming before the receiver: when it is a File object's setter, the next token says whether it - /// is set ([`Pending::Setter`]). An update operator in `before` is a prefix (`++f.length`) when - /// the receiver is on its line, or when it starts a line or comes where an expression may start; - /// otherwise it ends the operand before it (`i++` and a line break, then `f.length`). + /// coming before the receiver: when it is the setter of an object that may be a File object (not + /// of one that is a Folder object whatever the path names), the next token says whether it is set + /// ([`Pending::Setter`]). An update operator in `before` is a prefix + /// (`++f.length`) when the receiver is on its line, or when it starts a line or comes where an + /// expression may start; otherwise it ends the operand before it (`i++` and a line break, then + /// `f.length`). fn setter(&mut self, name: &str, receiver: Option>, before: Option>, line: Option) { - if catalog::FILE_SETTERS.contains(&name) && self.file_receiver(receiver, before) { + if catalog::FILE_SETTERS.contains(&name) && self.held_file(receiver, before) == Some(false) { // Before a receiver that ends in `)` (`new File(i++).length`), the operator is inside the // parentheses. let update = before.filter(|b| (b.is("++") || b.is("--")) && receiver.is_some_and(|r| r.kind == T::Ident)); @@ -328,7 +330,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> { /// (not a property of the same name), or a File or Folder object made in place or held in /// grouping parentheses ([`Sig::file`]). fn file_receiver(&self, receiver: Option>, before: Option>) -> bool { - receiver.is_some_and(|r| r.file || (r.kind == T::Ident && !member_mark(before) && self.files.contains(r.text))) + self.held_file(receiver, before).is_some() + } + + /// What [`Self::file_receiver`] finds: `Some(true)` for a Folder object whatever the path names + /// ([`Sig::folder`], [`Analyzer::folder`]), `Some(false)` for an object that may be a File object, + /// and `None` for anything else. + fn held_file(&self, receiver: Option>, before: Option>) -> Option { + let r = receiver?; + if r.file { + Some(r.folder) + } else if r.kind == T::Ident && !member_mark(before) && self.alias(&r) { + Some(self.folder(r.text)) + } else { + None + } } fn string(&mut self, t: &Sig<'s>, line: Option) { diff --git a/crates/scriptcheck/src/analyze/sig.rs b/crates/scriptcheck/src/analyze/sig.rs index 1cde2df0fe..edcb642cc5 100644 --- a/crates/scriptcheck/src/analyze/sig.rs +++ b/crates/scriptcheck/src/analyze/sig.rs @@ -14,6 +14,9 @@ pub(super) struct Sig<'s> { /// name in `Folder.temp` and the other places of [`catalog::FOLDER_PLACES`], or the `)` of /// grouping parentheses that hold only such an object or a variable holding one (`(f)`). pub(super) file: bool, + /// The object that [`Sig::file`] marks the end of is a Folder object whatever the path names: + /// `new Folder(…)`, a place of [`catalog::FOLDER_PLACES`], or grouping parentheses that hold one. + pub(super) folder: bool, /// A statement may start at the token ([`crate::lex::Token::stmt`]). pub(super) stmt: bool, /// An expression may start at the token ([`crate::lex::Token::expr`]). @@ -25,7 +28,7 @@ pub(super) struct Sig<'s> { impl<'s> Sig<'s> { /// The significant token `t`, after a line break when `nl` is set. pub(super) fn of(t: &Token<'s>, nl: bool) -> Self { - Sig { kind: t.kind, text: t.text, line: t.line, nl, file: false, stmt: t.stmt, expr: t.expr, start: t.start } + Sig { kind: t.kind, text: t.text, line: t.line, nl, file: false, folder: false, stmt: t.stmt, expr: t.expr, start: t.start } } pub(super) fn is(&self, punct: &str) -> bool { diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..0045c764f2 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -40,6 +40,8 @@ pub(crate) const FOLDER_DIALOGS: &[&str] = &["selectDialog"]; pub(crate) const INSTANCE_DIALOGS: &[&str] = &["openDlg", "saveDlg", "selectDlg"]; pub(crate) const FOLDER_PLACES: &[&str] = &["appData", "appPackage", "commonFiles", "current", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; +/// The `Folder` place a script can assign. +pub(crate) const FOLDER_CURRENT: &str = "current"; pub(crate) const EXECUTE: &str = "execute"; pub(crate) const OPEN: &str = "open"; /// The open modes that write: write, append and edit. diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..b771cc6417 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -564,6 +564,95 @@ fn setting_a_files_length_or_flags_writes_it() { assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[2, 3, 4, 5, 6, 7, 8, 10, 12][..])); } +/// `new Folder(…)` and the `Folder` places always give a Folder object, which has no `length`, +/// `hidden` or `readonly` setter. `Folder(…)` gives a File object when the path names a file, +/// `Folder.selectDialog()` gives a File or Folder object, and a variable assigned another variable +/// may hold either, so setting those writes. Removing a folder still writes. +#[test] +fn setting_a_folders_length_or_flags_does_not_write() { + let r = report(concat!( + "var d = new Folder(p);\n", + "d.length = 0;\n", + "d.hidden = true;\n", + "Folder.temp.length = 0;\n", + "(new Folder(q)).length = 0;\n", + "(Folder.desktop)['readonly'] = true;\n", + "Folder(p).readonly = true;\n", + "var e = Folder.selectDialog();\n", + "e.length = 0;\n", + "var g = (d);\n", + "g['length'] = 0;\n", + "var h = Folder(p);\n", + "h.hidden = true;\n", + "(Folder(p)).length = 0;\n", + "d.remove();\n", + "Folder.current.hidden = true;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[7, 9, 11, 13, 14, 15, 16][..])]); + assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[7, 9, 11, 13, 14, 15, 16][..])); +} + +/// A File object assigned to a function's own variable, its parameter or a `catch` block's +/// parameter ends with them; one assigned to an outer variable stays. Such a variable or parameter +/// starts without what the outer variable of the same name was assigned. +#[test] +fn a_file_in_a_local_variable_leaves_an_outer_folder_alone() { + let r = report(concat!( + "var d = new Folder(p);\n", + "function f(e) { var d = new File(q); e = new File(q); d.length = 0; }\n", + "var e = new Folder(p);\n", + "try { x(); } catch (d) { d = new File(q); }\n", + "d.length = 0; e.hidden = true;\n", + "var g = new Folder(p);\n", + "function h() { g = y(); g = new File(q); }\n", + "g.length = 0;\n", + "var k = new File(q);\n", + "function m(n) { var k = new Folder(p); k.length = 0; n = new Folder(p); n.hidden = true; }\n", + "try { x(); } catch (k) { k = new Folder(p); k.readonly = true; }\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2, 8][..])]); +} + +/// The check reads branches and function bodies in order, so a variable that any assignment gives an +/// object that may be a File object keeps counting as one, in the same file, in a function the code +/// after it assigns, and across included files. +#[test] +fn a_variable_that_may_hold_a_file_counts_as_one() { + let r = report(concat!( + "var d;\n", + "if (c) { d = new File(p); } else { d = new Folder(p); }\n", + "d.length = 0;\n", + "function w() { h.hidden = true; }\n", + "var h = new Folder(q);\n", + "if (c) h = File(p);\n", + "var k = new Folder(q);\n", + "k.length = 0;\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3, 4][..])]); + for lib in ["d = new File(q);\n", "d = Folder.selectDialog();\n", "var x = new File(q); d = x;\n"] { + let mut m = mem(&[("lib.jsxinc", lib)]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[3][..])], "{lib}"); + } + // The function that may give `d` a File object only does so once `e` holds one, which the + // second scan learns. + let r = report(concat!( + "var d = new Folder(p);\n", + "function write() { d.length = 0; }\n", + "function assign() { d = e; }\n", + "var e = new File(q);\n", + )); + let outside: Vec<(&str, &[usize])> = r.outside.iter().map(|o| (o.id, o.lines.as_slice())).collect(); + assert_eq!(outside, [("filesWritten", &[2][..])]); + let mut m = mem(&[("lib.jsxinc", "d = Folder.temp;\n")]); + let r = check("main.jsx", b"#include 'lib.jsxinc'\nvar d = new Folder(p);\nd.length = 0;\n", Some(&mut m), &Limits::default()); + assert!(r.outside.is_empty(), "{:?}", r.outside); +} + #[test] fn a_function_after_a_line_that_ends_a_statement_is_a_declaration() { let r = report("var n = 1\nfunction File() {}\nFile('x');\nvar m = 2 /* a\n */ function Socket() {}\nnew Socket();\n"); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..d120aa130c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2558,7 +2558,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, (`app.executeMenuCommand('…')`), each with a count and its lines, and `menuCommands.dynamic` counts the calls whose argument isn't a string literal. - `outside` lists what the script does outside the document: `filesWritten` (with the open modes used; setting a - File object's `length`, `hidden` or `readonly` counts too), `filesOpened` (files opened in other apps), `network`, + File object's `length`, `hidden` or `readonly` counts too, on any object that may be a File object; only + `new Folder(…)` and the `Folder` places such as `Folder.temp`, other than `Folder.current`, are left out), `filesOpened` (files opened in other apps), `network`, `nativeCode`, `otherApps` (messages to other apps), `environment` (environment variables), `unseenCode` (`eval`, `new Function` and `$.evalFile`) and `preferences` (the reference app's preferences changed). - `problems` lists what would stop the script loading as written (strings, comments, regular expressions, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..4a1a91589d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1071,7 +1071,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`). - File › Scripts › Check Script… reads a script written for Illustrator (`.jsx`, `.jsxinc` or a compiled `.jsxbin`) without running any of it and reports what it needs (the document model, files, dialogs, menu commands, features only Illustrator has), what it would do outside the document, the menu commands and document-model members it uses, its directives and included files, and the problems that would stop it loading (`script.check`, which also reads `.js` files); File › Open and drag-and-drop show the report for `.jsx`, `.jsxinc` and `.jsxbin` files. - Check Script reads names by the same identifier rule as `vectorcraft-js`: Unicode 17.0 `ID_Start` characters, `$` and `_` start a name, and `ID_Continue` characters and `$` continue it (https://www.unicode.org/reports/tr31/, https://tc39.es/ecma262/#sec-names-and-keywords). U+2118, U+203F, U+00B7 and the zero width non-joiner and joiner are name characters, and U+00B2 and U+2E2F are not. Of the characters Unicode 17.0 assigned, U+088F starts a name and U+1ACF may follow its first character. A `\uXXXX` escape is read as its character only where a name may hold it, so `\u0030abc` does not become a name that starts with a digit; a `\u{…}` escape takes any number of hexadecimal digits up to U+10FFFF, and one that is empty, unclosed, out of range or a surrogate is not part of a name. Each `\u{…}` escape read in a name is reported as syntax newer than ES3, which has only the four-digit form (https://ecma-international.org/wp-content/uploads/ECMA-262_3rd_edition_december_1999.pdf, section 7.6). A private name may start with an escape (`this.#\u{61}pp` is the private name `#app`), and a private name at the start of a line inside braces is not read as a directive unless its name is a directive's. Tests: `crates/scriptcheck/src/tests.rs` (`names_are_made_of_the_unicode_identifier_characters`, `an_escape_stands_for_a_character_only_where_a_name_may_hold_it`, `braced_escapes_in_names_are_read_by_their_value`, `braced_name_escape_reports_later_syntax_and_member`, `private_names_with_escaped_starts_are_single_tokens`, `private_name_at_line_start_is_not_a_directive`), `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs` (`both_lexers_take_the_same_characters_into_names`). - - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). + - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. From 57dbc644a423915d59d1a9e1c0072fd2f62a45dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:23:35 -0800 Subject: [PATCH 081/126] Window: a restored window fitted to a small work area is not held at the minimum size When the work area is smaller than the smallest window (800 x 500 points), `place` fits the restored window to it, but the native minimum inner size from `native_options` stayed at 800 x 500, so the system kept the window bigger than the work area. `restore` now lowers the minimum to the fitted size in each dimension where it is smaller, and keeps the normal minimum where the work area has room for it. --- apps/vectorcraft/src/window.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/apps/vectorcraft/src/window.rs b/apps/vectorcraft/src/window.rs index ce224584fd..e36add3d08 100644 --- a/apps/vectorcraft/src/window.rs +++ b/apps/vectorcraft/src/window.rs @@ -170,6 +170,12 @@ fn fit(size: [f32; 2], room: [f32; 2]) -> [f32; 2] { std::array::from_fn(|i| size[i].min(room[i]).max(MIN_SIZE[i].min(room[i])).max(1.0)) } +/// The smallest size a window of `size` points may take: [`MIN_SIZE`], lowered to `size` in each +/// dimension where [`fit`] made the window smaller than that to fit a small work area. +fn min_size(size: [f32; 2]) -> [f32; 2] { + std::array::from_fn(|i| MIN_SIZE[i].min(size[i])) +} + /// Whether to list the monitors again: on the first frame, when the UI zoom changed, and at most /// every [`MONITORS_EVERY`] seconds while the app draws. `listed` holds the last list's time and zoom. pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool { @@ -302,6 +308,12 @@ pub fn restore(window: &winit::window::Window, saved: Option) -> if let Some([x, y]) = g.pos { window.set_outer_position(PhysicalPosition::new(x, y)); } + // The native minimum (`MIN_SIZE`, set in `native_options`) would keep the window bigger than a + // size fitted to a small work area, so it is lowered to that size first. + let min = min_size(g.size); + if min != MIN_SIZE { + window.set_min_inner_size(Some(LogicalSize::new(min[0], min[1]))); + } // Returns the new size when it applies at once; either way the window gets it. let _ = window.request_inner_size(LogicalSize::new(g.size[0], g.size[1])); #[cfg(not(target_os = "linux"))] @@ -444,6 +456,21 @@ mod tests { assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None); } + #[test] + fn a_window_fitted_below_the_smallest_size_lowers_the_minimum_to_its_size() { + // 1366 × 768 at 150% with a 48-pixel taskbar along the bottom: a work area 480 points high. + let areas = [WorkArea { monitor: [0, 0, 1366, 768], work: [0, 0, 1366, 720] }]; + let m = [monitor(0, 0, 1366, 768, 1.5).with_work_area(&areas)]; + let g = place(saved(Some([0, 0]), [900.0, 500.0], false), &m, Some(0)); + assert_eq!(g.size, [900.0, 480.0]); + // The minimum height drops to the fitted 480 points; the width keeps the normal minimum. + assert_eq!(min_size(g.size), [800.0, 480.0]); + // A window with room for the smallest size keeps the normal minimum. + let big = [monitor(0, 0, 1920, 1080, 1.0)]; + assert_eq!(min_size(place(saved(Some([0, 0]), [1000.0, 700.0], false), &big, Some(0)).size), MIN_SIZE); + assert_eq!(min_size([1.0, 1.0]), [1.0, 1.0]); + } + #[test] fn macos_screen_rects_turn_into_winits_top_left_pixels() { // A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock, From b461422beed65b166c79382ecc3c60ba9d8739ca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:15:36 -0800 Subject: [PATCH 082/126] Live Paint: freeform point edits without a target leave the selection alone under the bucket While the proxies show the colors the Live Paint Bucket paints with, `paint.freeform.get` and `paint.freeform.selectPoint` with an index find no freeform gradient. The point and line edits (`addPoint`, `setPoint`, `deletePoint`, `addLine`, `splitLine`) still edited the selected object's freeform gradient when they named no target. Those edits now report an error then, when no `ids`, `id` or `item` is given, as the other paint commands leave the selection alone. A bad `aligned` or `target` is still reported first. With a target they edit that object as before. `get` and `selectPoint` now say that the bucket's colors have no freeform points instead of suggesting `paint.editGradient`. The params text and docs/mcp.md describe the rule. --- crates/engine/src/cmd/freeform.rs | 34 ++++++++++++++++++++-------- crates/engine/src/tests/freeform.rs | 35 +++++++++++++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index b238dd865a..548e5fade2 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it; an error while the proxies show the Live Paint Bucket's colors and no ids, id or item are given → {index}", has_doc, split_line ), @@ -64,7 +64,7 @@ pub fn specs() -> Vec { "Select Freeform Point", [], None, - "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", + "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's; an index is an error while the proxies show the Live Paint Bucket's colors): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}", has_doc, select_point ), @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Freeform Gradient", [], None, - "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", + "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object (an error while the proxies show the Live Paint Bucket's colors) → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}", has_doc, get ), @@ -81,6 +81,14 @@ pub fn specs() -> Vec { } const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})"; +const BUCKET_NOT_FREEFORM: &str = "the Live Paint Bucket's colors have no freeform points (give ids, id or item to edit an object's)"; +const BUCKET_NO_POINTS: &str = "the Live Paint Bucket's colors have no freeform points"; + +/// The error of `paint.freeform.get` and `paint.freeform.selectPoint` when the active proxy shows no freeform gradient: +/// while the Live Paint Bucket paints, the proxies show its colors, which have none. +fn no_proxy_freeform(s: &Session) -> &'static str { + if s.bucket_paints() { BUCKET_NO_POINTS } else { NOT_FREEFORM } +} impl Session { /// The selected freeform point (`paint.freeform.selectPoint`), while the gradient it was @@ -179,6 +187,14 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result { /// as one undo step; returns what it returned for the first. An unplaced gradient gets the /// automatic points it shows first, and the stops follow the points' colours. fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result) -> Result { + // While the Live Paint Bucket paints, the proxies show its colors, which have no freeform points + // (paint.freeform.get finds none): an edit that names no target is refused. A bad `aligned` or + // `target` is refused first, as it is without the bucket. + if super::paint::for_bucket(s, p) { + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; + return Err(bad(cmd, BUCKET_NOT_FREEFORM)); + } let item = item_target(s, p, cmd)?; let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?; let item = item.of_kind(s, !stroke); @@ -331,7 +347,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { Some(Value::Null) => None, Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`index` must be a whole number or null"))?; - let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, NOT_FREEFORM))?; + let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; check_index(&f, i).map_err(|e| bad(C, e))?; Some(i) } @@ -343,7 +359,7 @@ fn select_point(s: &mut Session, p: &Value) -> Result { fn get(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.freeform.get"; let stroke = switch_or(p, "stroke", !s.fill_active, C)?; - let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, NOT_FREEFORM))?; + let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, no_proxy_freeform(s)))?; let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None }; let mut v = vectorcraft_tools::params::freeform_json(&f); v["selected"] = json!(selected); diff --git a/crates/engine/src/tests/freeform.rs b/crates/engine/src/tests/freeform.rs index 4e65c86894..99810296ef 100644 --- a/crates/engine/src/tests/freeform.rs +++ b/crates/engine/src/tests/freeform.rs @@ -283,6 +283,41 @@ fn point_commands_need_a_freeform_gradient() { assert!(s.execute("paint.freeform.addPoint", &json!({"at": [1, 1]})).is_err()); } +/// While the Live Paint Bucket is the active tool, the point and line commands that name no `ids`, +/// `id` or `item` leave a selected freeform fill as it is and report an error, as +/// `paint.freeform.get` finds no freeform gradient then. With `ids` they edit that object. `get` and +/// `selectPoint` with an index name the bucket's colors in their error. +#[test] +fn point_commands_without_a_target_leave_the_selection_alone_under_the_bucket() { + let (mut s, id) = freeform_rect(); + run(&mut s, "paint.freeform.addLine", json!({"points": [0, 1]})); + run(&mut s, "paint.freeform.selectPoint", json!({"index": 1})); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + // get and selectPoint with an index name the bucket's colors; clearing the point still works. + for (cmd, p) in [("paint.freeform.get", json!({})), ("paint.freeform.selectPoint", json!({"index": 0}))] { + let err = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(err.contains("Live Paint Bucket"), "{cmd}: {err}"); + } + run(&mut s, "paint.freeform.selectPoint", json!({"index": null})); + let before = points(&s, id); + // A bad `aligned` is reported as such, before the missing target. + let err = s.execute("paint.freeform.addPoint", &json!({"at": [150, 150], "aligned": 3})).unwrap_err().to_string(); + assert!(err.contains("aligned"), "{err}"); + for (cmd, p) in [ + ("paint.freeform.addPoint", json!({"at": [150, 150]})), + ("paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000"})), + ("paint.freeform.deletePoint", json!({"index": 0})), + ("paint.freeform.addLine", json!({"points": [1, 2]})), + ("paint.freeform.splitLine", json!({"line": 0, "segment": 0})), + ("paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000", "ids": null})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + assert_eq!(points(&s, id), before, "{cmd} {p}: the object's points"); + } + run(&mut s, "paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000", "ids": [id.0]})); + assert_ne!(points(&s, id), before, "with ids the object's point changes"); +} + /// The point and line commands refuse a point, line or segment of 2^32 + k, where k names one that /// exists, and the points and the selected point stay as they were. A 32-bit build read the number /// as k. diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..771463bbc9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4857,7 +4857,9 @@ already walks Image Trace. Short agent entry points: `tool.setOption {tool: "eyedropper", values: {stop: "livePaintBucket"}}`): the stop stays selected, and the click's `paint.sampleColor {color, stop}` recolors that stop of the bucket's gradient and leaves the selection's paint as it is. Once that stop is no longer selected (a Cmd/Ctrl-click selected another - object), the next click ends the pick without sampling and switches back to the bucket. + object), the next click ends the pick without sampling and switches back to the bucket. The bucket's colors have no + freeform points: `paint.freeform.get`, and `paint.freeform.selectPoint` with an `index`, report an error, and so do + the other `paint.freeform` commands without `ids`, `id` or `item`, which then leave the selection's gradient as it is. With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or `paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the From acc07f19d6a07aa41e00e749f8d5dbcbb51b5162 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:00:16 -0800 Subject: [PATCH 083/126] Links: Unembed leaves a released or edited clipping mask as it is Unembed re-applied the clipping path read back from the PNG or TIFF it had just written, with a path and with a folder. A clipping mask released in the document came back, and a mask edited in the document got a clip group of the file's original path nested inside it. The same held for a distorted image. Unembed now leaves a clipping mask released, edited or made in the document as it is. A clip group of the file's own clipping path still follows the file written, as before. --- crates/engine/src/cmd/fileio/tests_psdread.rs | 72 +++++++++++++++++++ crates/engine/src/cmd/links.rs | 42 ++++++++--- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 109 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 7a56932aed..37f4b132b5 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -863,6 +863,78 @@ fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { } } +/// Unembed leaves a clipping mask released or edited in the document as it is, with a path and with +/// a folder, for a plain image and for a distorted one: no clip group of the file's clipping path is +/// put back or nested inside the edited mask. Every case runs, and the test names each one that +/// fails. +#[test] +fn unembed_keeps_a_released_or_edited_clipping_mask() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-mask"); + let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources())); + let cases = ["release", "move"] + .into_iter() + .flat_map(|edit| [false, true].into_iter().flat_map(move |distort| [(edit, distort, false), (edit, distort, true)])); + let failed: Vec<_> = cases + .filter(|&(edit, distort, folder)| { + std::panic::catch_unwind(|| unembed_mask_case(&dir.join(format!("{edit}-{distort}-{folder}")), &data, edit, distort, folder)).is_err() + }) + .collect(); + assert!(failed.is_empty(), "failed: {failed:?}"); +} + +/// One case of [`unembed_keeps_a_released_or_edited_clipping_mask`]: the clipping mask of a placed +/// PSD file's image released or moved (`edit`), the image or the clip group then distorted with +/// `distort`, and the image unembedded into `out`. +fn unembed_mask_case(out: &std::path::Path, data: &str, edit: &str, distort: bool, folder: bool) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + if edit == "release" { + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.clippingMask.release", &json!({})).unwrap(); + } else { + let Some(NodeKind::Group { children, .. }) = s.doc().unwrap().doc.node(group).map(|n| &n.kind) else { panic!("a clip group") }; + let mask = children[0].id; + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap(); + } + if distort { + let target = if edit == "release" { image } else { group }; + s.execute("select.set", &json!({"ids": [target.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image(), "{edit}, folder: {folder}: distorted"); + } + let parent = |s: &Session| s.doc().unwrap().doc.parent_of(image); + let before = (parent(&s), parent(&s).and_then(|p| s.doc().unwrap().doc.node(p).cloned())); + std::fs::create_dir_all(out).unwrap(); + if folder { + s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + } else { + s.execute("links.unembed", &json!({"id": image.0, "path": out.join("cut")})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "{edit}, folder: {folder}: linked to the file written"); + assert_eq!(parent(&s), before.0, "{edit}, folder: {folder}: the image stays where it was"); + let after = before.0.and_then(|p| d.node(p)); + match (edit, after.map(|n| &n.kind), before.1.as_ref().map(|n| &n.kind)) { + // Released: the image is in no clip group, as before. + ("release", Some(NodeKind::Group { clip, .. }), _) => assert!(!clip, "folder: {folder}: the released mask came back"), + ("release", _, _) => {} + // Moved: the same clip group of the moved path holds just the image. + (_, Some(NodeKind::Group { children: a, clip: true }), Some(NodeKind::Group { children: b, clip: true })) => { + assert_eq!(a.len(), 2, "{edit}, folder: {folder}: a clip group was nested inside the edited mask"); + let path = |c: &std::sync::Arc| match &c.kind { + NodeKind::Path { path, .. } => path.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect::>(), + _ => vec![], + }; + assert_eq!((path(&a[0]), a[1].id), (path(&b[0]), image), "{edit}, folder: {folder}: the clipping mask"); + } + other => panic!("{edit}, folder: {folder}: {other:?}"), + } +} + /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a /// text chunk within the size limit that reads as a path gives one back. #[test] diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fccff66c0c..29da4d0524 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path 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", + "{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. A clipping mask released, edited or made in the document stays as it is, in either case. 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 ), @@ -1264,7 +1264,31 @@ fn warped(path: &PathData, map: &Homography) -> Option { /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that /// show that content. -fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { +fn install(d: &mut Document, ids: &[NodeId], read: FileRead, force: Option, also: Option<(&str, &str)>) -> Result<()> { + install_with(d, ids, read, force, also, false) +} + +/// What Unembed (`unembed`) does with the clip `to` of an image whose clip group holding just it +/// has a clipping path (`held`): a clipping mask released, edited or made in the document stays as +/// it is, and only a clip group of the old file's own clipping path follows the file written. +fn unembed_clip(to: ClipTo, held: bool) -> ClipTo { + match to { + ClipTo::Nest(_) => ClipTo::Keep, + ClipTo::File(_) if !held => ClipTo::Keep, + to => to, + } +} + +/// As [`install`]; with `unembed`, each clip goes through [`unembed_clip`]. +fn install_with( + d: &mut Document, + ids: &[NodeId], + (link, img): FileRead, + force: Option, + also: Option<(&str, &str)>, + unembed: bool, +) -> Result<()> { + let keep = |to: ClipTo, held: bool| if unembed { unembed_clip(to, held) } else { to }; let new_pt = super::place::pt_per_px(img.ppi); let mut clips = vec![]; let nested = nested_ids(d, ids); @@ -1290,7 +1314,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio _ => None, }; let clip = refill_distorted(&mut n, old_clip.as_ref(), &link, &img, held); - return (n, clip); + return (n, keep(clip, held.is_some())); } if let NodeKind::Image(im) = &mut n.kind { let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; @@ -1300,7 +1324,7 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio None => (super::place::pt_per_px(None), None), }; let (xf, c) = placed_xf(im.xf, size(im.width, im.height), old_pt, size(img.width, img.height), new_pt, o); - clip = clip_to(im.xf, old_clip, c, &img, xf, held); + clip = keep(clip_to(im.xf, old_clip, c, &img, xf, held), held.is_some()); (im.key, im.width, im.height, im.xf, im.link) = (img.key.clone(), img.width, img.height, xf, Some(link.clone())); } (n, clip) @@ -1315,7 +1339,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio }; 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))))); + let clip = refill_distorted(n, old_clip.as_ref(), &link, &img, held.as_ref().map(|(path, rule)| (path, *rule))); + clips.push((*id, keep(clip, held.is_some()))); } continue; } @@ -1326,7 +1351,8 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio // Placement Options' clip, else the clipping path of a DCS file (read again with its // plates) or of a PSD or PSB file. let old_clip = d.images.get(&im.key).and_then(file_clip); - clips.push((*id, clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, clip_path_of(d, *id)))); + let held = clip_path_of(d, *id); + clips.push((*id, keep(clip_to(im.xf, old_clip.as_ref(), clip, &img, xf, held), held.is_some()))); if let Some(n) = d.node_mut(*id) && let NodeKind::Image(im) = &mut n.kind { @@ -2829,7 +2855,7 @@ fn unembed(s: &mut Session, p: &Value) -> Result { write_file(&path, &bytes)?; let read = (link_info(&path, &bytes), img); drop(doc); - s.edit("Unembed", |d, _| editing_brush_art(d, |d| install(d, &[id], read, Some(Preserve::Bounds), None)))?; + s.edit("Unembed", |d, _| editing_brush_art(d, |d| install_with(d, &[id], read, Some(Preserve::Bounds), None, true)))?; Ok(json!({ "id": id.0, "path": path })) } @@ -2896,7 +2922,7 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re drop(doc); let done: Vec = reads.iter().map(|(id, (l, _))| json!({ "id": id.0, "path": l.path })).collect(); let edited = s.edit("Unembed", |d, _| { - editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install(d, &[id], read, Some(Preserve::Bounds), None))) + editing_brush_art(d, |d| reads.into_iter().try_for_each(|(id, read)| install_with(d, &[id], read, Some(Preserve::Bounds), None, true))) }); if let Err(e) = edited { remove_written(&written); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..0f9f86dbcc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9899,7 +9899,8 @@ file is missing stays linked: relink it first); `links.unembed {id, path}` write (another extension converts it) and links to it, and without `path` returns `{name, dataBase64}`. An image from a PSD or PSB file written as stored (PNG, or TIFF for a CMYK file), with `path` or `folder`, keeps the clip group of the clipping path that file names, and the file written keeps the path: Open, Place, Relink and Update Links read the file -with its clip group. +with its clip group. A clipping mask released, edited or made in the document stays as it is, whatever format the +image is written in. `ids` of one image works as `id` does. `links.unembed {ids?, folder}` writes each embedded image of `ids` (or of `id`; default: the selected embedded images) to a new file in `folder`, in the format it is stored in (as PNG when that format is not one of VectorCraft's raster file formats), and links each image to its file, keeping its bounds, in one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..7ec540063d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2325,7 +2325,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). + - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group and leaves a clipping mask released, edited or made in the document as it is, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). The import fuzz tests open, count and place PSD files whose resource 1050 is in version 6 (with a version 16 descriptor after a record) and in the descriptors of versions 7 and 8, with their data mutated, cut short with the resource's length saying so, and cut short in the file; a slice count past 10,000 or past the slices stored, and data one byte short, bring the art in without its slices and with a warning. `tests_psdslices::damaged_slices_never_panic` now fails when a command reports an internal error (`import_fuzz::the_sliced_psd_samples_bring_in_their_user_slices`, `import_fuzz::sliced_psd_samples_with_huge_counts_or_cut_short_come_in_without_their_slices`, `import_fuzz::mutated_psd_slices_never_panic`). Scores and estimates unchanged. - PSD export writes slices: the user and object slices that reach into the exported artboard go into image resource 1050 in version 6, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it and as Import Slices reads it, so an opened PSD file's slices survive its export. VectorCraft's own rules: slices are written with Write Layers and as a flat image alike, clipped to the artboard in its pixels; an object slice is written as a user slice over its object's bounds, and an HTML Text slice as No Image with its type's text; auto slices are left out and laid out again on open; text alignment is written as the default (`crates/render/src/encode/tests_psd.rs`, `crates/engine/src/cmd/fileio/tests_psdslices.rs`). From c7a3b0746564144d480a569d3237b9a523e7e110 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:41:21 -0800 Subject: [PATCH 084/126] Eyedropper: sampling into a stop of given objects reads their gradient `paint.sampleColor` with `stop` and objects in `ids` took the stop list from the gradient behind the proxy: the selection's, or the Live Paint Bucket's while it was active. With the bucket on a solid color it refused a valid target, and with another gradient behind the proxy it copied that gradient's stops onto the given objects. The stop list now comes from the topmost fill (or stroke) of the first object `paint.editGradient` edits for those ids (a compound path for its member, a group's first painted object), whatever tool is active. Without objects in `ids`, the gradient behind the proxy is used as before. The params text and docs/mcp.md describe the rule. --- crates/engine/src/cmd/xform.rs | 32 ++++++++++++++++--- crates/engine/src/tests/gradpanel.rs | 47 ++++++++++++++++++++++++++++ docs/mcp.md | 4 ++- 3 files changed, 78 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index ba8f7e94ab..006f39ac19 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), @@ -529,9 +529,15 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { Some(v) => { let i = v.as_u64().map(index).ok_or_else(|| bad(C, "`stop` must be a stop index"))?; let color = super::paint::new_color(s, p, color_value(c).ok_or_else(|| bad(C, format!("bad color {c}")))?); - let (fill, stroke_paint) = s.proxy_paints(); - let Paint::Gradient(g) = (if stroke { stroke_paint } else { fill }) else { - return Err(bad(C, "the paint behind the proxy is not a gradient")); + let (paint, source) = match given_stop_paint(s, p, stroke)? { + Some(paint) => (paint, "the paint of the first object in `ids`"), + None => { + let (fill, stroke_paint) = s.proxy_paints(); + (if stroke { stroke_paint } else { fill }, "the paint behind the proxy") + } + }; + let Paint::Gradient(g) = paint else { + return Err(bad(C, format!("{source} is not a gradient"))); }; let mut stops = g.gradient.stops; let n = stops.len(); @@ -550,6 +556,24 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { Ok(result) } +/// The paint whose gradient `paint.sampleColor` recolors a stop of when `p` gives `stop` and +/// objects in `ids`: the fill (or stroke, `stroke`) of the first object `paint.editGradient` edits +/// for those ids (a compound path for its member, a group's painted objects, not the art of a graph +/// design in a series). None without `stop` or without objects in `ids`: the gradient behind the +/// proxy is used. +fn given_stop_paint(s: &Session, p: &Value, stroke: bool) -> Result> { + const C: &str = "paint.sampleColor"; + if p.get("stop").is_none_or(Value::is_null) || p.get("ids").and_then(Value::as_array).is_none_or(Vec::is_empty) { + return Ok(None); + } + let q = json!({ "ids": p.get("ids"), "stroke": stroke }); + let item = super::appearance::item_target(s, &q, C)?.of_kind(s, !stroke); + let ids = super::appearance::drop_design_art_rows(s, item.targets_for(s, &q, !stroke)?, item, !stroke, C)?; + let d = &s.doc()?.doc; + let Some(n) = ids.first().and_then(|id| d.node(*id)) else { return Ok(None) }; + Ok(Some(super::paint::proxy_paint(n, stroke, None))) +} + // ---------- artboards ---------- fn artboard_move(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/tests/gradpanel.rs b/crates/engine/src/tests/gradpanel.rs index 680abfa9e8..2a757e2a90 100644 --- a/crates/engine/src/tests/gradpanel.rs +++ b/crates/engine/src/tests/gradpanel.rs @@ -51,6 +51,53 @@ fn sample_color_with_a_stop_recolours_that_stop_in_one_undo_step() { ); } +/// With `stop` and objects in `ids`, the stop is recolored in the first object's gradient, not in +/// the gradient behind the proxy: the selection's, or the Live Paint Bucket's while it is active. +#[test] +fn sample_color_with_a_stop_and_ids_recolours_the_first_given_objects_gradient() { + let mut s = session(); + let target = rect(&mut s, 10.0, 10.0, 100.0, 100.0); + let three = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#888888"}, {"offset": 1, "color": "#000000"}]); + s.execute("paint.setFill", &json!({"gradient": {"stops": three}})).unwrap(); + let selected = rect(&mut s, 200.0, 10.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2, "ids": [target.0]})).unwrap(); + assert_eq!(stop_hexes(&s, target, false), ["#ffffff", "#888888", "#ff0000"], "the given object's three stops"); + assert_eq!(stop_hexes(&s, selected, false), ["#ffffff", "#000000"], "the selection"); + // The bucket's solid fill, and then a two-stop gradient of its own. + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [target.0]})).unwrap(); + assert_eq!(stop_hexes(&s, target, false), ["#0000ff", "#888888", "#ff0000"], "under the bucket's solid fill"); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#00ffff", "stop": 1, "ids": [target.0]})).unwrap(); + assert_eq!(stop_hexes(&s, target, false), ["#0000ff", "#00ffff", "#ff0000"], "under the bucket's gradient"); + // A given object without a gradient has no stop to recolor. + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [selected.0]})).unwrap(); + let err = s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [selected.0]})).unwrap_err(); + assert!(err.to_string().contains("not a gradient"), "{err}"); + // A member of a compound path: the compound path's gradient, which the edit changes. + s.select_tool("selection", ViewInfo::default()).unwrap(); + let (a, b) = (rect(&mut s, 10.0, 300.0, 50.0, 50.0), rect(&mut s, 100.0, 300.0, 50.0, 50.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = s.doc().unwrap().selection.objects[0]; + s.execute("paint.setFill", &json!({"gradient": {"stops": three}, "ids": [compound.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [selected.0]})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2, "ids": [a.0]})).unwrap(); + assert_eq!(stop_hexes(&s, compound, false), ["#ffffff", "#888888", "#ff0000"], "the compound path's three stops"); + // A group: the stops of its first painted object, which every painted object of the group takes. + let (c, d) = (rect(&mut s, 10.0, 400.0, 50.0, 50.0), rect(&mut s, 100.0, 400.0, 50.0, 50.0)); + s.execute("paint.setFill", &json!({"gradient": {"stops": three}, "ids": [c.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [d.0]})).unwrap(); + s.execute("select.set", &json!({"ids": [c.0, d.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [selected.0]})).unwrap(); + s.execute("paint.sampleColor", &json!({"color": "#0000ff", "stop": 0, "ids": [group.0]})).unwrap(); + assert_eq!(stop_hexes(&s, c, false), ["#0000ff", "#888888", "#000000"], "the group's first object"); + assert_eq!(stop_hexes(&s, d, false), ["#0000ff", "#888888", "#000000"], "the group's other object"); +} + fn fill_geom(s: &Session, id: NodeId) -> Option { match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() { Paint::Gradient(g) => g.geom, diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..8abef4d577 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6278,7 +6278,9 @@ Alt+Shift-click samples only the color at the pointer into the active paint defa sets them; a tree names flags under `appearance` (`transparency`, `fill` `{color, transparency, overprint}`, `stroke` `{color, transparency, overprint, weight, cap, join, miter, dash}`), `character` and `paragraph`, and a bool for a branch sets all of it. `paint.sampleColor {color}` puts a sampled color into the active proxy (in a CMYK document an -RGB color is stored as CMYK, as `paint.setFill` stores it). Clicking an image samples its pixels: a CMYK image (a +RGB color is stored as CMYK, as `paint.setFill` stores it). `paint.sampleColor {color, stop}` recolors that stop of +the gradient behind the proxy; with objects in `ids` it recolors that stop in the topmost fill (or stroke) gradient of +the first object `paint.editGradient` edits for them, whatever tool is active. Clicking an image samples its pixels: a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's sRGB pixel is taken into the working RGB space. From 17517e93a5c72678773a3b0ecf00937edce874ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:27:59 -0800 Subject: [PATCH 085/126] Dimension tool: a level is checked across the whole span of both lines The span a parallel line is checked across now runs from the lowest to the highest point of both lines along the dimension. It no longer depends on which end of the other line comes first, and it has no one-point floor, so a short line that stays within 0.000001 pt of its level is a level. --- crates/tools/src/dimension.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 5dbe1fd6ef..4e76ede6b2 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -541,7 +541,8 @@ fn line_level(levels: &[DimensionLine], d: &Dimension, p: Point, reach: f64) -> let (u, normal) = (d.direction(), d.normal()); let mut best: Option<(f64, f64, f64, (Point, Point))> = None; for &(ends, direction) in levels { - let span = [ends.1, d.a, d.b].iter().map(|q| (*q - ends.0).dot(u).abs()).fold(1.0, f64::max); + let along_u = [ends.0, ends.1, d.a, d.b].map(|q| (q - ends.0).dot(u)); + let span = along_u.iter().fold(f64::NEG_INFINITY, |m, s| m.max(*s)) - along_u.iter().fold(f64::INFINITY, |m, s| m.min(*s)); let drift = u.cross(direction).abs() * span; if !drift.is_finite() || drift > 1e-6 { continue; @@ -1214,6 +1215,27 @@ mod tests { assert!(at.distance(pt(10_000_100.0, 170.0)) < 1e-9, "{at:?}"); } + /// The span a level is checked across runs from the lowest to the highest point of both lines + /// along the dimension, whichever end of the other line comes first, and has no lower bound. + #[test] + fn a_level_is_checked_across_the_whole_span_of_both_lines() { + let pt = Point::new; + let level = |from: Point, to: Point| ((from, to), (to - from) / (to - from).hypot()); + // 0.00000075 pt off across 100 pt drifts 0.0000015 pt across the 200 pt both lines cover. + let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(-100.0, 200.0), pt(100.0, 200.0), pt(0.0, 200.0), None); + let (a, b) = (pt(0.0, 170.0), pt(100.0, 170.000_000_75)); + for slanted in [level(a, b), level(b, a)] { + assert!(line_level(&[slanted], &d, pt(0.0, 168.0), 4.0).is_none(), "{slanted:?}"); + } + // 0.0000005 pt off across the 0.1 pt both lines cover is within the tolerance. + let d = DimensionTool::default().recipe(DimensionMode::Linear, pt(0.0, 200.0), pt(0.1, 200.0), pt(0.05, 200.0), None); + let (a, b) = (pt(0.0, 170.0), pt(0.1, 170.000_000_5)); + for short in [level(a, b), level(b, a)] { + let (at, _) = line_level(&[short], &d, pt(0.05, 168.0), 4.0).expect("on the level"); + assert!((at.y - 170.0).abs() < 1e-6, "{at:?}"); + } + } + /// A level that would put the line past the largest distance a dimension allows is passed /// over: the preview goes where the pointer is, with no level guide, or onto a level further /// off within reach that keeps the line within the limit. From e49a0d628c0fc13ab86381d3c8667e3dadc78f46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:54:27 -0800 Subject: [PATCH 086/126] Plug-ins: storage calls pay instructions for the bytes they move The settings and cache imports could move up to 1 GiB a run while the instruction budget charged only for the calls themselves. The bytes they read or write now cost the run one instruction per 64 bytes, counted over the whole run so that splitting a transfer into calls costs the same. A get also pays for the bytes it copies into the module's memory that the store didn't count, such as a setting answered from memory. A storage call pays from the store's fuel and from the part of the budget not yet handed out. The meter it gives the storage holds no more bytes than those instructions pay for, so a read or write the run can't pay for doesn't happen, and the run ends with "instruction budget". A read or write past the 1 GiB still returns -7. Bytes beyond the current slice are read or written only before the deadline and Cancel, and the host checks the deadline and Cancel after every storage call, so a run past either stops after the call instead of at the next slice. The plug-in fuzz test now also makes writes of up to about 1 MiB on small instruction budgets. Docs: docs/plugins.md. --- crates/engine/tests/plugin_fuzz.rs | 30 +++- crates/plugins/src/host.rs | 163 ++++++++++++++++++--- crates/plugins/src/runtime.rs | 36 ++++- crates/plugins/src/storage.rs | 51 ++++++- crates/plugins/tests/abi.rs | 224 ++++++++++++++++++++++++++++- docs/plugins.md | 16 ++- 6 files changed, 476 insertions(+), 44 deletions(-) diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 20546835c1..35f29a2a25 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -883,9 +883,10 @@ proptest! { } /// A plug-in that calls the storage imports with hostile keys (`..`, separators, device names, - /// control characters, too long), values, lengths and pointers in and out of its memory runs to - /// an output, never a panic; every call returns a length or a storage code, and the settings and - /// cache of another plug-in in the same store stay as they were. + /// control characters, too long), values, lengths up to about 1 MiB and pointers in and out of + /// its memory runs to an output, or on a small budget to its instruction budget, never a panic; + /// every call returns a length or a storage code, and the settings and cache of another plug-in + /// in the same store stay as they were. #[test] fn hostile_storage_arguments_never_crash( calls in prop::collection::vec( @@ -894,11 +895,12 @@ proptest! { prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x2000)], prop_oneof![any::(), 0..80i32], prop_oneof![any::(), 0x1ff00..0x20100i32, Just(0x3000)], - prop_oneof![any::(), 0..5000i32], + prop_oneof![any::(), 0..5000i32, 0..1_100_000i32], ), 0..16, ), key in prop::collection::vec(prop_oneof![Just(b'a'), Just(b'.'), Just(b'/'), Just(b'\\'), Just(b'_'), any::()], 0..80), + fuel in prop::option::of(1_000..200_000u64), ) { use vectorcraft_plugins::host::STORAGE_BUDGET; use vectorcraft_plugins::storage::Meter; @@ -936,17 +938,31 @@ proptest! { .collect(); let text: String = key.iter().map(|b| format!("\\{b:02x}")).collect(); let imports = format!(r#"{} (data (i32.const 0x2000) "{text}")"#, tpl::STORAGE_IMPORTS); - let wasm = wat::parse_str(tpl::with_imports(&storing("fuzz.storage"), &imports, &format!("(local $r i32) {body}"), r#"{"objects":[]}"#)).unwrap(); + // 64 more pages hold the values of the large writes. + let wasm = wat::parse_str(tpl::with_imports( + &storing("fuzz.storage"), + &imports, + &format!("(local $r i32) (drop (memory.grow (i32.const 64))) {body}"), + r#"{"objects":[]}"#, + )) + .unwrap(); // A failed case leaves its module installed, and the cases that shrink it install others // under the same id. let r = catch_quiet(|| { s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})) .map_err(|e| e.to_string())?; let p = vectorcraft_plugins::registry::get("fuzz.storage").ok_or("not installed")?; - p.run(b"{\"objects\":[]}", b"{}").map_err(|e| e.to_string()) + // A small budget runs out on the bytes the storage calls move. + let limits = Limits { fuel_base: fuel.unwrap_or(p.limits().fuel_base), fuel_per_byte: 0, ..p.limits().clone() }; + p.run_limited(b"{\"objects\":[]}", b"{}", &limits).map_err(|e| e.to_string()) }); let out = r.map_err(|msg| TestCaseError::fail(format!("panicked on {calls:?}: {msg}")))?; - prop_assert!(out.is_ok(), "{:?}", out); + prop_assert!( + out.is_ok() || (fuel.is_some() && out == Err(Error::Limit("instruction budget".into()).to_string())), + "{:?} on {:?} instructions", + out, + fuel + ); prop_assert_eq!(theirs.setting("mine", m).unwrap(), Some(b"kept".to_vec())); prop_assert_eq!(theirs.cache_entry("mine", m).unwrap(), Some(b"kept".to_vec())); prop_assert_eq!(theirs.cache_bytes(), 4); diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index b98407cb7c..354610e4c0 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -97,6 +97,10 @@ pub const MAX_STORAGE_CALLS: usize = 10_000; /// pass it returns [`STORAGE_BUDGET`]. pub const MAX_STORAGE_BYTES: usize = 1 << 30; +/// Bytes a storage call reads or writes for each instruction it costs the run, counted as for +/// [`MAX_STORAGE_BYTES`]: the 1 GiB a run may move costs 16,777,216 instructions. +pub const STORAGE_BYTES_PER_FUEL: u64 = 64; + /// What `vc_call` returns: the command ran, and `vc_call_result` reads its result. pub const CALL_OK: i32 = 0; /// What `vc_call` or `vc_call_result` returns: the id, the arguments or the buffer doesn't lie @@ -163,6 +167,19 @@ impl std::fmt::Display for CallPending { impl wasmi::errors::HostError for CallPending {} +/// What a storage call ends the run with when the instructions it may take can't pay for its bytes +/// ([`STORAGE_BYTES_PER_FUEL`]); the host reports why ([`Run::storage_stop`]). +#[derive(Debug)] +pub(crate) struct StorageStop; + +impl std::fmt::Display for StorageStop { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("storage call") + } +} + +impl wasmi::errors::HostError for StorageStop {} + /// One host import: its name, its type and the permission it needs. pub struct Import { pub name: &'static str, @@ -365,6 +382,18 @@ pub(crate) struct Run { storage: Option>, storage_calls: usize, storage_bytes: usize, + /// The instructions of the call's budget not yet handed to the store, which storage calls also + /// pay from; the host keeps it up to date around each slice. + pub(crate) fuel_left: u64, + /// Bytes storage reads copied into the module's memory beyond the bytes the storage counted for + /// them, such as a settings value answered from memory; they cost instructions at the same rate. + copied_bytes: u64, + /// Instructions the last storage call cost ([`STORAGE_BYTES_PER_FUEL`]), still to be taken. + fuel_owed: u64, + /// Why the call ends after a storage call: the instruction budget when it needed more + /// instructions than it could take, or the deadline or Cancel, checked before a storage call + /// takes from [`Run::fuel_left`] and after every storage call. + pub(crate) storage_stop: Option, /// The commands `vc_call` may run (the manifest's `commandAllowlist`), once the module has /// loaded and when the run has something to run them ([`Run::allow_calls`]); `None` otherwise. allowed: Option>, @@ -395,6 +424,10 @@ impl Run { storage: None, storage_calls: 0, storage_bytes: 0, + fuel_left: 0, + copied_bytes: 0, + fuel_owed: 0, + storage_stop: None, allowed: None, calls: 0, call_bytes: 0, @@ -527,16 +560,48 @@ impl Run { /// Makes one storage call with `call`, on the plug-in's storage and a [`Meter`] holding the /// run's storage bytes left, and counts the call and the bytes it read and wrote → the code for /// a run that has used up its calls or has no storage, else what `call` returns. - fn metered(&mut self, call: impl FnOnce(&dyn Storage, &mut Meter) -> std::result::Result) -> std::result::Result { + /// + /// The run's storage bytes cost one instruction for each whole [`STORAGE_BYTES_PER_FUEL`] + /// bytes, counted over the run, so splitting a transfer into calls costs the same. The meter + /// also holds no more bytes than the `held` instructions in the store pay for, with + /// [`Run::fuel_left`] too while the deadline and Cancel have not come ([`Meter::gated`]), so + /// the call stops before a read or write they can't pay for; one the storage bytes left would + /// allow sets [`Run::storage_stop`]. What the call costs goes to [`Run::fuel_owed`]. + fn metered( + &mut self, + held: u64, + call: impl FnOnce(&dyn Storage, &mut Meter) -> std::result::Result, + ) -> std::result::Result { if self.storage_calls >= MAX_STORAGE_CALLS { return Err(STORAGE_BUDGET); } self.storage_calls += 1; let Some(store) = self.storage.clone() else { return Err(STORAGE_UNAVAILABLE) }; - let mut meter = Meter::new(MAX_STORAGE_BYTES.saturating_sub(self.storage_bytes) as u64); + let before = self.storage_bytes as u64; + let by_bytes = MAX_STORAGE_BYTES.saturating_sub(self.storage_bytes) as u64; + // Bytes up to the end of the last whole unit `fuel` instructions pay for. + let by_fuel = |fuel: u64| { + let units = (before / STORAGE_BYTES_PER_FUEL).saturating_add(fuel).saturating_add(1); + units.saturating_mul(STORAGE_BYTES_PER_FUEL).saturating_sub(before).saturating_sub(1) + }; + // Bytes past what the store's fuel pays for are read or written only before the deadline + // and Cancel, as the host hands out the rest of the budget only then. + let left = by_bytes.min(by_fuel(held.saturating_add(self.fuel_left))); + let mut meter = Meter::gated(left, by_fuel(held), self.deadline.at); let done = call(store.as_ref(), &mut meter); // What the call read before it failed counts too. self.storage_bytes = self.storage_bytes.saturating_add(usize::try_from(meter.used()).unwrap_or(usize::MAX)); + self.fuel_owed = (self.storage_bytes as u64 / STORAGE_BYTES_PER_FUEL).saturating_sub(before / STORAGE_BYTES_PER_FUEL); + // A read or write the run's storage bytes alone allow was refused for its instructions, or + // for the deadline or Cancel. + let refused = meter.refused(); + if matches!(done, Err(StorageError::Budget)) && refused > 0 && refused <= by_bytes.saturating_sub(meter.used()) { + self.storage_stop = Some(match meter.stopped() { + Some(storage::Gate::Cancel) => Error::Cancelled, + Some(storage::Gate::Deadline) => Error::Limit(TIME_BUDGET.into()), + None => Error::Limit("instruction budget".into()), + }); + } done.map_err(|e| storage_code(&e)) } @@ -549,8 +614,8 @@ impl Run { } /// `vc_settings_get` and `vc_cache_read`: copies the value of the key at `name` into the - /// `out_cap` bytes at `out` when it fits → its length. - fn storage_read(&mut self, area: Area, memory: &mut [u8], name: (usize, usize), out: (usize, usize)) -> i32 { + /// `out_cap` bytes at `out` when it fits → its length. The store holds `held` instructions. + fn storage_read(&mut self, area: Area, memory: &mut [u8], name: (usize, usize), out: (usize, usize), held: u64) -> i32 { let key = match Self::storage_name(memory, name.0, name.1) { Ok(key) => key, Err(code) => return code, @@ -559,7 +624,8 @@ impl Run { return STORAGE_OUTSIDE_MEMORY; } // The storage counts what it read whether or not the value fits the buffer. - let got = self.metered(|store, meter| match area { + let counted = self.storage_bytes; + let got = self.metered(held, |store, meter| match area { Area::Settings => store.setting(&key, meter), Area::Cache => store.cache_entry(&key, meter), }); @@ -573,12 +639,18 @@ impl Run { && let Some(dest) = memory.get_mut(out.0..out.0 + value.len()) { dest.copy_from_slice(&value); + // Bytes copied that the storage didn't count, counted over the run like the others. + let uncounted = (value.len() as u64).saturating_sub(self.storage_bytes.saturating_sub(counted) as u64); + let before = self.copied_bytes / STORAGE_BYTES_PER_FUEL; + self.copied_bytes = self.copied_bytes.saturating_add(uncounted); + self.fuel_owed = self.fuel_owed.saturating_add(self.copied_bytes / STORAGE_BYTES_PER_FUEL - before); } len } - /// `vc_settings_set` and `vc_cache_write`: sets the key at `name` to the `value` bytes. - fn storage_write(&mut self, area: Area, memory: &[u8], name: (usize, usize), value: (usize, usize)) -> i32 { + /// `vc_settings_set` and `vc_cache_write`: sets the key at `name` to the `value` bytes. The + /// store holds `held` instructions. + fn storage_write(&mut self, area: Area, memory: &[u8], name: (usize, usize), value: (usize, usize), held: u64) -> i32 { let key = match Self::storage_name(memory, name.0, name.1) { Ok(key) => key, Err(code) => return code, @@ -587,7 +659,7 @@ impl Run { if bytes.len() > area.max_value() { return STORAGE_FULL; } - let written = self.metered(|store, meter| match area { + let written = self.metered(held, |store, meter| match area { Area::Settings => store.set_setting(&key, bytes, meter), Area::Cache => store.set_cache_entry(&key, bytes, meter), }); @@ -595,8 +667,8 @@ impl Run { } /// `vc_settings_delete` and `vc_cache_clear`: removes the key at `name`, or with `vc_cache_clear` - /// and a `name` of no bytes, every cache entry. - fn storage_remove(&mut self, area: Area, memory: &[u8], name: (usize, usize)) -> i32 { + /// and a `name` of no bytes, every cache entry. The store holds `held` instructions. + fn storage_remove(&mut self, area: Area, memory: &[u8], name: (usize, usize), held: u64) -> i32 { let key = match (area, name.1) { (Area::Cache, 0) => None, _ => match Self::storage_name(memory, name.0, name.1) { @@ -604,7 +676,7 @@ impl Run { Err(code) => return code, }, }; - let removed = self.metered(|store, meter| match (area, key) { + let removed = self.metered(held, |store, meter| match (area, key) { (Area::Settings, Some(key)) => store.delete_setting(&key, meter), (Area::Cache, Some(key)) => store.remove_cache_entry(&key), (_, None) => store.clear_cache().map(|_| true), @@ -700,6 +772,35 @@ fn memory_and_host<'a>(caller: &'a mut Caller<'_, Host>) -> Option<(&'a mut [u8] Some(memory.data_and_store_mut(caller)) } +/// Takes what the last storage call cost ([`Run::fuel_owed`]) from the `held` instructions in the +/// store, then from [`Run::fuel_left`]. A call that needed more instructions than those, or that +/// ended after the deadline or Cancel (checked in that order, as after a `vc_call`), ends the run +/// with [`StorageStop`] and the reason in [`Run::storage_stop`]. +fn pay_storage(caller: &mut Caller<'_, Host>, held: u64) -> std::result::Result<(), wasmi::Error> { + let run = &mut caller.data_mut().run; + let owed = std::mem::take(&mut run.fuel_owed); + if run.storage_stop.is_none() { + run.storage_stop = if owed > held.saturating_add(run.fuel_left) { + Some(Error::Limit("instruction budget".into())) + } else if run.deadline.passed() { + Some(Error::Limit(TIME_BUDGET.into())) + } else if vectorcraft_doc::cancel::is_cancelled() { + Some(Error::Cancelled) + } else { + None + }; + } + if run.storage_stop.is_some() { + return Err(wasmi::Error::host(StorageStop)); + } + let from_store = owed.min(held); + run.fuel_left = run.fuel_left.saturating_sub(owed - from_store); + if from_store > 0 { + caller.set_fuel(held - from_store)?; + } + Ok(()) +} + /// An i32 argument as the unsigned offset or length it stands for. fn offset(v: i32) -> usize { v as u32 as usize @@ -726,18 +827,34 @@ pub(crate) fn linker(engine: &Engine, granted: &[Permission]) -> Linker { if !granted.contains(&permission) { continue; } - let _ = linker.func_wrap(MODULE, get, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, out: i32, out_cap: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_read(area, data, (offset(key), offset(key_len)), (offset(out), offset(out_cap))) - }); - let _ = linker.func_wrap(MODULE, set, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, value: i32, value_len: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_write(area, data, (offset(key), offset(key_len)), (offset(value), offset(value_len))) - }); - let _ = linker.func_wrap(MODULE, remove, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32| -> i32 { - let Some((data, host)) = memory_and_host(&mut caller) else { return STORAGE_OUTSIDE_MEMORY }; - host.run.storage_remove(area, data, (offset(key), offset(key_len))) - }); + // A storage call pays for its bytes before it returns ([`pay_storage`]). + let _ = linker.func_wrap( + MODULE, + get, + move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, out: i32, out_cap: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_read(area, data, (offset(key), offset(key_len)), (offset(out), offset(out_cap)), held); + pay_storage(&mut caller, held).map(|()| code) + }, + ); + let _ = linker.func_wrap( + MODULE, + set, + move |mut caller: Caller<'_, Host>, key: i32, key_len: i32, value: i32, value_len: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_write(area, data, (offset(key), offset(key_len)), (offset(value), offset(value_len)), held); + pay_storage(&mut caller, held).map(|()| code) + }, + ); + let _ = + linker.func_wrap(MODULE, remove, move |mut caller: Caller<'_, Host>, key: i32, key_len: i32| -> std::result::Result { + let held = caller.get_fuel().unwrap_or(0); + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(STORAGE_OUTSIDE_MEMORY) }; + let code = host.run.storage_remove(area, data, (offset(key), offset(key_len)), held); + pay_storage(&mut caller, held).map(|()| code) + }); } if granted.contains(&Permission::Commands) { // A call that can be made pauses the run: the host makes it with what the run was given to diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 1a25e9e6b0..7c4262dd4e 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -191,6 +191,27 @@ fn charge(live: &mut Live, left: &mut u64, cost: u64) -> Result<()> { live.store.set_fuel(held - (cost - from_left)).map_err(wasm_err) } +/// Resumes a run's call with `step`: the store's storage calls may also pay from `left` +/// ([`host::Run::fuel_left`]), and what they took from it comes off `left` when the call pauses → +/// the pause, or the error the call ended with ([`run_err`]). +fn slice(live: &mut Live, left: &mut u64, step: impl FnOnce(&mut Store) -> std::result::Result) -> Result { + live.store.data_mut().run.fuel_left = *left; + let paused = step(&mut live.store); + *left = std::mem::take(&mut live.store.data_mut().run.fuel_left); + paused.map_err(|e| run_err(&mut live.store, e)) +} + +/// Why a storage call ended a run of `store` ([`host::Run::storage_stop`]). +fn stop_reason(store: &mut Store) -> Error { + store.data_mut().run.storage_stop.take().unwrap_or_else(|| Error::Limit("instruction budget".into())) +} + +/// The error `e` that a run of `store` ended with: a storage call's reason ([`host::StorageStop`]) +/// or [`wasm_err`]'s. +fn run_err(store: &mut Store, e: wasmi::Error) -> Error { + if e.downcast_ref::().is_some() { stop_reason(store) } else { wasm_err(e) } +} + fn wasm_err(e: wasmi::Error) -> Error { if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) } } @@ -306,7 +327,7 @@ impl Plugin { Ok(instance) => instance, Err(e) => { *report = std::mem::take(&mut store.data_mut().run.report); - return Err(wasm_err(e)); + return Err(run_err(&mut store, e)); } }; let memory = @@ -321,7 +342,9 @@ impl Plugin { /// for it. It charges a `memory.fill` or `memory.copy` for its whole length before writing, so /// up to that cost can be left in the store at a pause. Each slice tops the store up to the /// slice size, keeping that fuel, and a run ends with the instruction budget only when the - /// store's fuel and the rest of the budget together can't pay for the next instruction. + /// store's fuel and the rest of the budget together can't pay for the next instruction. A + /// storage call pays for its bytes ([`host::STORAGE_BYTES_PER_FUEL`]) from the store's fuel and + /// the rest of the budget as it is made, and one they can't pay for ends the run. fn call(&self, live: &mut Live, f: &TypedFunc, params: P, fuel: u64, deadline: &Deadline) -> Result { self.call_with(live, f, params, fuel, deadline, None) } @@ -343,11 +366,14 @@ impl Plugin { let give = left.min(FUEL_SLICE); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; - let mut call = f.call_resumable(&mut live.store, params).map_err(wasm_err)?; + let mut call = slice(live, &mut left, |store| f.call_resumable(store, params))?; loop { match call { TypedResumableCall::Finished(r) => return Ok(r), TypedResumableCall::HostTrap(inv) => { + if inv.host_error().downcast_ref::().is_some() { + return Err(stop_reason(&mut live.store)); + } let pending = live.store.data_mut().run.pending.take(); let (Some((id, args, size)), Some(bridge)) = (pending, bridge.as_deref_mut()) else { return Err(Error::Trap("unexpected host trap".into())); @@ -361,7 +387,7 @@ impl Plugin { charge(live, &mut left, returned as u64 / 64)?; deadline.check()?; vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; - call = inv.resume(&mut live.store, &[Val::I32(code)]).map_err(wasm_err)?; + call = slice(live, &mut left, |store| inv.resume(store, &[Val::I32(code)]))?; } TypedResumableCall::OutOfFuel(inv) => { let need = inv.required_fuel(); @@ -375,7 +401,7 @@ impl Plugin { let fill = total.min(FUEL_SLICE.max(need)).max(held); left -= fill - held; live.store.set_fuel(fill).map_err(wasm_err)?; - call = inv.resume(&mut live.store).map_err(wasm_err)?; + call = slice(live, &mut left, |store| inv.resume(store))?; } } } diff --git a/crates/plugins/src/storage.rs b/crates/plugins/src/storage.rs index b7de23c45a..fb32e94513 100644 --- a/crates/plugins/src/storage.rs +++ b/crates/plugins/src/storage.rs @@ -49,12 +49,33 @@ pub enum StorageError { pub struct Meter { left: u64, used: u64, + refused: u64, + /// Past `free` bytes in all, a read or write happens only before the deadline `until` and + /// Cancel ([`vectorcraft_doc::cancel`]); `stopped` records which refused one. + free: u64, + until: Option, + stopped: Option, +} + +/// What made a gated [`Meter`] refuse a read or write. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Gate { + /// The run was canceled. + Cancel, + /// The run's deadline passed. + Deadline, } impl Meter { /// A meter that lets a call read and write `left` bytes. pub fn new(left: u64) -> Self { - Meter { left, used: 0 } + Meter { left, used: 0, refused: 0, free: u64::MAX, until: None, stopped: None } + } + + /// A meter that lets a call read and write `left` bytes, those past the first `free` only + /// before `until` and Cancel. + pub(crate) fn gated(left: u64, free: u64, until: web_time::Instant) -> Self { + Meter { free, until: Some(until), ..Meter::new(left) } } /// A meter with no limit, for callers that don't count. @@ -63,20 +84,46 @@ impl Meter { } /// Counts `bytes` about to be read or written → [`StorageError::Budget`], counting nothing, - /// when that is more than is left. + /// when that is more than is left, or when they pass the free bytes of a gated meter after its + /// deadline or Cancel. pub fn take(&mut self, bytes: u64) -> Result<(), StorageError> { if bytes > self.left { + self.refused = bytes; return Err(StorageError::Budget); } + if self.used.saturating_add(bytes) > self.free { + // The deadline first, as the host checks it between two slices. + let closed = if self.until.is_some_and(|at| web_time::Instant::now() >= at) { + Some(Gate::Deadline) + } else { + vectorcraft_doc::cancel::is_cancelled().then_some(Gate::Cancel) + }; + if closed.is_some() { + self.stopped = closed; + self.refused = bytes; + return Err(StorageError::Budget); + } + } self.left -= bytes; self.used = self.used.saturating_add(bytes); Ok(()) } + /// What made the meter refuse a read or write past its free bytes ([`Meter::gated`]), if + /// anything did. + pub(crate) fn stopped(&self) -> Option { + self.stopped + } + /// The bytes counted so far. pub fn used(&self) -> u64 { self.used } + + /// The bytes of the last read or write the meter refused (0 when it refused none). + pub(crate) fn refused(&self) -> u64 { + self.refused + } } impl std::fmt::Display for StorageError { diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index ae99846c69..f4cb2e103b 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -621,9 +621,9 @@ fn charged( key: &str, meter: &mut Meter, ) -> Result>, StorageError> { - let value = kept.lock().unwrap().get(key).cloned(); - meter.take(value.as_ref().map_or(0, |v| v.len() as u64))?; - Ok(value) + let kept = kept.lock().unwrap(); + meter.take(kept.get(key).map_or(0, |v| v.len() as u64))?; + Ok(kept.get(key).cloned()) } impl Storage for Kept { @@ -777,6 +777,224 @@ fn a_read_into_too_small_a_buffer_still_counts_its_bytes() { registry::set_storage(id, None); } +/// Storage calls cost the run one instruction for every 64 bytes they read or write: reading a +/// 64 MiB cache entry, or writing 1 MiB to the cache 64 times, ends a run of 1 M instructions with +/// its instruction budget and finishes within 2 M. A call the run can't pay for reads and writes +/// nothing, a call pays from the budget not yet in the store, a call past the 1 GiB still returns +/// `STORAGE_BUDGET`, and a small read finishes on a small budget. +#[test] +fn storage_calls_pay_instructions_for_the_bytes_they_move() { + use vectorcraft_plugins::host::{MAX_STORAGE_BYTES, STORAGE_BUDGET, STORAGE_DONE}; + use vectorcraft_plugins::storage::MAX_CACHE_ENTRY; + let id = "test.storage.fuel"; + let kept = std::sync::Arc::new(Kept::default()); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + kept.settings.lock().unwrap().insert("zoom".into(), b"hello".to_vec()); + registry::set_storage(id, Some(kept.clone())); + let run = |first: &str, fuel_base: u64| { + let limits = Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }; + Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), first, INPUT)), limits).unwrap().run(INPUT.as_bytes(), b"{}") + }; + let zoom = "(i32.const 0x2000) (i32.const 4)"; + let reading = expect(&format!("(call $vc_cache_read {zoom} (i32.const 0x3000) (i32.const 0))"), MAX_CACHE_ENTRY as i32); + // 17 more pages of memory, then 1 MiB of them written to the cache 64 times. + let write = expect(&format!("(call $vc_cache_write {zoom} (i32.const 0x20000) (i32.const 1048576))"), STORAGE_DONE); + let writing = format!( + "(local $n i32) (drop (memory.grow (i32.const 17))) (local.set $n (i32.const 64)) \ + (loop $work {write} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ); + let budget = Err(Error::Limit("instruction budget".into())); + let done = Ok(INPUT.as_bytes().to_vec()); + let small = expect(&format!("(call $vc_settings_get {zoom} (i32.const 0x3000) (i32.const 16))"), 5); + assert_eq!(run(&small, 10_000), done, "a small read on 10,000 instructions"); + // Growing the memory by 17 pages costs about 17,400 instructions and writing 1 MiB 16,384: a + // write the run can't pay for writes nothing. + let once = format!("(drop (memory.grow (i32.const 17))) {write}"); + assert_eq!(run(&once, 30_000), budget, "1 MiB written on 30,000 instructions"); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged"); + assert_eq!(run(&once, 60_000), done, "1 MiB written on 60,000 instructions"); + assert_eq!(kept.cache_bytes(), 1 << 20, "the entry is written"); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + assert_eq!(run(&reading, 1_000_000), budget, "a 64 MiB read on 1 M instructions"); + assert_eq!(run(&reading, 2_000_000), done, "a 64 MiB read on 2 M instructions"); + assert_eq!(run(&writing, 1_000_000), budget, "64 MiB written on 1 M instructions"); + assert_eq!(run(&writing, 2_000_000), done, "64 MiB written on 2 M instructions"); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + // About 19.7 M instructions of fills leave less of the first 20 M slice than a 64 MiB read + // costs; the read pays from the rest of the budget. + let burning = format!( + "(local $n i32) (drop (memory.grow (i32.const 130))) (local.set $n (i32.const 149)) \ + (loop $burn (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $burn (local.get $n))) {reading}" + ); + assert_eq!(run(&burning, 21_000_000), done, "a read across two slices within the budget"); + assert_eq!(run(&burning, 20_500_000), budget, "a read across two slices over the budget"); + // What the read took from the rest of the budget is gone: six more 8 MiB fills (about 786,000 + // instructions) don't fit the 21 M. + let more = format!( + "{burning} (local.set $n (i32.const 6)) (loop $more (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $more (local.get $n)))" + ); + assert_eq!(run(&more, 21_000_000), budget, "fills after the read over the budget"); + // With 8 MiB of the run's 1 GiB of storage bytes left and instructions for less, a 64 MiB read + // returns `STORAGE_BUDGET`, since the bytes alone refuse it, and the run goes on. + let rest = MAX_STORAGE_BYTES - 15 * MAX_CACHE_ENTRY - (8 << 20); + kept.cache.lock().unwrap().insert("x".into(), vec![0; rest]); + let x = expect("(call $vc_cache_read (i32.const 0x200d) (i32.const 1) (i32.const 0x3000) (i32.const 0))", rest as i32); + let over = expect(&format!("(call $vc_cache_read {zoom} (i32.const 0x3000) (i32.const 0))"), STORAGE_BUDGET); + let near = [vec![reading.clone(); 15], vec![x, over]].concat().concat(); + assert_eq!(run(&near, 16_700_000), done, "a read past the 1 GiB"); + // Bytes are counted over the run: 9,000 writes of 63 bytes, each under 64, cost about 8,860 + // instructions more than 9,000 writes of none, not 0 or 9,000 as rounding each write down or up + // would. Each run's fewest instructions are found by bisection. + let looped = |len: u32| { + let write = expect(&format!("(call $vc_cache_write {zoom} (i32.const 0x2000) (i32.const {len}))"), STORAGE_DONE); + format!( + "(local $n i32) (local.set $n (i32.const 9000)) \ + (loop $work {write} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ) + }; + let fewest = |first: &str| { + let (mut lo, mut hi) = (10_000, 50_000_000); + assert_eq!(run(first, hi), done, "the writes finish"); + while lo + 1 < hi { + let mid = (lo + hi) / 2; + match run(first, mid) { + Ok(_) => hi = mid, + Err(Error::Limit(why)) if why == "instruction budget" => lo = mid, + Err(e) => panic!("the writes failed on {mid} instructions: {e:?}"), + } + } + hi + }; + let (none, small) = (fewest(&looped(0)), fewest(&looped(63))); + assert!((none + 8_800..=none + 8_900).contains(&small), "63-byte writes take {small} instructions, empty ones {none}"); + registry::set_storage(id, None); +} + +/// A storage call that needs more of the budget than the store holds takes it only before Cancel +/// and the deadline: after either, a 32 MiB write near the end of the first 20 M slice writes +/// nothing and the run ends as canceled or with its time budget. +#[test] +fn after_cancel_or_the_deadline_a_storage_call_takes_no_more_of_the_budget() { + use vectorcraft_plugins::host::STORAGE_DONE; + use vectorcraft_plugins::storage::MAX_CACHE_ENTRY; + let id = "test.storage.cancel"; + let kept = std::sync::Arc::new(Kept::default()); + kept.cache.lock().unwrap().insert("zoom".into(), vec![0; MAX_CACHE_ENTRY]); + registry::set_storage(id, Some(kept.clone())); + // Growing by 512 pages and 148 fills of 8 MiB take about 19.9 M instructions; the write costs + // 524,288. + let write = expect("(call $vc_cache_write (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 33554432))", STORAGE_DONE); + let first = format!( + "(local $n i32) (drop (memory.grow (i32.const 512))) (local.set $n (i32.const 148)) \ + (loop $burn (memory.fill (i32.const 0x20000) (i32.const 7) (i32.const 8388608)) \ + (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $burn (local.get $n))) {write}" + ); + let limits = Limits { fuel_base: 21_000_000, fuel_per_byte: 0, ..Limits::default() }; + let p = Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), limits.clone()).unwrap(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); + assert_eq!(r, Err(Error::Cancelled)); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged"); + let timed = Limits { wall_time_ms: 0, ..limits }; + assert_eq!(p.run_limited(INPUT.as_bytes(), b"{}", &timed), Err(Error::Limit("time budget".into()))); + assert_eq!(kept.cache_bytes(), MAX_CACHE_ENTRY as u64, "the entry is unchanged after the deadline"); + // With both, the time budget, as between two slices. + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run_limited(INPUT.as_bytes(), b"{}", &timed)); + assert_eq!(r, Err(Error::Limit("time budget".into()))); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Ok(INPUT.as_bytes().to_vec()), "the same run without Cancel"); + assert_eq!(kept.cache_bytes(), 32 << 20, "the entry is written"); + registry::set_storage(id, None); +} + +/// The host checks the deadline and Cancel after every storage call, also one the store's +/// instructions pay for: after either, a 1 MiB cache write is the run's last storage call, and the +/// write after it doesn't happen. +#[test] +fn a_run_past_its_deadline_or_canceled_stops_after_a_storage_call() { + use vectorcraft_plugins::host::STORAGE_DONE; + let id = "test.storage.after"; + let kept = std::sync::Arc::new(Kept::default()); + registry::set_storage(id, Some(kept.clone())); + let first = format!( + "(drop (memory.grow (i32.const 17))) {} {}", + expect("(call $vc_cache_write (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 1048576))", STORAGE_DONE), + expect("(call $vc_cache_write (i32.const 0x200d) (i32.const 1) (i32.const 0x20000) (i32.const 1048576))", STORAGE_DONE), + ); + let p = Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), Limits::default()).unwrap(); + let written = || { + let cache = kept.cache.lock().unwrap(); + let names = (cache.contains_key("zoom"), cache.contains_key("x")); + drop(cache); + kept.cache.lock().unwrap().clear(); + names + }; + let timed = Limits { wall_time_ms: 0, ..p.limits().clone() }; + assert_eq!(p.run_limited(INPUT.as_bytes(), b"{}", &timed), Err(Error::Limit("time budget".into()))); + assert_eq!(written(), (true, false), "after the deadline"); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + assert_eq!(vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")), Err(Error::Cancelled)); + assert_eq!(written(), (true, false), "after Cancel"); + assert_eq!(p.run(INPUT.as_bytes(), b"{}"), Ok(INPUT.as_bytes().to_vec()), "the same run before both"); + assert_eq!(written(), (true, true), "before both"); + registry::set_storage(id, None); +} + +/// A store that answers every setting with the same value without counting its bytes, as the app's +/// store answers a get from the settings it keeps in memory. +struct Remembered(Vec); + +impl Storage for Remembered { + fn setting(&self, _: &str, _: &mut Meter) -> Result>, StorageError> { + Ok(Some(self.0.clone())) + } + fn set_setting(&self, _: &str, _: &[u8], _: &mut Meter) -> Result<(), StorageError> { + Ok(()) + } + fn delete_setting(&self, _: &str, _: &mut Meter) -> Result { + Ok(false) + } + fn cache_entry(&self, _: &str, _: &mut Meter) -> Result>, StorageError> { + Ok(None) + } + fn set_cache_entry(&self, _: &str, _: &[u8], _: &mut Meter) -> Result<(), StorageError> { + Ok(()) + } + fn remove_cache_entry(&self, _: &str) -> Result { + Ok(false) + } + fn clear_cache(&self) -> Result { + Ok(0) + } + fn cache_bytes(&self) -> u64 { + 0 + } +} + +/// A settings get the store answers without counting bytes still costs the bytes it copies into +/// the module's memory: 2,000 gets of a 64 KiB value (128,000 KiB copied) end a run of 1 M +/// instructions with its instruction budget and finish within 4 M. +#[test] +fn settings_gets_answered_from_memory_pay_for_the_bytes_they_copy() { + let id = "test.storage.copied"; + registry::set_storage(id, Some(std::sync::Arc::new(Remembered(vec![7; 65536])))); + let get = expect("(call $vc_settings_get (i32.const 0x2000) (i32.const 4) (i32.const 0x20000) (i32.const 65536))", 65536); + let first = format!( + "(local $n i32) (drop (memory.grow (i32.const 2))) (local.set $n (i32.const 2000)) \ + (loop $work {get} (local.set $n (i32.sub (local.get $n) (i32.const 1))) (br_if $work (local.get $n)))" + ); + let run = |fuel_base: u64| { + let limits = Limits { fuel_base, fuel_per_byte: 0, ..Limits::default() }; + Plugin::load(&build(&tpl::with_imports(&storing(id), &storage_data(), &first, INPUT)), limits).unwrap().run(INPUT.as_bytes(), b"{}") + }; + assert_eq!(run(1_000_000), Err(Error::Limit("instruction budget".into())), "on 1 M instructions"); + assert_eq!(run(4_000_000), Ok(INPUT.as_bytes().to_vec()), "on 4 M instructions"); + registry::set_storage(id, None); +} + /// A plug-in reaches only the storage of its own id, and a plug-in with none (not installed with a /// plug-in store, as on the web) gets `STORAGE_UNAVAILABLE`. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 7e6dd26185..ab294db1ff 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -129,14 +129,14 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | -| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte; [storage calls](#settings-and-cache) take one more for every 64 bytes they move | `Limit("instruction budget")` | +| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions and after each [storage call](#settings-and-cache); the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | | Module shape | wasmi's strict limits (≤ 10,000 functions, 1 memory, …) | rejected | An export runs where the export runs: with Background Export on, on the export's worker, whose Cancel stops the -plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the +plug-in between two of those 20 M-instruction slices or after a storage call; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. ### Instruction budget preference @@ -151,7 +151,7 @@ and MCP alike: A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and -the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +the time budget stop a run between two 20 M-instruction slices, or after a storage call, with either choice. `prefs.set {key: "pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other value; a saved preferences file with another value reads as Normal. @@ -428,6 +428,14 @@ its 10,000 storage calls or its 1 GiB of storage reads and writes. Each call cou settings call counts the whole settings file when it reads the file, and a set or delete also counts the whole file when it writes the file; a cache call counts the entry it reads or writes. A read counts them even when the value doesn't fit and nothing is copied. A call that would pass the 1 GiB returns `-7` before it reads or writes anything. +The bytes the calls count also cost the run one instruction of its budget for every 64 bytes (VectorCraft's own +value), counted over the whole run, so the 1 GiB costs about 16.8 M instructions. A get also pays at that rate for the +bytes it copies into the module's memory that it didn't count, such as a value answered from memory. A call stops +before a read or write of a file that the run's instructions can't pay for, and the run ends with +`Limit("instruction budget")`; a set or delete may already have read the settings file then. A call takes +instructions beyond the current 20 M-instruction slice only before Cancel and the time budget; after either, a read or +write that needs them doesn't happen. After every storage call the run checks its time budget and Cancel, and stops +if either has come. A read or write that would pass the 1 GiB still returns `-7`, whatever the instructions left. The app keeps the settings in memory after the first call and reads `settings.json` again only when the file's size or modified time differs from the last read or write. A get answered from memory reads no file and counts no bytes. A From 999521e391a72060364dba5e96d592eafbb45f19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:38:37 -0800 Subject: [PATCH 087/126] Scripts: File.hidden can be set and File.createAlias makes a link within the grants On macOS and Linux, setting `hidden` renames the file or link in its folder with one leading dot added, or its leading dots taken off. Both the old and the new name must be places the script may write, and a name of dots alone, a name in use and a folder are refused. A file the object has open stays open at the new path. `createAlias(target)` makes a symbolic link at the object's path to the real path of a file the script may read. The link's place must be one the script may write where nothing is, a link that leads nowhere included; the settings folder is refused for both. When a folder above the link's place is replaced by a link while the alias is made, the new link is removed and the call fails. `hidden` reads a link's own name, and setting `hidden`, `rename` and `remove` act on the link itself. On Windows both still set `error` and change nothing. `execute` stays unavailable. Behavior: https://extendscript.docsforadobe.dev/file-system-access/file-object/ and https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/ --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/file_access.rs | 10 +- crates/engine/src/script/files.rs | 166 +++++++++++++--- crates/engine/src/tests/script_io.rs | 281 ++++++++++++++++++++++++++- crates/js/src/file_classes.rs | 37 ++-- crates/js/src/realm.rs | 8 +- docs/mcp.md | 24 ++- docs/target-app-parity.md | 1 + 8 files changed, 471 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..dc33c46ab1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..abc7fa0740 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -782,15 +782,17 @@ impl ScriptScope { self.allows(&real.join(rest)) } - /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. + /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. Whether + /// it is hidden is a link's own, and the rest is what the link leads to. pub(crate) fn stat(&self, path: &Path) -> Result { let real = self.locate(path)?; let meta = std::fs::metadata(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; - let link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()); + let own = std::fs::symlink_metadata(path).ok().filter(|m| m.file_type().is_symlink()); + let link = own.is_some(); #[cfg(windows)] - let hidden = std::os::windows::fs::MetadataExt::file_attributes(&meta) & 2 != 0; + let hidden = std::os::windows::fs::MetadataExt::file_attributes(own.as_ref().unwrap_or(&meta)) & 2 != 0; #[cfg(not(windows))] - let hidden = real.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')); + let hidden = if link { path.file_name() } else { real.file_name() }.is_some_and(|n| n.to_string_lossy().starts_with('.')); Ok(ScriptEntry { dir: meta.is_dir(), file: meta.is_file(), diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index c0694bbd81..94ef3bdf9e 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -67,8 +67,15 @@ //! file and once more for each such object. `write` joins its values only for an open file and //! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the //! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed. -//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`. -//! `execute` is counted in the report's `fileExecutes`. +//! - On Unix, where a name that starts with a dot is hidden, setting `hidden` renames the file in +//! its folder, adding one dot or taking its leading dots off, under the rules for `rename`: the +//! old and the new name must both be places the script may write, and a name in use is refused. +//! `createAlias` makes a symbolic link at the object's path, a place the script may write where +//! nothing is, that leads to the real path of a file the script may read. `hidden` and `alias` +//! tell of a link itself, and setting `hidden`, `rename` and `remove` change the link, never what +//! it leads to. On other systems both set `error` and change nothing. +//! - `execute` is not available: it returns `false`, sets `error`, and is counted in the report's +//! `fileExecutes`. //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; @@ -118,6 +125,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; +#[cfg(not(unix))] pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases"; pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed"; pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed"; @@ -1883,44 +1891,41 @@ fn remove(host: &Host, a: &[Data]) -> Result { /// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path. fn rename(host: &Host, a: &[Data]) -> Result { let (path, name) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + Ok(match rename_in(&mut disk, &path, &name) { + Ok(new) => Data::Object(vec![("fs".into(), Data::String(new))]), + Err(m) => error(m), + }) +} + +/// Renames the file or folder at `path`, a link itself, to `name` in the same folder. → its new +/// path. +fn rename_in(disk: &mut Disk, path: &str, name: &str) -> Result { let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':'))); if bad || name.contains('\0') { - return Ok(error(BAD_NAME)); + return Err(BAD_NAME); } - let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; - let mut disk = host.disk.borrow_mut(); - let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) { - (Ok(f), Ok(t)) => (f, t), - (Err(m), _) | (_, Err(m)) => return Ok(error(m)), - }; - let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) }; + let new = Path::new(path).parent().map(|p| p.join(name).to_string_lossy().into_owned()).ok_or(ACCESS_DENIED)?; + let (from, to) = (disk.target(path, false)?, disk.target(&new, false)?); + let was = std::fs::symlink_metadata(&from).map_err(|_| NOT_FOUND)?; // A folder that holds the settings folder is not moved, also when its name is given in another // case where case does not matter. let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept)); if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) { - return Ok(error(ACCESS_DENIED)); + return Err(ACCESS_DENIED); } // A name that differs in case alone may name the same file, which then takes the new name. if let Ok(there) = std::fs::symlink_metadata(&to) && !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there))) { - return Ok(error(NAME_TAKEN)); + return Err(NAME_TAKEN); } // Open objects hold real paths with the names the file system keeps, and `from` keeps the last // name as given, which where case does not matter can differ in case: they are matched by the // kept name. A link is renamed itself, and no object holds a path through it. When the kept // name cannot be learned, nothing is renamed, so no object goes on under the old path's rules. - let kept = if was.file_type().is_symlink() { - from.clone() - } else { - match std::fs::canonicalize(&from) { - Ok(kept) => kept, - Err(_) => return Ok(error(WRITE_FAILED)), - } - }; - if std::fs::rename(&from, &to).is_err() { - return Ok(error(WRITE_FAILED)); - } + let kept = if was.file_type().is_symlink() { from.clone() } else { std::fs::canonicalize(&from).map_err(|_| WRITE_FAILED)? }; + std::fs::rename(&from, &to).map_err(|_| WRITE_FAILED)?; // Open objects of the file, or of files in the folder, write to the new path, and the rules for // reading apply to them there. let moved = |p: &mut Option| { @@ -1935,7 +1940,102 @@ fn rename(host: &Host, a: &[Data]) -> Result { // The old path no longer holds the file, so the report names it as well as the new one. disk.wrote(&from); disk.wrote(&to); - Ok(Data::Object(vec![("fs".into(), Data::String(new))])) + Ok(new) +} + +/// `setHidden(path, hidden)`: on Unix, where a name that starts with a dot is hidden, the file or +/// link at `path` (a link itself, never what it leads to) renamed with one dot added or its leading +/// dots taken off; → `{fs}`, its path. A file already as asked keeps its name. A name that would be +/// left empty, a folder, and every system that is not Unix give `{error}`. +fn set_hidden(host: &Host, a: &[Data]) -> Result { + let (path, on) = (arg_text(a, 0), matches!(a.get(1), Some(Data::Bool(true)))); + let mut disk = host.disk.borrow_mut(); + let at = match disk.target(&path, false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if !cfg!(unix) { + return Ok(error(NO_HIDDEN)); + } + match std::fs::symlink_metadata(&at) { + Err(_) => return Ok(error(NOT_FOUND)), + Ok(m) if m.is_dir() => return Ok(error(NOT_REGULAR)), + Ok(_) => {} + } + let Some(name) = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; + if name.starts_with('.') == on { + return Ok(Data::Object(vec![("fs".into(), Data::String(path))])); + } + let new = if on { format!(".{name}") } else { name.trim_start_matches('.').to_string() }; + if new.is_empty() { + return Ok(error(NO_HIDDEN)); + } + Ok(match rename_in(&mut disk, &path, &new) { + Ok(fs) => Data::Object(vec![("fs".into(), Data::String(fs))]), + Err(m) => error(m), + }) +} + +/// `createAlias(path, target)`: on Unix a symbolic link at `path` that leads to the real path of the +/// file `target`. `path` must be a place the script may write where nothing is, not even a link +/// that leads nowhere, and `target` a file the script may read. Every system that is not Unix gives +/// `{error}`. +fn create_alias(host: &Host, a: &[Data]) -> Result { + let (path, to) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + let at = match disk.target(&path, false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if std::fs::symlink_metadata(&at).is_ok() { + return Ok(error(NAME_TAKEN)); + } + if to.is_empty() { + return Ok(error(NOT_FOUND)); + } + let real = match disk.stat(&to) { + Ok(Some(e)) if e.file => disk.checked(&to).ok().and_then(|p| disk.scope.locate(p).ok()), + Ok(Some(_)) => return Ok(error(NOT_REGULAR)), + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + }; + let Some(real) = real else { return Ok(error(ACCESS_DENIED)) }; + #[cfg(test)] + if let Some(hook) = BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()) { + hook(&at); + } + Ok(make_link(&mut disk, &at, &real)) +} + +/// A symbolic link at the real path `at` that leads to the real path `real`. → `true`, or `{error}`. +#[cfg(unix)] +fn make_link(disk: &mut Disk, at: &Path, real: &Path) -> Data { + // Making the link fails when something took its place since it was looked up. + if std::os::unix::fs::symlink(real, at).is_err() { + return error(WRITE_FAILED); + } + // A link put in place of a folder above it since it was looked up may have taken the new link + // elsewhere: that link is removed again, when it is still the one made here. + let placed = at.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c == p)); + let ours = std::fs::read_link(at).is_ok_and(|l| l == real); + if !placed { + if ours { + let _ = std::fs::remove_file(at); + } + return error(ACCESS_DENIED); + } + // Something else at `at` replaced the new link since it was made: it is left alone. + if !ours { + return error(WRITE_FAILED); + } + disk.wrote(at); + Data::Bool(true) +} + +/// Every system that is not Unix: `{error}` with [`NO_ALIAS`]. +#[cfg(not(unix))] +fn make_link(_: &mut Disk, _: &Path, _: &Path) -> Data { + error(NO_ALIAS) } /// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on @@ -2309,13 +2409,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr })) }; let value = |s: &str| HostItem::Value(Data::String(s.to_string())); - let text = HostItem::Object(vec![ - ("notOpen".into(), value(NOT_OPEN)), - ("badMode".into(), value(BAD_MODE)), - ("noAlias".into(), value(NO_ALIAS)), - ("noHidden".into(), value(NO_HIDDEN)), - ("tooLarge".into(), value(TOO_LARGE)), - ]); + let text = + HostItem::Object(vec![("notOpen".into(), value(NOT_OPEN)), ("badMode".into(), value(BAD_MODE)), ("tooLarge".into(), value(TOO_LARGE))]); let system = if WINDOWS { "Windows" } else if cfg!(target_os = "macos") { @@ -2357,6 +2452,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("create".into(), call(link, create)), ("setLength".into(), call(link, set_length)), ("setReadonly".into(), call(link, set_readonly)), + ("setHidden".into(), call(link, set_hidden)), + ("createAlias".into(), call(link, create_alias)), ("pick".into(), call(link, pick)), ]; realm.define_file_classes(items) @@ -2367,9 +2464,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr #[cfg(test)] pub(crate) type CopyHook = Box; +/// Tests: what the next `createAlias` does with the real path of its link. +#[cfg(test)] +pub(crate) type AliasHook = Box; + #[cfg(test)] thread_local! { pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Tests: what the next `createAlias` does with the real path of its link, after looking it up + /// and before making the link. + pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7653dc083d..25ccb3bcfb 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -418,7 +418,8 @@ fn script_file_encoding_binary_ascii() { } /// A script's own folder is only read: writing there, and anywhere it was not given, is refused, -/// and with nobody to ask its file dialogs give `null`. Aliases and `execute` are not available. +/// and with nobody to ask its file dialogs give `null`. Setting `hidden` and `createAlias` are +/// refused there too, and `execute` is not available. #[test] fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { let base = folder("writes"); @@ -454,10 +455,10 @@ fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { null, false, "Script files cannot be opened in another application", - "Script file hidden setting cannot be changed", + DENIED, false, false, - "Script files cannot make aliases", + DENIED, "" ]]) ); @@ -465,6 +466,7 @@ fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { assert_eq!(r["written"], json!([])); assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists()); + assert!(!base.join("main/.keep.txt").exists() && std::fs::symlink_metadata(base.join("main/l")).is_err()); assert!(!Path::new(&outside).exists()); let _ = std::fs::remove_dir_all(base); } @@ -693,6 +695,250 @@ fn a_renamed_file_names_its_old_and_new_paths_in_written() { let _ = std::fs::remove_dir_all(base); } +#[cfg(unix)] +const NOT_FOUND: &str = "Script file does not exist"; +#[cfg(unix)] +const NOT_REGULAR: &str = "Script file is not a regular file"; +#[cfg(unix)] +const TAKEN: &str = "Script file name is already in use"; + +/// On Unix setting `hidden` renames a file with one dot added or its leading dots taken off, and the +/// object takes the new path: a file it has open stays open and is written at the new path, a file +/// already as asked keeps its name, and a name in use, a name of dots alone and a folder are refused. +#[cfg(unix)] +#[test] +fn script_file_hidden_renames_the_file_with_a_leading_dot() { + let base = folder("hidden"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, u = new File(d + '/u.txt'); u.open('w'); u.write('kept');\n\ + var before = u.fsName; u.hidden = true;\n\ + var out = [u.name, u.hidden, u.error, new File(d + '/.u.txt').hidden, new File(before).exists];\n\ + u.hidden = true; out.push(u.name, u.error, u.write('+'), u.close()); u.open('r'); out.push(u.read()); u.close();\n\ + u.hidden = false; out.push(u.name, u.hidden, new File(d + '/.u.txt').exists);\n\ + var dots = new File(d + '/...'); dots.open('w'); dots.close(); dots.hidden = false; out.push(dots.error, dots.exists);\n\ + var v = new File(d + '/v.txt'), w = new File(d + '/.v.txt'); v.open('w'); v.close(); w.open('w'); w.write('w'); w.close();\n\ + v.hidden = true; out.push(v.error, v.name, w.length);\n\ + var g = new Folder(d + '/g'); g.create(); var gf = new File(g.fsName); gf.hidden = true; out.push(gf.error, g.exists);\n\ + vc.log(out); vc.log(d);", + ) + .unwrap(); + let no_hidden = "Script file hidden setting cannot be changed"; + assert_eq!( + r["log"][0], + json!([ + ".u.txt", + true, + "", + true, + false, + ".u.txt", + "", + true, + true, + "kept+", + "u.txt", + false, + false, + no_hidden, + true, + TAKEN, + "v.txt", + 1, + NOT_REGULAR, + true + ]) + ); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + let mut names: Vec = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["...", ".v.txt", "g", "u.txt", "v.txt"]); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for name in ["u.txt", ".u.txt"] { + assert!(written.contains(&d.join(name).to_string_lossy().as_ref()), "{name} in {written:?}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `hidden` gives the file a new name, which must be a place the script may write too: a +/// file allowed on its own in a save dialog keeps its name. +#[cfg(unix)] +#[test] +fn script_file_hidden_needs_the_new_name_to_be_writable() { + let base = folder("hiddengrant"); + let picked = base.join("picked/s.txt"); + write(&picked, b"s"); + let mut s = with_data(&base); + start_framed( + &mut s, + &base, + "var f = File.saveDialog('s'); f.hidden = true; var out = [f.error, f.name, f.hidden]; out.push(f.rename('t.txt'), f.error, f.name); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[DENIED, "s.txt", false, false, DENIED, "s.txt"]])); + assert!(picked.exists() && !base.join("picked/.s.txt").exists() && !base.join("picked/t.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix `createAlias` makes a link, in a place the script may write, to a file it may read: the +/// link is an alias that resolves to the file and reads it, `hidden` tells of the link's own name, +/// setting `hidden` and `remove` change the link alone, and writing through it to a file the script +/// may only read is refused. A link that leads out of the script's places afterward reads nothing. +#[cfg(unix)] +#[test] +fn script_file_create_alias_links_to_a_file_the_script_may_read() { + let base = folder("alias"); + write(&base.join("main/keep.txt"), b"keep"); + write(&base.join("main/.hid.txt"), b"hid"); + write(&base.join("secret.txt"), b"secret"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, k = new File('keep.txt'), l = new File(d + '/l');\n\ + var out = [l.createAlias(k), l.error, l.alias, l.resolve().fsName === k.fsName, l.hidden, k.alias];\n\ + l.open('r'); out.push(l.read()); l.close();\n\ + out.push(l.open('w'), l.error, l.open('a'), l.error);\n\ + var h = new File(d + '/h'); out.push(h.createAlias('.hid.txt'), h.hidden, h.resolve().name);\n\ + l.hidden = true; out.push(l.name, l.alias, l.hidden, k.exists, k.hidden);\n\ + out.push(l.remove(), l.exists, k.exists); vc.log(out); vc.log(d);", + ) + .unwrap(); + assert_eq!( + r["log"][0], + json!([ + true, "", true, true, false, false, "keep", false, DENIED, false, DENIED, true, false, ".hid.txt", ".l", true, true, true, false, true, + false, true + ]) + ); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); + assert!(std::fs::symlink_metadata(d.join("l")).is_err() && std::fs::symlink_metadata(d.join(".l")).is_err()); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(written.contains(&d.join("l").to_string_lossy().as_ref()), "{written:?}"); + std::fs::remove_file(d.join("h")).unwrap(); + std::os::unix::fs::symlink(base.join("secret.txt"), d.join("h")).unwrap(); + let r = run_in(&mut s, &base, "var h = new File(Folder.userData.fsName + '/h'); vc.log([h.open('r'), h.error, h.alias, h.resolve()]);").unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, false, null]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `createAlias` makes nothing where the script may only read or may not go at all, at a name in use +/// (a link that leads nowhere included), to a folder, to a file outside its places, in the settings +/// folder or behind a link that leads out, to a file that is not there, or without a target. +#[cfg(unix)] +#[test] +fn script_file_create_alias_is_refused_outside_the_scripts_places() { + let base = folder("aliasdenied"); + write(&base.join("main/keep.txt"), b"keep"); + write(&base.join("secret.txt"), b"secret"); + write(&base.join("main/settings/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + std::fs::create_dir_all(base.join("main/sub")).unwrap(); + std::fs::create_dir_all(base.join("elsewhere")).unwrap(); + std::os::unix::fs::symlink(base.join("secret.txt"), base.join("main/out.txt")).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("main/settings/Script Data")); + let d = PathBuf::from(run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap()["log"][0].as_str().unwrap()); + write(&d.join("taken"), b"t"); + std::os::unix::fs::symlink(base.join("nowhere"), d.join("dangling")).unwrap(); + let text = format!( + "var d = Folder.userData.fsName, out = [];\n\ + function a(at, to) {{ var f = new File(at); out.push(f.createAlias(to), f.error); }}\n\ + a('own', 'keep.txt'); a(d + '/taken', 'keep.txt'); a(d + '/dangling', 'keep.txt'); a(d + '/dir', 'sub');\n\ + a(d + '/s', {:?}); a(d + '/g', 'settings/Script Grants.json'); a(d + '/o', 'out.txt'); a(d + '/n'); a(d + '/m', 'missing.txt');\n\ + a({:?}, 'keep.txt'); vc.log(out);", + base.join("secret.txt").to_string_lossy(), + base.join("elsewhere/x").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!( + r["log"], + json!([[ + false, + DENIED, + false, + TAKEN, + false, + TAKEN, + false, + NOT_REGULAR, + false, + DENIED, + false, + DENIED, + false, + DENIED, + false, + NOT_FOUND, + false, + NOT_FOUND, + false, + DENIED + ]]) + ); + assert!(std::fs::symlink_metadata(base.join("main/own")).is_err()); + assert_eq!(std::fs::read_dir(base.join("elsewhere")).unwrap().count(), 0); + for name in ["dir", "s", "g", "o", "n", "m"] { + assert!(std::fs::symlink_metadata(d.join(name)).is_err(), "{name}"); + } + assert_eq!(std::fs::read(d.join("taken")).unwrap(), b"t"); + assert_eq!(std::fs::read_link(d.join("dangling")).unwrap(), base.join("nowhere")); + assert_eq!(r["written"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// A link put in place of the folder an alias goes in, after the alias's place was looked up, does +/// not leave a new link where it leads. +#[cfg(unix)] +#[test] +fn script_file_alias_is_not_left_behind_a_folder_replaced_by_a_link() { + let base = folder("aliasrace"); + write(&base.join("main/keep.txt"), b"keep"); + let outside = base.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let mut s = with_data(&base); + let to = outside.clone(); + crate::script::files::BEFORE_ALIAS_LINK.with(|h| { + *h.borrow_mut() = Some(Box::new(move |at: &Path| { + let sub = at.parent().unwrap(); + std::fs::rename(sub, sub.with_file_name("moved")).unwrap(); + std::os::unix::fs::symlink(&to, sub).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName; new Folder(d + '/sub').create(); var l = new File(d + '/sub/l'); vc.log([l.createAlias('keep.txt'), l.error]);", + ); + crate::script::files::BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()); + assert_eq!(r.unwrap()["log"], json!([[false, DENIED]])); + assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0, "no link is left outside the script's places"); + let _ = std::fs::remove_dir_all(base); +} + +/// Where a hidden file is not one whose name starts with a dot, setting `hidden` and `createAlias` +/// set `error` and change nothing. +#[cfg(not(unix))] +#[test] +fn script_file_hidden_and_aliases_are_refused_off_unix() { + let base = folder("hiddenoff"); + write(&base.join("main/keep.txt"), b"keep"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, u = new File(d + '/u.txt'); u.open('w'); u.close(); u.hidden = true; var out = [u.error, u.name];\n\ + var l = new File(d + '/l'); out.push(l.createAlias('keep.txt'), l.error, l.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([["Script file hidden setting cannot be changed", "u.txt", false, "Script files cannot make aliases", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a /// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and /// `readonly`. @@ -1213,6 +1459,35 @@ fn script_file_rename_does_not_move_the_settings_folder() { let _ = std::fs::remove_dir_all(base); } +/// In a folder granted in a file dialog, a file is not renamed to the name of the settings folder, +/// and on Unix setting `hidden` does not give it that name either. +#[test] +fn script_file_rename_does_not_take_the_settings_folders_name() { + let base = folder("renamein"); + write(&base.join("cfg"), b"c"); + write(&base.join("x.txt"), b"x"); + let mut s = Session::new(); + s.attach_script_data(base.join(".cfg/Script Data")); + let hide = + if cfg!(unix) { "var h = new File(p.fsName + '/cfg'); h.hidden = true; out.push(h.error, h.name);" } else { "out.push(DENIED, 'cfg');" }; + let denied = format!("var DENIED = {DENIED:?};"); + start_framed( + &mut s, + &base, + &format!( + "{denied} var p = Folder.selectDialog('p'), x = new File(p.fsName + '/x.txt'), out = [x.rename('.cfg'), x.error, x.name]; {hide} vc.log(out);" + ), + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, "x.txt", DENIED, "cfg"]])); + assert!(!base.join(".cfg").is_file()); + assert_eq!(std::fs::read(base.join("x.txt")).unwrap(), b"x"); + assert_eq!(std::fs::read(base.join("cfg")).unwrap(), b"c"); + let _ = std::fs::remove_dir_all(base); +} + /// Where case does not matter, a folder named in another case is still the folder that holds the /// settings folder, or the settings folder itself: it is not renamed or removed. #[cfg(any(windows, target_os = "macos"))] diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index c962bf9679..30de04cf12 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -443,19 +443,32 @@ fn path_call(i: &mut Interp, this: &Value, what: &str, name: &str, args: &[Value Ok(Value::Bool(outcome(i, o, &r)?)) } -/// `createAlias`: not available, so it sets `error` and returns `false`. -fn create_alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "createAlias")?; - let m = message(i, "noAlias")?; - set_slot(i, o, ERROR, m)?; - Ok(Value::Bool(false)) +/// `createAlias(target)`: an alias at the object's path that leads to `target`, a path or a `File`. +/// Without a target the host gets an empty path, which names no file. +fn create_alias(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "createAlias")?; + let fs = match arg(args, 0) { + Value::Undefined | Value::Null => Value::str(""), + target => { + let p = parse(i, &target)?; + i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))? + } + }; + i.rooted(std::slice::from_ref(&fs), |i| path_call(i, &this, "createAlias", "createAlias", std::slice::from_ref(&fs))) } -/// Setting `hidden`: not available, so it sets `error` and changes nothing. -fn set_hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "hidden")?; - let m = message(i, "noHidden")?; - set_slot(i, o, ERROR, m)?; +/// Setting `hidden`: the host may give the file a new path, which the object then takes. A file +/// the object has open stays open, at the new path. +fn set_hidden(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "hidden")?; + let on = Value::Bool(arg(args, 0).truthy()); + let r = i.rooted(std::slice::from_ref(&path), |i| host(i, "setHidden", &[path.clone(), on]))?; + if outcome(i, o, &r)? { + let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; + if matches!(fs, Value::String(_)) { + set_slot(i, o, PATH, fs)?; + } + } Ok(Value::Undefined) } @@ -1173,7 +1186,7 @@ mod tests { ("parent", Data::String("/".into())), ]) }; - let messages = ["notOpen", "badMode", "noAlias", "noHidden"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + let messages = ["notOpen", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); let stat = move |a: Vec| -> Result { let dir = text(&a, 0) == "/d"; Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))])) diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index d675e82ec7..ee2cd364f8 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -491,10 +491,10 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file - /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and - /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, - /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `setHidden`, + /// `createAlias`, `pick` (the file dialogs, where a run may wait), `encode`, `decode`, + /// `encodingAvailable`, `current` and `locations`, with the values `system` and `lineFeed` and + /// the messages `text.notOpen` and `text.badMode`. Each object keeps its path, its `error` /// text, its open file's id, its encoding and its line feed in properties that are not /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { diff --git a/docs/mcp.md b/docs/mcp.md index 3cb8d1d239..c92792961d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2934,9 +2934,19 @@ VectorCraft reads files by these rules of its own: folder gives `null` with `Script folder mask takes too many steps to match`. - A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a `File` or `Folder` is made from it. -- `createAlias` returns `false` with `Script files cannot make aliases`, setting `hidden` sets `error` to `Script - file hidden setting cannot be changed` and changes nothing, and `execute` opens nothing and returns `false`. In the - web build every lookup fails with `Script file access is unavailable on the web`. +- On Unix a file is hidden when its name starts with a dot. Setting `hidden` renames the file in its folder with one + dot added, or with its leading dots taken off, under the rules for `rename`, and the object takes the new path, + where a file it has open stays open; a + file already as asked keeps its name, and a name of dots alone or a folder gives `false` with `error` set. + `createAlias(target)` makes a symbolic link at the object's path to a file, a path or a `File`, and returns `true`; + the link leads to the file's real path. On Windows setting `hidden` sets `error` to `Script file hidden setting + cannot be changed`, `createAlias` returns `false` with `Script files cannot make aliases`, and neither changes + anything. `execute` opens nothing and returns `false`. In the web build every lookup fails with `Script file access + is unavailable on the web`. +- `alias` is true for a link and `resolve()` gives the file it leads to, and reading or writing through the link reads + or writes that file. `hidden` tells whether the link's own name is hidden, and setting `hidden`, `rename` and + `remove` change the link and not the file it leads to, as the help page describes + (). The help page's writing members work as it describes (, @@ -2980,6 +2990,14 @@ VectorCraft writes files by these rules of its own: been made, apart from the script's own `Folder.userData`, and a folder that holds it cannot be renamed. Anything else gives `false` with `Script file access denied`. +- Setting `hidden` needs both the old and the new name to be places the script may write. `createAlias` needs the + link's place to be one the script may write where nothing is, not even a link that leads nowhere (`Script file + name is already in use`), and the file it leads to to be one the script may read, never a folder (`Script file is + not a regular file`) or a file that is not there (`Script file does not exist`). A link is looked up again each + time it is used: one that leads out of the script's places afterward is refused like any other path, and writing + through a link needs the file it leads to to be a place the script may write. When a folder above the link's place + is replaced by a link while the alias is made, the new link is removed again and `createAlias` gives `Script file + access denied`. - What a script writes is written when it closes the file or when the run ends, also when the run fails. At the run's end the files left open are written in the order they were opened. A file that `close` could not write stays open, so a later `close` tries again, and is written again when the run ends; a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e8483f80a..c34567014d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1040,6 +1040,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: `$.line` is the line of the running script, counting from 1, and `$.stack` is the current stack trace ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: both count lines in the file the code is in (the script, a file it included, a file `$.evalFile` ran, or the file of an earlier run of the named engine), and `$.stack` writes each frame as `name@file:line`, outermost first; code that `eval` or `Function` compiled keeps its own line in `[eval]`, and code whose place the engine no longer keeps is at line 0 of `[unknown]`. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. + - Scripts: the `hidden` setter and `createAlias(target)` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/)), with setting `hidden`, `rename` and `remove` acting on an alias itself ([Using File and Folder objects](https://extendscript.docsforadobe.dev/file-system-access/using-file-and-folder-objects/)). VectorCraft's own rules: on Unix a name that starts with a dot is hidden, so setting `hidden` renames the file with one dot added or its leading dots taken off, and both names must be places the script may write; `createAlias` makes a symbolic link to the real path of a file the script may read, in a place it may write where nothing is, a link that leads nowhere included; a link is checked again each time it is used; on Windows both set `error` and change nothing. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Messages over the window: `app.toast {message, level?, seconds?}` shows a message at the window's bottom right that does not stop work and closes after its time (4 seconds by default) or when clicked; at most 5 show at once, the newest lowest. Scripts raise one through `vc.run`, MCP clients through the command, and an action records it as a step. The limits are VectorCraft's own values. Tests: `cmd::toast::tests` in `vectorcraft-engine`, `toasts::tests` in `vectorcraft-ui-egui`. From 36005d9a02b1f92677427da1a3b4aa5b2a7157e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:41:47 -0800 Subject: [PATCH 088/126] Appearance: aligned copies go to `to` when the stacks are the same `appearance.duplicateItem` with `aligned: true` and `to` was refused for every selection of two or more objects, so copying a row of a graph's Legend group to `to` failed even when every label had the same rows. It now refuses `to` with aligned rows only when the stacks differ, as the params text says, and the copies land at `to` in each object as one undo step. --- crates/engine/src/cmd/appearance.rs | 24 ++++++------------------ crates/engine/src/cmd/graph/tests.rs | 23 +++++++++++++++++++++++ crates/engine/src/tests/appearance.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 5 ++--- 4 files changed, 55 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 3b23d62634..6fede6aceb 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -398,15 +398,6 @@ pub(crate) fn aligned(p: &Value, cmd: &str) -> Result { switch_or(p, "aligned", false, cmd) } -/// What the appearances of `ids` share, when there are several of them and they all exist. -pub(crate) fn shared_stack(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> Option { - if ids.len() < 2 { - return None; - } - let aps: Vec<&Appearance> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect::>()?; - Some(SharedStack::of(&aps)) -} - /// Do the appearances of `ids` differ (several objects whose stacks aren't all equal)? pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) -> bool { let mut aps = ids.iter().filter_map(|id| d.node(*id)).map(|n| &n.appearance); @@ -1502,19 +1493,16 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { let mut first_at = None; let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); let mut active_at = None; - // Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art, - // which is left out, go to `to` in an object whose stack is the same as the art's. + // Aligned rows of a mixed selection are copied right above themselves in each object. Aligned rows of objects whose + // stacks are the same, and rows of a graph design's art, which is left out, go to `to` as in one stack. let of = design_reference(s, p, C)?; - if aligned(p, C)? - && to.is_some() - && (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)))) - { + if aligned(p, C)? && to.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids)) { return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows")); } let before = s.doc()?.doc.clone(); - // With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist. - let per = - if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) }; + // With `to`, aligned rows are rows of stacks that are all the same (the art's too), so each target takes the same + // indices, each of which must exist. + let per = if to.is_some() { vec![idx.clone(); ids.len()] } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) }; s.edit("Duplicate Item", |d, _| { let mut any = false; // Copies that became the topmost visible row of their kind: the series stores their paint even when the object diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 13394fc8d0..6e0d90bf65 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -9472,6 +9472,29 @@ fn appearance_commands_given_the_axes_or_legend_group_edit_its_lines_and_labels( } } +/// Aligned rows copied to `to` given the Legend group, whose labels have the same rows, go to `to` in every label. +#[test] +fn aligned_copies_given_the_legend_group_go_to_to_when_its_labels_have_the_same_rows() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + let labels = |s: &Session| -> Vec { + let n = s.doc().unwrap().doc.node(id).unwrap().clone(); + group(&n, "Legend").children().unwrap().iter().map(|c| (*c.appearance).clone()).collect() + }; + let legend = group(s.doc().unwrap().doc.node(id).unwrap(), "Legend").id; + s.execute("appearance.addFill", &json!({"ids": [legend.0]})).unwrap(); + s.execute("appearance.addStroke", &json!({"ids": [legend.0]})).unwrap(); + let was = labels(&s); + assert!(was.len() >= 2 && was.iter().all(|a| *a == was[0]) && was[0].items.len() >= 2, "{was:?}"); + let top = was[0].items.len() - 1; + s.execute("appearance.duplicateItem", &json!({"ids": [legend.0], "index": top, "to": 0, "aligned": true})).unwrap(); + for a in labels(&s) { + assert_eq!(a.items.len(), was[0].items.len() + 1); + assert_eq!(a.items[0], was[0].items[top], "the copy is at the bottom"); + } +} + /// A row index given the Axes group, whose lines and labels have different rows, is refused unless it is `aligned`, a row /// of the backmost member's stack: then the members that share that row change, the labels keep theirs, and the graph /// keeps the change when it is drawn again. diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index a04bb89b4a..9a29f9e026 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -1129,6 +1129,30 @@ fn shared_effects_and_new_fills_reach_every_selected_object() { assert!(s.execute("appearance.moveItem", &json!({"from": 1, "to": 0, "aligned": true})).is_err()); } +/// Aligned rows copied to `to`: refused when the selected stacks differ, and placed at `to` in each object when the +/// stacks are the same, as an aligned move is. +#[test] +fn aligned_copies_go_to_to_when_the_stacks_are_the_same() { + let mut s = session(); + let (a, b) = mixed_circles(&mut s, true); + let was = (node(&s, a).appearance.clone(), node(&s, b).appearance.clone()); + assert!(s.execute("appearance.duplicateItem", &json!({"index": 1, "to": 0, "aligned": true})).is_err()); + assert_eq!((node(&s, a).appearance.clone(), node(&s, b).appearance.clone()), was, "nothing changed"); + + let mut s = session(); + let (a, b) = mixed_circles(&mut s, false); + run(&mut s, "paint.setFill", json!({"ids": [b.0], "color": "#ffff00"})); + assert_eq!(node(&s, a).appearance, node(&s, b).appearance); + let steps = s.doc().unwrap().history.undo.len(); + // The stroke (row 1) copied to the bottom of each stack: [Stroke, Fill, Stroke]. + run(&mut s, "appearance.duplicateItem", json!({"index": 1, "to": 0, "aligned": true})); + for id in [a, b] { + assert_eq!(node(&s, id).appearance.items.iter().map(AppearanceItem::kind_name).collect::>(), ["stroke", "fill", "stroke"]); + assert_eq!(stroke(&node(&s, id), 0).width, 11.0); + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); +} + /// An effect applied to the first object's stroke row goes on the equal stroke of the other /// object, which sits lower in a longer stack there. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..ab34928297 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1018,9 +1018,8 @@ as it is. When no object has one, `appearance.setItem` and `appearance.removeIte do for a row no object has, and the other commands are an error. The paint, stroke and gradient commands are also an error when the art's row is not the kind of row they edit, and `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform.*` commands without `stroke` edit the kind of the art's row. `appearance.moveItem`, `effect.move` and -`appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects', and -`appearance.duplicateItem` with `to` is also an error when two or more other objects are given, as it is without the -art. To change the art, edit the design with `graph.design`. +`appearance.duplicateItem` with `to` are an error when the art's stack differs from the other objects'. To change the +art, edit the design with `graph.design`. The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke of a path directly in a series: a weight set with `stroke.set`, `stroke.weightUp` or `stroke.weightDown`; a gradient From 5adeec1151fc947dcf5b3b493bc2c0fc87d1caff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:51:57 -0800 Subject: [PATCH 089/126] Save for Web: a Custom table keeps shifted and locked colors first, and 255 opaque colors beside transparent pixels - With transparent pixels, a fixed palette's colors mapped to transparent share the transparent pixels' slot, so at Colors 256 all 255 opaque colors keep their entries. - The preview's mappedToTransparent lists a color mapped to transparent that did not fit in the fixed palette when its pixels became transparent. - When Colors leaves a fixed palette fewer slots than it has opaque colors, shifted colors keep their slots first, then locked ones, then the others in palette order. The file keeps the palette's order. - quantize::nearest_entries hands each pixel's entry to a callback instead of collecting one per pixel. - A GIF lossy test with one fixed entry of three. Docs: params text, docs/mcp.md. --- crates/engine/src/cmd/webexport.rs | 125 +++++++++++++++++--------- crates/engine/src/tests/webexport.rs | 45 ++++++++++ crates/render/src/encode/quantize.rs | 30 +++---- crates/render/src/encode/tests_web.rs | 7 ++ docs/mcp.md | 5 +- 5 files changed, 150 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 498982a7f9..14c5fa6ebd 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together (the transparent pixels' slot when there are any), its shifted and then its locked colors kept first; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -800,11 +800,18 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 transparency: s.transparency, matte, }; - let mut ix = reduced(rgba, w, h, s, &o, &kept)?; + let (mut ix, dropped) = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. let before = ix.palette.clone(); let clear = ix.transparent.map(usize::from); - let mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect(); + let mut mapped: Vec<[u8; 3]> = before.iter().enumerate().filter(|(i, c)| Some(*i) != clear && to_clear.contains(c)).map(|(_, c)| *c).collect(); + // The colors mapped to transparent that did not fit in a fixed palette and whose pixels became + // transparent. + for c in dropped { + if !mapped.contains(&c) { + mapped.push(c); + } + } let remap = web::to_transparent(&mut ix, |i| Some(i) != clear && before.get(i).is_some_and(|c| to_clear.contains(c))); let mut sources = ix.palette.clone(); for (old, new) in remap.iter().enumerate() { @@ -868,8 +875,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 /// color table's fixed one, without the deleted colors. The pixels of a deleted color take the /// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to /// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of -/// `colors` together, and its first opaque colors that fit in the rest. -fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result { +/// `colors` together (the transparent pixels' slot when there are any), and the opaque colors that +/// fit in the rest: the `locked` ones first, in their order, then the others in palette order. Also returns the +/// colors mapped to transparent that did not fit and whose pixels became transparent. +fn reduced( + rgba: &[u8], + w: u32, + h: u32, + s: &WebSettings, + o: &PaletteOptions, + locked: &[[u8; 3]], +) -> std::result::Result<(Indexed, Vec<[u8; 3]>), String> { let table = &s.color_table; let deleted = ColorTable::colors(&table.deleted, "deleted")?; let custom = ColorTable::colors(&table.custom_palette, "customPalette")?; @@ -880,13 +896,13 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc let clear = ix.transparent.map(usize::from); let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c); if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) { - return Ok(ix); + return Ok((ix, vec![])); } let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect(); if left.is_empty() || !opaque_left(&left) { return Err(KEEP_ONE.into()); } - return Ok(quantize::quantize_to(rgba, w, h, o, &left)); + return Ok((quantize::quantize_to(rgba, w, h, o, &left), vec![])); } // A fixed palette holds at most `colors` entries, the transparent one included. let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); @@ -901,32 +917,46 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc return Err(KEEP_ONE.into()); } // The colors mapped to transparent all become the one transparent entry, so together they take - // one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of - // them and no pixel is transparent, that slot goes to the next opaque color instead. - let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true); + // one slot, and the opaque colors fill the rest. With transparent pixels that slot is theirs, so + // the colors mapped to transparent take no entry of their own and their pixels take the + // transparent pixels' entry. Without them, when no pixel takes one of those colors, the slot + // goes to the next opaque color instead. + let kept = fixed_palette(&left, &to_clear, locked, s.colors, has_clear, !has_clear); let mut ix = quantize::quantize_to(rgba, w, h, o, &kept); - clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); + let dropped = clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) { - return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false))); + return Ok((quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, locked, s.colors, has_clear, false)), vec![])); } - Ok(ix) + Ok((ix, dropped)) } -/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in -/// `to_clear` are kept and take one slot together; without it they are left out. The list holds -/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry). -fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { +/// The entries of the fixed palette `left` that fit in `colors`, in palette order. The opaque +/// colors in `locked` are kept first, in the order `locked` lists them (the colors shifted by hand +/// before the locked ones), then the other opaque colors in palette order. With `clear`, +/// the colors in `to_clear` are kept and take one slot together; without it they are left out. The +/// list holds at most 256 entries, less one when `has_clear` (the transparent pixels' entry). +fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], locked: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { let any_clear = clear && left.iter().any(|c| to_clear.contains(c)); let total = 256 - usize::from(has_clear); - let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); - let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room); - let mut clear_room = if clear { total - opaque } else { 0 }; + let room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); + let opaque = |c: &&[u8; 3]| !to_clear.contains(c); + let mut first: Vec<[u8; 3]> = vec![]; + for c in locked.iter().filter(opaque).filter(|c| left.contains(c)) { + if first.len() < room && !first.contains(c) { + first.push(*c); + } + } + let rest = room - first.len(); + let others: Vec<[u8; 3]> = left.iter().filter(opaque).filter(|c| !locked.contains(c)).take(rest).copied().collect(); + let mut clear_room = if clear { total - first.len() - others.len() } else { 0 }; left.iter() .copied() .filter(|c| { - let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room }; - let keep = *slots > 0; - *slots = slots.saturating_sub(1); + if !to_clear.contains(c) { + return first.contains(c) || others.contains(c); + } + let keep = clear_room > 0; + clear_room = clear_room.saturating_sub(1); keep }) .collect() @@ -935,32 +965,39 @@ fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: /// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to /// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the /// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later. -fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) { +/// Returns those colors that a pixel took. +fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) -> Vec<[u8; 3]> { let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect(); if dropped.is_empty() { - return; + return vec![]; } let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); - let near = quantize::nearest_entries(rgba, o, &all); - if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { - return; - } - let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) { - Some(i) => i, - None => { - // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. - let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else { - return; - }; - ix.palette.push(*c); - i + let Indexed { palette, transparent, indices, .. } = ix; + // The entry such pixels take, looked up at the first of them. + let mut entry: Option> = None; + let mut taken = vec![false; dropped.len()]; + let mut pixel = 0; + quantize::nearest_entries(rgba, o, &all, |n| { + if let Some(d) = n.and_then(|n| n.checked_sub(kept.len())) { + let e = *entry.get_or_insert_with(|| { + transparent.or_else(|| palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())).or_else(|| { + // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. + let c = kept.iter().find(|c| to_clear.contains(c))?; + let i = u8::try_from(palette.len()).ok()?; + palette.push(*c); + Some(i) + }) + }); + if let (Some(e), Some(v)) = (e, indices.get_mut(pixel)) { + *v = e; + if let Some(t) = taken.get_mut(d) { + *t = true; + } + } } - }; - for (v, n) in ix.indices.iter_mut().zip(&near) { - if n.is_some_and(|n| n >= kept.len()) { - *v = entry; - } - } + pixel += 1; + }); + dropped.into_iter().zip(taken).filter(|(_, t)| *t).map(|(c, _)| c).collect() } /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index fe3deecbef..39c95da3f6 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -582,6 +582,8 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() { let clear: Vec = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect(); let palette: Vec = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect(); let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}}); + let v = run(&mut d, "document.exportForWeb.preview", p.clone()); + assert_eq!(v["mappedToTransparent"], json!(["#0000ee"]), "the color that did not fit is listed: {v}"); let img = pixels(&one(&mut d, p)); assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0)); // Without transparent pixels the colors mapped to transparent still take one slot together. @@ -598,6 +600,49 @@ fn colour_table_fixed_palette_keeps_an_opaque_color() { assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255])); } +/// With transparent pixels, the colors of a fixed palette mapped to transparent share the +/// transparent pixels' slot, so at 256 colors all 255 opaque colors keep their entries. +#[test] +fn colour_table_fixed_palette_with_transparent_pixels_keeps_255_opaque_colors() { + // A 16×16 grid of 2×2 squares in 255 colors, the last cell left empty (transparent). + let mut s = session(32.0, 32.0); + let color = |i: usize| format!("#{:02x}{:02x}80", i, 255 - i); + for i in 0..255 { + rect(&mut s, [(i % 16) as f64 * 2.0, (i / 16) as f64 * 2.0, 2.0, 2.0], &color(i)); + } + let palette: Vec = (0..255).map(color).chain(["#000000".to_string()]).collect(); + for table in [json!({"customPalette": palette, "transparent": ["#000000"]}), json!({"customPalette": palette[..255], "transparent": []})] { + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": table}); + let img = pixels(&one(&mut s, p.clone())); + let opaque: std::collections::HashSet<[u8; 4]> = img.pixels().map(|p| p.0).filter(|p| p[3] == 255).collect(); + assert_eq!(opaque.len(), 255, "{p}"); + assert_eq!((img.get_pixel(29, 31).0, img.get_pixel(31, 31).0[3]), ([254, 1, 128, 255], 0), "{p}"); + } +} + +/// When Colors leaves a fixed palette fewer slots than it has colors, its locked and shifted colors +/// keep their slots first (shifted ones before locked ones), so a shifted color still shows its new +/// color. +#[test] +fn colour_table_fixed_palette_keeps_locked_and_shifted_colors_first() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#00ff00"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let palette = json!(["#ff0000", "#00ff00", "#0000ff"]); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": palette, "shifted": {"#0000ff": "#ff8800"}}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0), ([255, 0, 0, 255], [255, 136, 0, 255])); + // A shifted color keeps its slot before the locked ones. + let table = json!({"customPalette": palette, "locked": ["#ff0000", "#00ff00"], "shifted": {"#0000ff": "#ff8800"}}); + let img = pixels(&one(&mut s, json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table}))); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0), ([255, 0, 0, 255], [255, 136, 0, 255])); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": palette, "locked": ["#0000ff"]}}); + let v = run(&mut s, "document.exportForWeb.preview", p); + let sources: Vec<&Value> = v["colors"].as_array().unwrap().iter().map(|c| &c["source"]).collect(); + assert_eq!(sources, vec![&json!("#ff0000"), &json!("#0000ff")], "the palette keeps its order: {v}"); +} + /// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in /// the image, the other colors stay, the table shows it as shifted and locked, and the preview is /// the file. diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index fff66aa142..cad3127abd 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -205,30 +205,28 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal /// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures /// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a -/// pixel that becomes transparent, and for every pixel when `palette` is empty. -pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec> { - let px = rgba.as_chunks::<4>().0; - let colors = opaque_colors(px, o, false); +/// pixel that becomes transparent, and for every pixel when `palette` is empty. `f` gets each +/// pixel's entry in pixel order, worked out one pixel at a time. +pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]], mut f: impl FnMut(Option)) { let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect(); let index = PaletteIndex::new(&pal, o.reduction.weights()); - colors - .iter() - .zip(px) - .map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) }) - .collect() + for p in rgba.as_chunks::<4>().0 { + f(if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(opaque_color(p, o, false).map(f32::from))) }); + } } /// The color of each pixel when opaque: blended over the matte, and gray when `gray`. fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> { + px.iter().map(|p| opaque_color(p, o, gray)).collect() +} + +/// The color of the pixel `p` when opaque, as [`opaque_colors`] gives it. +fn opaque_color(p: &[u8; 4], o: &PaletteOptions, gray: bool) -> [u8; 3] { let matte = o.matte.unwrap_or([255; 3]); let blend = o.matte.is_some() || !o.transparency; - px.iter() - .map(|p| { - let a = if blend { p[3] as u32 } else { 255 }; - let c = [0, 1, 2].map(|i| ((p[i] as u32 * a + matte[i] as u32 * (255 - a) + 127) / 255) as u8); - if gray { [luma(c); 3] } else { c } - }) - .collect() + let a = if blend { p[3] as u32 } else { 255 }; + let c = [0, 1, 2].map(|i| ((p[i] as u32 * a + matte[i] as u32 * (255 - a) + 127) / 255) as u8); + if gray { [luma(c); 3] } else { c } } /// Map the pixels `px` (their opaque `colors`) to `palette` with `dither`, then drop the entries diff --git a/crates/render/src/encode/tests_web.rs b/crates/render/src/encode/tests_web.rs index 7eb480a414..79e36b3f5f 100644 --- a/crates/render/src/encode/tests_web.rs +++ b/crates/render/src/encode/tests_web.rs @@ -93,6 +93,13 @@ fn lossy_makes_runs_and_smaller_gifs() { let mut kept = ix.clone(); lossy(&mut kept, &px, 100, &fixed); assert_eq!(kept, ix); + // With one fixed entry of three, no pixel moves into or out of it, and the others still merge. + let palette: Vec<[u8; 3]> = vec![[100, 0, 0], [110, 0, 0], [120, 0, 0]]; + let indices: Vec = vec![1, 0, 0, 1, 1, 2]; + let px: Vec = indices.iter().flat_map(|&i| palette[usize::from(i)].into_iter().chain([255])).collect(); + let mut part = Indexed { width: 2, height: 3, palette, transparent: None, indices }; + lossy(&mut part, &px, 100, &[0]); + assert_eq!(part.indices, vec![1, 0, 0, 1, 1, 1]); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 85247a0c87..204b64d1b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10540,8 +10540,9 @@ ignored. Deleting every opaque color is an error, and the settings, preview and entry of transparent pixels cannot be deleted. `colorTable.customPalette: ["#rrggbb"…]` is a fixed palette (a Custom table) used instead of the reduction's own, at most `colors` entries with the transparent one included, so a color it lacks is not made again. Its colors in `transparent` all become the transparent entry and take one of the `colors` -slots together (when no pixel is transparent and no pixel takes one of them, that slot goes to its next color); its -other colors fill the remaining slots in order. The dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold +slots together (with transparent pixels they share those pixels' slot; when no pixel is transparent and no pixel takes +one of them, that slot goes to its next color), and the preview's `mappedToTransparent` lists each of them a pixel +took; its other colors fill the remaining slots, its shifted colors first, then its locked ones, then the rest in order. The dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold at most 256 colors, and `#rrggbbaa` is refused. A `reduction` change without `colorTable` in the same params clears both lists. JPEG and PNG-24 have no color table and do not read them. Presets and `webExport.settings` keep them. In the dialog a click selects one color, Shift-click selects the colors between it and the last one clicked, and From 133a5a475963ca9b694053740e7e448b59b4d88e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 18:45:23 -0800 Subject: [PATCH 090/126] Shapes: the Curvature Circle tool reaches its circles again after Deselect The tool passed over the circles it drew until the undo history moved, the tool changed or another document became active. Deselect and a pick in the Layers panel change only the selection, so the drawn circles stayed out of reach. The tool now forgets them once the selection holds none of them, after a command run from outside the tool and at the next pointer event. docs/mcp.md and the tool's module comment name every case that makes the circles reachable again. The engine's Undo test checks which path the click hit, and a comment on the set in candidate_paths says the loop skips ids that are already listed. --- crates/engine/src/tests/curvature_circle.rs | 30 +++++++++++++++++++ crates/engine/src/tooling.rs | 5 ++-- crates/tools/src/curvature_circle.rs | 32 +++++++++++++++++++-- crates/tools/src/curvature_circle/tests.rs | 21 ++++++++++++++ crates/tools/src/draw2.rs | 1 + docs/mcp.md | 6 ++-- 6 files changed, 88 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs index e862a03aaf..028ffa6487 100644 --- a/crates/engine/src/tests/curvature_circle.rs +++ b/crates/engine/src/tests/curvature_circle.rs @@ -176,6 +176,13 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { } } +/// The path the last `shape.curvatureCircle` drew on. +fn drawn_on(s: &Session) -> NodeId { + let (cmd, p) = s.journal.last().unwrap().clone(); + assert_eq!(cmd, C); + id_of(&p) +} + /// With the Curvature Circle tool, a click on a path draws the circle that matches it there, in /// one undo step; with Shift, on the other side. A click on a straight line or away from every /// path draws nothing. @@ -223,4 +230,27 @@ fn the_next_click_passes_over_the_circle_the_tool_drew() { assert_eq!(object_count(&s), count + 1, "the circle drawn first is within reach again"); let third = *s.doc().unwrap().selection.objects.first().unwrap(); assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle"); + assert_eq!(drawn_on(&s), first, "the click hit the first circle"); +} + +/// After Deselect, the pointer reaches the circle the tool drew again, with no edit in between, +/// and still does when the circle is selected again before the pointer moves. +#[test] +fn after_deselect_the_pointer_reaches_the_circle_the_tool_drew() { + for reselect in [false, true] { + let mut s = session(); + let path = parabola(&mut s); + s.select_tool("curvatureCircle", view()).unwrap(); + click(&mut s, Mods::default(), 200.0, 200.0); + let first = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_eq!(drawn_on(&s), path); + let undo = undo_len(&s); + s.execute("select.none", &json!({})).unwrap(); + if reselect { + s.execute("select.set", &json!({"ids": [first.0]})).unwrap(); + } + assert_eq!(undo_len(&s), undo, "Deselect is not an edit"); + click(&mut s, Mods::default(), 280.0, 236.0); + assert_eq!(drawn_on(&s), first, "the click hit the circle drawn first ({reselect})"); + } } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7b1caffb7c..4e4633e5d4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1536,11 +1536,12 @@ impl Session { } /// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]): - /// the Type tool and the Eyedropper clear a character range whose text is no longer selected. + /// the Type tool and the Eyedropper clear a character range whose text is no longer selected, + /// and the Curvature Circle tool lets the pointer reach its circles once none is selected. /// After `edit.undo` or `edit.redo` (`cmd`), the tool is told first, so the Type tool puts the /// caret where the step changed the text. pub(crate) fn after_command(&mut self, cmd: Option<&str>) { - if self.in_tool_actions || (!self.tool.wants_text() && self.tool.id() != "eyedropper") { + if self.in_tool_actions || (!self.tool.wants_text() && !matches!(self.tool.id(), "eyedropper" | vectorcraft_tools::curvature_circle::ID)) { return; } if let Some(cmd @ ("edit.undo" | "edit.redo")) = cmd { diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs index b484651181..7124f55cda 100644 --- a/crates/tools/src/curvature_circle.rs +++ b/crates/tools/src/curvature_circle.rs @@ -11,8 +11,9 @@ //! the side the path bends toward; with Shift held at the press, on the other side. On a straight //! stretch, at a cusp, at a corner, or where the circle would reach past the canvas, the pointer //! shows "Straight segment", "Cusp", "Corner" or "Circle too large" instead, and a click draws -//! nothing. The pointer passes over the circles the tool drew until another tool is chosen or an -//! edit, Undo or Redo is made outside the tool. +//! nothing. The pointer passes over the circles the tool drew until the selection holds none of +//! them, another tool is chosen, another document becomes active, or an edit, Undo or Redo is +//! made outside the tool. use std::collections::HashSet; @@ -58,10 +59,24 @@ pub struct CurvatureCircleTool { /// The press in progress, where the pointer was pressed: what a release draws. press: Option<(Hit, bool)>, from: Point, - /// The circles the tool drew since the history last moved outside it. + /// The circles the tool drew since the history last moved outside it or the selection last + /// held none of them. drawn: HashSet, } +impl CurvatureCircleTool { + /// After Deselect or a selection made outside the tool, the selection holds none of the + /// circles the tool drew, and the pointer reaches them again. + /// Returns whether it forgot any. + fn forget_unselected(&mut self, cx: &ToolContext) -> bool { + if self.drawn.is_empty() || cx.selection.objects.iter().any(|id| self.drawn.contains(id)) { + return false; + } + self.drawn.clear(); + true + } +} + /// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in /// `skip` left out; of paths at the same distance, a selected one, then the one on top. fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { @@ -118,6 +133,7 @@ impl Tool for CurvatureCircleTool { if !ev.pos.is_finite() { return vec![]; } + self.forget_unselected(cx); match ev.kind { PointerKind::Move => { self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); @@ -185,6 +201,16 @@ impl Tool for CurvatureCircleTool { } } + /// A command from outside the tool (Deselect, a pick in the Layers panel) may leave none of the + /// circles the tool drew selected. The circle shown under the pointer then waits for the next + /// hover. + fn after_command(&mut self, cx: &ToolContext) -> Vec { + if self.forget_unselected(cx) { + self.hover = None; + } + vec![] + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.hover = None; self.press = None; diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs index d417af58dc..1dccebecc6 100644 --- a/crates/tools/src/curvature_circle/tests.rs +++ b/crates/tools/src/curvature_circle/tests.rs @@ -198,6 +198,27 @@ fn the_next_click_passes_over_the_circle_just_drawn() { assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(drawn.0)); } +/// Once the selection holds none of the circles the tool drew (after Deselect, or a pick of another +/// object), the pointer reaches them again. +#[test] +fn a_selection_without_the_drawn_circles_makes_them_reachable() { + let line = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 450 L400 450").unwrap()); + let d = doc_with(&[circle(), circle(), line]); + let ids: Vec = d.layers[0].children().unwrap().iter().rev().map(|n| n.id).collect(); + let (drawn, under, other) = (ids[0], ids[1], ids[2]); + let p = paint(); + let holding = Selection { objects: vec![drawn], ..Selection::default() }; + let both = Selection { objects: vec![drawn, other], ..Selection::default() }; + let none = Selection::default(); + let picked = Selection { objects: vec![other], ..Selection::default() }; + for (after, want) in [(&holding, under), (&both, under), (&none, drawn), (&picked, drawn)] { + let mut t = CurvatureCircleTool::default(); + t.notify(&ToolContext { smart_guides: false, ..cx(&d, &holding, &p) }, "created"); + let cx = ToolContext { smart_guides: false, ..cx(&d, after, &p) }; + assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(want.0), "{:?}", after.objects); + } +} + /// A press that a second finger or a canceled touch drops draws nothing on the release, and an /// edit made outside the tool drops what the pointer was over. #[test] diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 3c663006e5..d5d53d9c65 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -375,6 +375,7 @@ pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec { } }); rest.reverse(); + // The loop skips ids that are already listed. let mut seen: std::collections::HashSet = v.iter().copied().collect(); for id in rest { if seen.insert(id) { diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..06ffc40f29 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7261,8 +7261,10 @@ it touches and, with Measurement Labels on, its radius by the pointer, followed radius. A click draws the circle, and a press dragged 2 screen points or more, or canceled with Escape, draws nothing; Shift held at the press puts the circle on the other side of the path. On a straight segment, at a cusp, at a corner anchor, or where the circle would reach past the canvas, the pointer shows "Straight segment", "Cusp", "Corner" or -"Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until another tool -is chosen or an edit, Undo or Redo is made outside the tool. +"Circle too large", and a click draws nothing. The pointer passes over the circles the tool drew until Deselect or a +selection made outside the tool leaves none of them selected, another tool is chosen, another document becomes +active, or an edit, Undo or Redo is made outside the tool. Selecting one of them again does not put it back out of +reach. ```json {"name":"run_command","arguments":{"command":"shape.curvatureCircle","params":{"id":12,"segment":0,"t":0.5}}} From ae9a11f661b9137714c5ea80f276389786103624 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:16:52 -0800 Subject: [PATCH 091/126] Patterns: pattern and Repeat commands refuse an unknown object id object.pattern.make, object.pattern.replaceArt and the object.repeat commands dropped an `ids` entry that names no object and acted on the other entries alone. They now return "no such object id N" and change nothing. --- crates/engine/src/cmd/patterncmds.rs | 7 ++++++- crates/engine/src/tests/pattern.rs | 24 +++++++++++++++++++++++- docs/mcp.md | 3 +++ 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index e4b6d810a6..d464be5d6f 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -43,7 +43,7 @@ pub fn specs() -> Vec { "Replace Pattern Art", [], None, - "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, for an id that names no object, and for art painted with the pattern itself → {name}", can_replace_pattern_art, pattern_replace_art ), @@ -244,10 +244,15 @@ fn ids_json(ids: &[NodeId]) -> Value { json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) } +/// The outermost objects among `ids` (layers left out), else the selected ones. An id that names +/// no object is an error, so the command never acts on the other ids alone. fn roots(s: &Session, p: &Value, cmd: &str) -> Result> { match ids_param(p, "ids", cmd)? { Some(ids) => { let st = s.doc()?; + if let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_none()) { + return Err(bad(cmd, format!("no such object id {}", id.0))); + } let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); Ok(outermost(&st.doc, sel.in_paint_order(&st.doc))) diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index 01f8e76fbc..14dda53e81 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -334,7 +334,7 @@ fn replace_art_is_refused_without_changing_anything() { for (case, p, why) in [ ("no name", json!({}), "missing name".to_string()), ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`".into()), - ("no art", json!({"name": "Dots", "ids": [9999]}), "select the art for the pattern tile".into()), + ("no art", json!({"name": "Dots", "ids": []}), "select the art for the pattern tile".into()), ("painted with it", json!({"name": "Dots", "ids": [other.0]}), "art painted with `Dots` can't be its tile".into()), ("through a pattern", json!({"name": "Dots", "ids": [via.0]}), "art painted with `Dots` can't be its tile".into()), ("through a symbol", json!({"name": "Dots", "ids": [instance.0]}), "art painted with `Dots` can't be its tile".into()), @@ -359,6 +359,28 @@ fn replace_art_is_refused_without_changing_anything() { unchanged(&s, &before, steps, "while editing"); } +/// Make, Replace Pattern Art and the Repeat commands return an error, changing nothing, when an +/// `ids` entry names no object, also beside one that does: they never act on the rest alone. +#[test] +fn pattern_and_repeat_commands_refuse_an_unknown_id_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + let blue = blue_rect(&mut s); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + for (cmd, p) in [ + ("object.pattern.replaceArt", json!({"name": "Dots", "ids": [blue.0, 9999]})), + ("object.pattern.make", json!({"name": "P", "ids": [blue.0, 9999]})), + ("object.repeat.radial", json!({"ids": [blue.0, 9999]})), + ("object.repeat.grid", json!({"ids": [9999, blue.0]})), + ("object.repeat.mirror", json!({"ids": [9999]})), + ] { + let err = s.execute(cmd, &p).unwrap_err(); + assert!(err.to_string().contains("no such object id 9999"), "{cmd}: {err}"); + assert_eq!(doc(&s), &before, "{cmd}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}: no undo step"); + } +} + fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { Arc::make_mut(&mut s.doc_mut().unwrap().doc) } diff --git a/docs/mcp.md b/docs/mcp.md index fe69653330..94057234e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6163,6 +6163,9 @@ and `height`, so a new `hSpacing` changes the tile's width. `pattern.options` st `height` that is not a positive number, such as `"width": 0`, and changes nothing. Without a `name`, `object.pattern.edit` edits the pattern that fills or strokes a selected object, and `pattern.options` changes the pattern being edited; each returns an error when there is no such pattern. `pattern.delete` requires `name`. +`object.pattern.make`, `object.pattern.replaceArt`, `object.repeat.radial`, `object.repeat.grid` and +`object.repeat.mirror` return the error "no such object id N", and change nothing, when an `ids` entry names no object, +even when the other entries name objects. With `pattern.options {moveTileWithArt: true}` (Move Tile with Art), a move of all of the tile art in pattern editing mode moves the tile by the same offset: `object.move`, `object.nudge`, `object.transform` with a translation, and drags From ba0b3d2754440ac062ff051364fd97f6035ff7ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:18:48 -0800 Subject: [PATCH 092/126] Tests: the inline refresh test's sessions share one created date refreshing_only_changed_trees_matches_the_full_pass compares the documents of two sessions. file.new stamps File Info's created date with the current time, so sessions made in different seconds differed in metadata.created and the test failed. The file's session() helper now passes created: 0. --- crates/engine/src/tests/inline.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index 37b72efa77..967276aa5f 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -13,7 +13,8 @@ use crate::*; fn session() -> Session { let mut s = Session::new(); - s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + // A fixed created date: two sessions made in different seconds would otherwise differ in it. + s.execute("file.new", &json!({"width": 800, "height": 600, "created": 0})).unwrap(); s } From 525dea58f03cee1b1022ec6997b8f8fb5e37aff2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:40:02 -0800 Subject: [PATCH 093/126] Native file: a distorted image with a malformed saved corner opens placed by its transform A native file whose `image_quad` held an entry that was not a point among its first four failed to open: `image_corners` read each entry as a `Point` and returned the error. Such corners, and an `image_quad` that is not a list, are now dropped as the file is read, and the image opens placed by its transform, as a list of other than four points already did. A point is `[x, y]` or `{"x": x, "y": y}`; values that are not taken are skipped without being kept in memory. Follows #8392. --- crates/doc/src/image_quad.rs | 44 ++++++++ crates/doc/src/node/wire.rs | 195 ++++++++++++++++++++++++++++++----- docs/mcp.md | 4 +- 3 files changed, 218 insertions(+), 25 deletions(-) diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index e07fd47760..3b32607a15 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -474,6 +474,50 @@ mod tests { assert_eq!(read.image_quad(), Some(q)); } + /// An entry among the first four that is not a point, or a field that is not a list, drops the + /// corners and leaves the rest of the image read; the entries after a bad one are skipped. + #[test] + fn malformed_corners_a_file_holds_are_dropped_as_it_is_read() { + let n = image(100, 100); + let plain: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap(); + let bad_entries = [ + serde_json::json!([[40.0, 0.0], "not a point", [100.0, 100.0], [0.0, 100.0]]), + serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], {"x": 1}]), + serde_json::json!([null, [60.0, 0.0], [100.0, 100.0], [0.0, 100.0]]), + serde_json::json!([[40.0, 0.0], [60.0], [100.0, 100.0], [0.0, 100.0], [5.0, 5.0]]), + serde_json::json!([[40.0, 0.0], [[1.0, 2.0], 3.0]]), + serde_json::json!([[40.0, 0.0], [60.0, 0.0, 1.0], [100.0, 100.0], [0.0, 100.0]]), + serde_json::json!([[40.0, 0.0], {"x": 60.0, "y": "0"}, [100.0, 100.0], [0.0, 100.0]]), + ]; + let bad_fields = [serde_json::json!("corners"), serde_json::json!(4), serde_json::json!(true), serde_json::json!({"a": [1.0, 2.0]})]; + for quad in bad_entries.into_iter().chain(bad_fields) { + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = quad.clone(); + // File text, so the fields after the corners are read from the same stream. + let text = serde_json::to_string(&v).unwrap(); + let read: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{quad}: {e}")); + assert!(read.extras().image_quad.is_none(), "{quad}"); + assert!(!read.is_distorted_image(), "{quad}"); + assert_eq!(read, plain, "{quad}"); + assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)), "{quad}"); + } + // A point with a repeated coordinate. + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = serde_json::json!([[40.0, 0.0], "SECOND", [100.0, 100.0], [0.0, 100.0]]); + let text = serde_json::to_string(&v).unwrap().replace("\"SECOND\"", r#"{"x":60.0,"y":0.0,"y":1.0}"#); + let read: Node = serde_json::from_str(&text).unwrap(); + assert_eq!(read, plain); + // Both forms of a point, whole numbers and unknown fields read as corners, from text and + // from a value. + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = serde_json::json!([[40, 0], {"y": 0.0, "x": 60.0, "z": [1, 2]}, [100.0, 100.0], {"x": 0, "y": 100}]); + let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let read: Node = serde_json::from_str(&serde_json::to_string(&v).unwrap()).unwrap(); + assert_eq!(read.image_quad(), Some(q)); + let read: Node = serde_json::from_value(v).unwrap(); + assert_eq!(read.image_quad(), Some(q)); + } + #[test] fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() { let mut n = image(10, 10); diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 9027c80b09..60a3c75d79 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -264,39 +264,188 @@ pub(super) struct NodeWire { } /// A distorted image's corners as a file holds them: a list of exactly four points, else none (the -/// image is then placed by its transform). At most five points of a longer list are kept while it -/// is read. +/// image is then placed by its transform). A point is `[x, y]` or `{"x": x, "y": y}`. A value that +/// is not a list, or a list with an entry that is not a point, is none too. Values that are not +/// taken are skipped as they are read, without being kept in memory, and at most four entries of a +/// longer list are decoded. fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result>, D::Error> { + use serde::de::{Deserializer, Error, IgnoredAny, MapAccess, SeqAccess, Visitor}; + use std::fmt::{Formatter, Result as FmtResult}; use vectorcraft_geom::Point; + + /// Skips the rest of a list; true when it held another entry. + fn rest_of_list<'de, A: SeqAccess<'de>>(mut seq: A) -> Result { + let mut more = false; + while seq.next_element::()?.is_some() { + more = true; + } + Ok(more) + } + fn rest_of_map<'de, A: MapAccess<'de>>(mut map: A) -> Result<(), A::Error> { + while map.next_entry::()?.is_some() {} + Ok(()) + } + // The visitors below give none for a value of a kind they do not take. + macro_rules! none_for { + (scalars) => { + fn visit_bool(self, _: bool) -> Result { + Ok(None) + } + fn visit_str(self, _: &str) -> Result { + Ok(None) + } + fn visit_unit(self) -> Result { + Ok(None) + } + fn visit_none(self) -> Result { + Ok(None) + } + }; + (numbers) => { + fn visit_i64(self, _: i64) -> Result { + Ok(None) + } + fn visit_u64(self, _: u64) -> Result { + Ok(None) + } + fn visit_f64(self, _: f64) -> Result { + Ok(None) + } + }; + (maps $de:lifetime) => { + fn visit_map>(self, map: A) -> Result { + rest_of_map(map)?; + Ok(None) + } + }; + } + + /// A coordinate: a number, else none. + struct Coord(Option); + impl<'de> serde::Deserialize<'de> for Coord { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Option; + fn expecting(&self, f: &mut Formatter) -> FmtResult { + f.write_str("a number") + } + fn visit_i64(self, v: i64) -> Result { + Ok(Some(v as f64)) + } + fn visit_u64(self, v: u64) -> Result { + Ok(Some(v as f64)) + } + fn visit_f64(self, v: f64) -> Result { + Ok(Some(v)) + } + fn visit_seq>(self, seq: A) -> Result { + rest_of_list(seq)?; + Ok(None) + } + none_for!(scalars); + none_for!(maps 'de); + } + d.deserialize_any(V).map(Coord) + } + } + + /// The name of a point's field. + enum Key { + X, + Y, + Other, + } + impl<'de> serde::Deserialize<'de> for Key { + fn deserialize>(d: D) -> Result { + struct V; + impl Visitor<'_> for V { + type Value = Key; + fn expecting(&self, f: &mut Formatter) -> FmtResult { + f.write_str("a field name") + } + fn visit_str(self, v: &str) -> Result { + Ok(match v { + "x" => Key::X, + "y" => Key::Y, + _ => Key::Other, + }) + } + } + d.deserialize_identifier(V) + } + } + + /// One entry of the list: a point, else none. + struct Corner(Option); + impl<'de> serde::Deserialize<'de> for Corner { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> Visitor<'de> for V { + type Value = Option; + fn expecting(&self, f: &mut Formatter) -> FmtResult { + f.write_str("a point") + } + fn visit_seq>(self, mut seq: A) -> Result { + let x = seq.next_element::()?.and_then(|c| c.0); + let y = match x { + Some(_) => seq.next_element::()?.and_then(|c| c.0), + None => None, + }; + let more = rest_of_list(seq)?; + Ok(x.zip(y).filter(|_| !more).map(|(x, y)| Point::new(x, y))) + } + fn visit_map>(self, mut map: A) -> Result { + let (mut x, mut y, mut bad) = (None, None, false); + while let Some(key) = map.next_key::()? { + let slot = match key { + Key::X => &mut x, + Key::Y => &mut y, + Key::Other => { + map.next_value::()?; + continue; + } + }; + let v = map.next_value::()?.0; + // A repeated or non-numeric coordinate makes the entry no point. + bad |= slot.is_some() || v.is_none(); + *slot = slot.or(v); + } + Ok(x.zip(y).filter(|_| !bad).map(|(x, y)| Point::new(x, y))) + } + none_for!(scalars); + none_for!(numbers); + } + d.deserialize_any(V).map(Corner) + } + } + struct Corners; - impl<'de> serde::de::Visitor<'de> for Corners { + impl<'de> Visitor<'de> for Corners { type Value = Option>; - fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, f: &mut Formatter) -> FmtResult { f.write_str("a list of points") } - fn visit_none(self) -> Result { - Ok(None) + fn visit_some>(self, d: D) -> Result { + d.deserialize_any(Corners) } - fn visit_unit(self) -> Result { - Ok(None) - } - fn visit_some>(self, d: D) -> Result { - d.deserialize_seq(Corners) - } - fn visit_seq>(self, mut seq: A) -> Result { + fn visit_seq>(self, mut seq: A) -> Result { let mut points = Vec::with_capacity(4); - while points.len() < 4 - && let Some(p) = seq.next_element::()? - { - points.push(p); + let mut malformed = false; + while points.len() < 4 && !malformed { + match seq.next_element::()? { + Some(Corner(Some(p))) => points.push(p), + Some(Corner(None)) => malformed = true, + None => break, + } } - // A fifth entry drops the field, so the rest is skipped without decoding it. - let mut extra = false; - while seq.next_element::()?.is_some() { - extra = true; - } - Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) }) + // A malformed or fifth entry drops the field, so the rest is skipped without decoding it. + let extra = rest_of_list(seq)?; + Ok(if extra || malformed { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) }) } + none_for!(scalars); + none_for!(numbers); + none_for!(maps 'de); } d.deserialize_option(Corners) } diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..930a2aff7f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7565,8 +7565,8 @@ allowed. In EMF each piece stores only the pixels inside its clip, with a pixel clip, so they write the image as the parallelogram nearest its corners and warn. Corners that would fold the image over itself, put three corners on one line, join two corners, cross the warp's horizon or lie too close together for a perspective map are an error, and nothing changes. A transform that squeezes the corners past what a perspective map -can place leaves the image at the parallelogram nearest them. A file whose `image_quad` holds other than four points, -or breaks these rules, opens with the image placed by its transform. A drag is one undo step, and a distort that leaves +can place leaves the image at the parallelogram nearest them. A file whose `image_quad` is not a list, holds other than four points +(an entry that is not a point included), or breaks these rules, opens with the image placed by its transform. A drag is one undo step, and a distort that leaves 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. From 5ea4753750be780d25bca578ede53d1b112a3afb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:36:13 -0800 Subject: [PATCH 094/126] Print: an overprinting freeform gradient leaves out the cells its plate samples write without ink On a PostScript plate, an overprinting freeform gradient left out only the cells whose color is paper white. A cell such as 0.1% cyan rounds to no ink in the 8-bit samples, yet it was kept and painted paper over the ink below. The cells are now classified from the samples the image writes. At Level 2, a field drawn again inside the clip of its inked cells was charged its samples a second time against the page limit, so a page with room for a reference to the image already kept left the placement out with the too-large warning. The check now charges the reference when the image is already kept. Follows #8400. --- crates/eps/src/print/tests.rs | 13 ++++++++ crates/eps/src/scene.rs | 62 +++++++++++++++++++++-------------- crates/eps/src/tests.rs | 32 ++++++++++++++++++ docs/target-app-parity.md | 2 +- 4 files changed, 83 insertions(+), 26 deletions(-) diff --git a/crates/eps/src/print/tests.rs b/crates/eps/src/print/tests.rs index 4c922b25e9..7600435c79 100644 --- a/crates/eps/src/print/tests.rs +++ b/crates/eps/src/print/tests.rs @@ -403,3 +403,16 @@ fn overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below ]; assert_keeps_the_ink_below(&cases); } + +#[test] +fn an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate() { + // 0.1% cyan around the left point: not paper white, but the plate's 8-bit samples write it as + // none of the ink, so the cyan below prints there. + let (faint, inked) = (Color::cmyk(0.001, 0.3, 0.0, 0.0), Color::cmyk(0.6, 0.3, 0.0, 0.0)); + let mut freeform = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, faint), GradientStop::new(1.0, inked)])); + let pure = |at: Point, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(at, c) }; + freeform.freeform = + Some(Freeform { points: vec![pure(Point::new(50.0, 50.0), faint), pure(Point::new(150.0, 50.0), inked)], ..Default::default() }); + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + assert_keeps_the_ink_below(&[("faint", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan")]); +} diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index be26ba8c4f..5643bb4127 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -8,7 +8,6 @@ use std::sync::Arc; use kurbo::Shape; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; -use vectorcraft_doc::overprint::is_white; use vectorcraft_doc::{ AppearanceItem, ColorMode, Document, Effect, ImageBlob, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject, }; @@ -1586,30 +1585,34 @@ impl<'a> Scene<'a> { let field = g.freeform_on(b).model_field(spread_scale(b)); let q = |v: f32| (unit(v) * 255.0).round() as u8; let (w, h) = (u32::from(cols), u32::from(rows)); - // Overprinting on a plate: the cells of paper white put none of the ink down, so they are - // left out, as clear pixels at Level 3 and outside a clip of the other cells at Level 2. - let blank: Option> = self.keep_below.then(|| field.grid(area, cols, rows).map(|(c, _)| is_white(&Paint::solid(c))).collect()); + let in_inks = field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)); + // Each cell's samples: its inks or its RGB, then its alpha. + let (mut samples, paper): (Vec, u8) = if in_inks { + let inks = field.grid(area, cols, rows).flat_map(|(color, a)| { + let [c, m, y, k] = color.to_cmyk(); + [q(c), q(m), q(y), q(k), q(a)] + }); + (inks.collect(), 0) + } else { + (field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect(), 255) + }; + let n = if in_inks { 5 } else { 4 }; + // Overprinting on a plate: the cells whose samples put none of the ink down are left out, + // as clear pixels at Level 3 and outside a clip of the other cells at Level 2. + let blank: Option> = self.keep_below.then(|| samples.chunks(n).map(|s| s.iter().take(n - 1).all(|&v| v == paper)).collect()); let blank = blank.filter(|b| b.contains(&true)); if blank.as_ref().is_some_and(|b| !b.contains(&false)) { return; } let keyed = self.o.level == Level::Three; - let clear = |i: usize, a: u8| if keyed && blank.as_ref().is_some_and(|b| b[i]) { 0 } else { a }; - let image = if field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)) { - let inks: Vec = field - .grid(area, cols, rows) - .enumerate() - .flat_map(|(i, (color, a))| { - let [c, m, y, k] = color.to_cmyk(); - [q(c), q(m), q(y), q(k), clear(i, q(a))] - }) - .collect(); - self.encode_inks(&inks, w, h) - } else { - let rgba: Vec = - field.display_grid(area, cols, rows).enumerate().flat_map(|(i, (c, a))| [q(c[0]), q(c[1]), q(c[2]), clear(i, q(a))]).collect(); - self.encode_image(&rgba, w, h) - }; + if let Some(b) = blank.as_ref().filter(|_| keyed) { + for (s, _) in samples.chunks_mut(n).zip(b).filter(|(_, blank)| **blank) { + if let Some(a) = s.last_mut() { + *a = 0; + } + } + } + let image = if in_inks { self.encode_inks(&samples, w, h) } else { self.encode_image(&samples, w, h) }; let Some(image) = image else { return }; let cells = blank.filter(|_| !keyed).map(|b| { let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); @@ -1631,8 +1634,13 @@ impl<'a> Scene<'a> { bp }); if let Some(bp) = &cells { - // Each row's run of cells is a rectangle of five path elements, about 60 bytes. - if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(image.inline_len) > self.max_body { + // Each row's run of cells is a rectangle of five path elements, about 60 bytes. The + // image is a reference when one encoded the same is already drawn. + let cost = self + .kept_field(&image) + .and_then(|i| self.codes.get(i)) + .map_or(image.inline_len, |c| if c.uses == 0 { c.inline_len } else { c.ref_len }); + if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(cost) > self.max_body { self.warn(TOO_LARGE); return; } @@ -1649,9 +1657,7 @@ impl<'a> Scene<'a> { /// image already kept when one is encoded the same. fn place_field(&mut self, image: ImageCode, place: Affine) { let key = image.content_key(); - let found = - self.fields.get(&key).and_then(|bucket| bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(&image)))); - let i = match found { + let i = match self.kept_field(&image) { Some(i) => i, None => { // A field that can't be placed isn't kept. @@ -1667,6 +1673,12 @@ impl<'a> Scene<'a> { self.place_image(i, place); } + /// The index in `codes` of a kept freeform gradient image encoded the same as `image`. + fn kept_field(&self, image: &ImageCode) -> Option { + let bucket = self.fields.get(&image.content_key())?; + bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(image))) + } + /// Forget the encoded images after the first `n` codes that no placement draws any longer, and /// the cache entries that name them: placed images, colorized images and fields. A code that a /// placement still draws keeps itself and every code before it. diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index cf62695254..317aefe355 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1605,6 +1605,38 @@ fn a_field_taken_back_at_the_page_limit_leaves_no_image_behind() { assert!(page.setup.contains("/VCim0 VCsrc") && !page.setup.contains("VCim1"), "{}", page.setup); } +/// On a plate at Level 2, an overprinting field drawn again inside the clip of its inked cells +/// is charged the reference to the image already kept against the page limit, not its samples a +/// second time: a page with room for that reference keeps both placements. +#[test] +fn a_repeated_field_clipped_on_a_plate_is_charged_its_reference_at_the_page_limit() { + let square = |d: &mut Document| { + // Wide spreads of pure color: paper white around the left point. + let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() }); + let pure = |x: f64, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(Point::new(x, 32.0), c) }; + g.freeform = Some(Freeform { points: vec![pure(12.0, Color::gray(0.0)), pure(52.0, Color::gray(0.6))], ..Default::default() }); + let mut n = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 64.0, 64.0)), Paint::Gradient(Box::new(g)), Paint::None, 0.0); + for it in &mut n.appearance.items { + *it.overprint_mut() = true; + } + n + }; + let twice = doc_with(|d| vec![square(d), square(d)]); + let o = EpsOptions { level: Level::Two, ..opts(&twice) }; + let full = crate::scene::Scene::new(&twice, &o).on_plate(true).run(); + assert!(full.warnings.is_empty(), "{:?}", full.warnings); + assert_eq!(reuses(&full.body, 0, Level::Two), 2, "{}", full.body); + assert!(full.body.contains("\nW\n"), "the inked cells clip the image: {}", full.body); + // The image's samples are in the setup and the body draws them twice. The limit leaves room + // for the body and the samples twice over (the clip is charged more than it writes), though + // not for the samples charged again at the second placement. + assert!(full.setup.len() > 2_000, "{}", full.setup.len()); + let limit = full.body.len() + 2 * full.setup.len(); + let page = crate::scene::Scene::new(&twice, &o).on_plate(true).with_max_body(limit).run(); + assert!(page.warnings.is_empty(), "{:?}", page.warnings); + assert_eq!((&page.setup, &page.body), (&full.setup, &full.body)); +} + /// A 200 × 200 pt document holding 8 × 8 pixels of noise as image `pic` and a three-pixel gray ramp /// as image `gray`, its first layer holding what `nodes` makes. fn image_doc_with(nodes: impl FnOnce(&mut Document) -> Vec) -> Document { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..788ca28d6c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2374,7 +2374,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - In the Separations Preview panel, an Alt-click (Option-click on macOS) on the eye of the plate shown alone shows every plate again, spot plates included, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for a second modified click on the eye (`view.separationsPreview {soloToggle: plate}`); an Alt-click on a plate shown among others shows only that plate, as the help page describes for the first one. VectorCraft's own rules: an Alt-click on a hidden plate, on another plate while one shows alone or while no plate is shown shows only that plate, and `only` still shows just the named plate when repeated (`crates/engine/src/tests/colormgmt.rs`, `crates/ui-egui/src/panels/separations.rs`). - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - - On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells of paper white out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate` and `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`. + - On a PostScript plate, an overprinting gradient that puts the plate's ink down in some places and none in others leaves the ink below where it puts none: the stretches between stops of paper white and the padding past an end that is painted paper white (with the end stop's color at Level 2 and the color of the stretch next to it in a Level 3 smooth shading, which differ when two stops share the end's offset) are clipped out of a linear, radial or diamond gradient, the wedges of paper white out of a conic one, and the cells whose 8-bit samples carry none of the plate's ink out of a freeform one (masked at Level 3, clipped at Level 2). This holds for fills, strokes and characters, and on spot plates. Where the gradient puts ink down, its amount replaces the ink below as before. A stop or point with up to half a percent of another ink in a color that counts as black puts none down, as a solid fill of that color does. PDF plates are unchanged. These are VectorCraft's own rules. Evidence: `print::tests::an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate`, `print::tests::an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate`, `print::tests::overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates` and `print::tests::an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_without_ink_on_a_postscript_plate` (`vectorcraft-eps`), `tests::print::a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates`. - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). From 6458bdd9c5a62710984896f184f9d3b6e2272788 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 20 Nov 2026 23:46:11 -0800 Subject: [PATCH 095/126] Smooth: a drag that reaches only a sliver of the next segment no longer splits it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Smooth drag that ends partway along a path splits each segment it leaves at the edge of its reach, so the anchor it adds there lies on that edge. The next drag over the same place reaches that anchor and only a sliver of the segment beyond it. Splitting that sliver gave the refit a segment of almost no length to end on, so the refit lost the path's direction there: on an ellipse dragged along its lower half, the second drag added two more anchors and left two 71.6° corners, and later drags turned the ellipse more each time. A segment leading out of the smoothed stretch that is in reach for no more than 1/64 of the reach from the stretch's anchor is now left as it is, and the stretch ends at that anchor. The same drags on the ellipse now keep the anchors of the first drag and leave no corner. --- crates/engine/src/cmd/draw2/smooth.rs | 50 ++++++++++++++++++++------- crates/engine/src/tests/draw2.rs | 22 ++++++++++++ docs/mcp.md | 6 ++-- docs/target-app-parity.md | 1 + 4 files changed, 65 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..ae3bf2d014 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -645,14 +645,28 @@ fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f (!same_anchors(&res, &anchors)).then(|| SubPath::new(res, false)) } -/// The segment `c`, which ends in the drag's reach (`near`) and starts outside it, split where it -/// enters the reach: the part outside, then the part in reach. `None` when no more than a sliver -/// is outside. -fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez, CubicBez)> { +/// How much of a segment that ends in the drag's reach is in reach ([`split_at_reach`]). +enum Reach { + /// All of it, or all but a sliver. + Whole, + /// No more than a sliver at its end. + End, + /// The part outside the reach, then the part in reach. + Split(CubicBez, CubicBez), +} + +/// Share of the tool's reach that the part of a segment in reach must be longer than for +/// [`split_at_reach`] to split the segment. VectorCraft's own value. +const REACH_SLIVER: f64 = 1.0 / 64.0; + +/// The segment `c`, which ends in the drag's reach (`near`, `radius` points) and starts outside it, +/// split where it enters the reach. No more than 2% of its parameter range outside the reach is a +/// sliver, and so is a part in reach no longer than [`REACH_SLIVER`] of the reach. +fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool, radius: f64) -> Reach { const STEPS: u32 = 32; let step = 1.0 / f64::from(STEPS); // Back from the end in reach to the first sample outside, then halving to the crossing. - let outside = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t)))?; + let Some(outside) = (1..=STEPS).map(|i| 1.0 - f64::from(i) * step).find(|t| !near(c.eval(*t))) else { return Reach::Whole }; let (mut lo, mut hi) = (outside, outside + step); for _ in 0..20 { let mid = (lo + hi) / 2.0; @@ -668,7 +682,11 @@ fn split_at_reach(c: CubicBez, near: &dyn Fn(Point) -> bool) -> Option<(CubicBez let s = c.subsegment(range); if straight { CubicBez::new(s.p0, s.p0, s.p3, s.p3) } else { s } }; - (hi > 0.02).then(|| (part(0.0..hi), part(hi..1.0))) + if hi <= 0.02 { + return Reach::Whole; + } + let (far, reach) = (part(0.0..hi), part(hi..1.0)); + if polygon_len(reach) <= REACH_SLIVER * radius { Reach::End } else { Reach::Split(far, reach) } } /// `anchors` with each run of `marked` ones smoothed by a Gaussian of spread `sigma` and refitted @@ -695,25 +713,33 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool } let mut out = anchors.to_vec(); for (a, b) in runs.into_iter().rev() { - let lo = a.saturating_sub(1); - let hi = (b + 1).min(n - 1); + let (mut lo, mut hi) = (a.saturating_sub(1), (b + 1).min(n - 1)); + // How much of the segments leading out of the run is in reach. A segment that is in reach + // only at the run's anchor stays out of the piece, so the piece ends at that anchor rather + // than in a sliver of a segment, which would leave the refit no direction to end along. + let after = if hi > b { split_at_reach(CubicBez::new(out[hi].p, out[hi].h_in, out[b].h_out, out[b].p), near, radius) } else { Reach::Whole }; + let before = if lo < a { split_at_reach(CubicBez::new(out[lo].p, out[lo].h_out, out[a].h_in, out[a].p), near, radius) } else { Reach::Whole }; + if matches!(after, Reach::End) { + hi = b; + } + if matches!(before, Reach::End) { + lo = a; + } if hi == lo { continue; } let mut piece = out[lo..=hi].to_vec(); // The anchors outside the reach, kept with the part of their segment that is outside. let (mut head, mut tail) = (None, None); - if hi > b + if let Reach::Split(far, reach) = after && let [.., inner, outer] = piece.as_mut_slice() - && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_in, inner.h_out, inner.p), near) { inner.h_out = reach.p2; tail = Some(Anchor { h_in: far.p1, ..*outer }); *outer = Anchor::with_handles(far.p3, reach.p1, far.p2); } - if lo < a + if let Reach::Split(far, reach) = before && let [outer, inner, ..] = piece.as_mut_slice() - && let Some((far, reach)) = split_at_reach(CubicBez::new(outer.p, outer.h_out, inner.h_in, inner.p), near) { inner.h_in = reach.p2; head = Some(Anchor { h_out: far.p1, ..*outer }); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..e2a6513281 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2692,6 +2692,28 @@ fn a_smooth_drag_that_only_meets_corners_adds_no_undo_step() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +/// Drags of the Smooth tool again and again along the lower half of an ellipse add no anchors after +/// the first, which splits the two segments the drag's reach ends on, and leave no corner. The +/// anchors at those splits lie on the edge of the next drag's reach, where the segment beyond each +/// one is in reach at that anchor only, so the next drag leaves that segment as it is. +#[test] +fn smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners() { + let mut s = session(); + let r = s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag: Vec<Point> = + (0..=32).map(|i| f64::from(i) / 32.0 * std::f64::consts::PI).map(|a| Point::new(200.0 + 100.0 * a.cos(), 160.0 + 60.0 * a.sin())).collect(); + let mut first = None; + for pass in 1..=6 { + smooth_pass(&mut s, &drag); + let p = path(&s, id); + let turns = smooth_anchor_turns(&p.subpaths[0]); + assert!(turns.iter().all(|t| *t < 1.0), "pass {pass} leaves a corner: {turns:?}"); + assert_eq!(p.anchor_count(), *first.get_or_insert(p.anchor_count()), "pass {pass}"); + } +} + #[test] fn join_tool_joins_two_lines() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..f15b317984 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7161,8 +7161,10 @@ round, such as a rectangle, stays as it is. Closed paths stay closed and open pa reaches the first or last anchor of an open path, the curve there leaves or arrives along the smoothed path within `radius` of that end rather than along the first or last segment, so a jagged end turns with the rest of the path; it keeps the segment's direction when the smoothed path there turns back by 90° or more. Where the stretch ends inside a -path, the curve keeps the direction of the part outside the drag. `object.path.smooth` and Simplify keep each end's -direction. +path, the curve keeps the direction of the part outside the drag. A segment leading out of the stretch that is within +`radius` of the drag for no more than 1/64 of `radius` from the stretch's anchor is left as it is, and the stretch ends +at that anchor, so a call that reaches an anchor an earlier call added at the edge of its reach does not split the +segment beyond it again (the 1/64 share is VectorCraft's own value). `object.path.smooth` and Simplify keep each end's direction. `path.smoothRegion` keeps an anchor as a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) at the anchor and also over `radius` and over twice `radius` on either side of it (on a closed path that the drag reaches all the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..8d62e68d12 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,6 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When a Smooth tool drag reaches the first or last anchor of an open path, that anchor stays where it is and the curve there leaves or arrives along the smoothed path within the reach, so a jagged first or last segment no longer sets the end's direction; an end where the smoothed path turns back by 90° or more keeps its segment's direction, and where the refitted stretch ends inside the path the curve keeps the direction of the part outside the drag. This rule is VectorCraft's own (`tests/draw2.rs`, `smoothing_an_open_path_turns_its_jagged_ends_with_the_path` and `a_smooth_drag_turns_only_the_end_it_reaches`). A Smooth tool drag keeps a corner where the path turns by more than 57.5° (an angle inside the corner under 122.5°) and rounds a wider one. An anchor is kept as a corner when the path turns by that much at the anchor and also over the drag's reach and over twice the reach on either side of it, so a jag or a bump smaller than the reach is still smoothed; [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes the tool as reducing irregularities in a path. The stretches on either side of a kept corner are smoothed and refitted on their own, and the corner keeps its place and the directions the path arrives and leaves along, on every drag, on open and closed paths, the anchor a closed path starts at included. A drag that changes no anchor adds no undo step. The threshold and the two distances are VectorCraft's own values, the same on every drag and at any Fidelity (`tests/draw2.rs`, `the_smooth_tool_keeps_corners_sharper_than_its_threshold`, `smoothing_a_closed_path_keeps_its_corners` and `a_smooth_drag_that_only_meets_corners_adds_no_undo_step`). A Smooth drag along a curved segment smooths the stretch of it in the drag's reach even when neither of the segment's anchors is in reach, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-paths.html) describes dragging along the path segment; the segment is cut where the drag enters and leaves the reach, and the parts outside keep their shape (`path.smoothRegion`). Paths of two anchors are smoothed too, and Alt with the Paintbrush smooths a selected two-anchor curve; a two-anchor straight line still gets the closed stroke. How the reach is found on a segment (samples no more than half the reach apart) is VectorCraft's own, and a straight segment is left as it is. + A segment leading out of the stretch a Smooth drag smooths that is in the drag's reach for no more than 1/64 of the reach from the stretch's anchor is left as it is, and the stretch ends at that anchor, so a drag that reaches an anchor an earlier drag added at the edge of its reach does not split the segment beyond it again or leave a corner there (`path.smoothRegion`). The 1/64 share is VectorCraft's own value (`tests/draw2.rs`, `smooth_drags_again_and_again_along_part_of_an_ellipse_add_no_anchors_or_corners`). Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). From 6fb2028149a74250e4cd2c28ce6a35740a68719e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Fri, 20 Nov 2026 23:55:44 -0800 Subject: [PATCH 096/126] Print: classify a freeform gradient's plate cells after their opacity A translucent cell whose samples round to ink before its opacity is applied, such as 0.4% cyan at 25% opacity, is written with no ink once the opacity is applied, yet it was kept and painted paper over the ink below. The cells are now classified from the samples the image writes after opacity, and RGB cells in CMYK output from their converted inks. --- crates/eps/src/scene.rs | 33 ++++++++++++++++++++++++++++++--- crates/eps/src/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 5643bb4127..35a68371b1 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -1597,9 +1597,36 @@ impl<'a> Scene<'a> { (field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect(), 255) }; let n = if in_inks { 5 } else { 4 }; - // Overprinting on a plate: the cells whose samples put none of the ink down are left out, - // as clear pixels at Level 3 and outside a clip of the other cells at Level 2. - let blank: Option<Vec<bool>> = self.keep_below.then(|| samples.chunks(n).map(|s| s.iter().take(n - 1).all(|&v| v == paper)).collect()); + // Overprinting on a plate: the cells whose samples put none of the ink down once their + // opacity is applied, as `encode_inks` and `encode_image` write them (RGB converted to + // CMYK in CMYK output), are left out, as clear pixels at Level 3 and outside a clip of the + // other cells at Level 2. + let written = |v: u8, a: u8| { + let (v, a) = (u32::from(v), u32::from(a)); + ((v * a + u32::from(paper) * (255 - a) + 127) / 255) as u8 + }; + let (cms, to_cmyk) = (self.cms.clone(), !in_inks && self.cmyk); + let intent = cms.settings().intent; + let mut converted: HashMap<[u8; 3], bool> = HashMap::new(); + let blank: Option<Vec<bool>> = self.keep_below.then(|| { + samples + .chunks(n) + .map(|s| { + let a = s.last().copied().unwrap_or(0); + if a == 0 || in_inks { + return s.iter().take(n - 1).all(|&v| written(v, a) == paper); + } + let rgb = [0, 1, 2].map(|i| s.get(i).map_or(paper, |&v| written(v, a))); + if !to_cmyk { + return rgb == [paper; 3]; + } + *converted.entry(rgb).or_insert_with(|| { + let inks = cms.srgb_to_cmyk(rgb.map(|x| f32::from(x) / 255.0), intent); + inks.iter().all(|&x| (unit(x) * 255.0).round() as u8 == 0) + }) + }) + .collect() + }); let blank = blank.filter(|b| b.contains(&true)); if blank.as_ref().is_some_and(|b| !b.contains(&false)) { return; diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 317aefe355..e6161da23d 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1637,6 +1637,30 @@ fn a_repeated_field_clipped_on_a_plate_is_charged_its_reference_at_the_page_limi assert_eq!((&page.setup, &page.body), (&full.setup, &full.body)); } +/// On a plate, an overprinting freeform gradient whose cells are translucent enough that their +/// opacity takes every sample to no ink (or to paper white in RGB) draws no image at either level. +#[test] +fn a_translucent_field_whose_samples_write_no_ink_on_a_plate_draws_no_image() { + let faint = [Color::cmyk(0.004, 0.0, 0.0, 0.0), Color::rgb(254.0 / 255.0, 254.0 / 255.0, 254.0 / 255.0)]; + for color in faint { + let d = doc_with(|d| { + let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() }); + let point = |x: f64| FreeformPoint { opacity: 0.25, ..FreeformPoint::new(Point::new(x, 32.0), color) }; + g.freeform = Some(Freeform { points: vec![point(12.0), point(52.0)], ..Default::default() }); + let mut n = path(d, shapes::rectangle(Rect::new(0.0, 0.0, 64.0, 64.0)), Paint::Gradient(Box::new(g)), Paint::None, 0.0); + for it in &mut n.appearance.items { + *it.overprint_mut() = true; + } + vec![n] + }); + for level in [Level::Three, Level::Two] { + let o = EpsOptions { level, ..opts(&d) }; + let out = crate::scene::Scene::new(&d, &o).on_plate(true).run(); + assert!(!out.body.contains("image"), "{color:?} at {level:?}: {}", out.body); + } + } +} + /// A 200 × 200 pt document holding 8 × 8 pixels of noise as image `pic` and a three-pixel gray ramp /// as image `gray`, its first layer holding what `nodes` makes. fn image_doc_with(nodes: impl FnOnce(&mut Document) -> Vec<Node>) -> Document { From c5a98e19f0f14c2a298f75f430bb0a723e052778 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 00:52:40 -0800 Subject: [PATCH 097/126] Tools: restored Spiral, Rectangular Grid and Polar Grid counts keep the current value A saved preferences file is restored onto the drawing tools without the option check that tool.setOption applies. A Spiral segment count or a grid divider count that was not a whole number (a string, a fraction, a negative, null) reset the tool to 10 or 5 instead of keeping its current count. The Arc tool's base axis took any string other than y as x. Each now keeps its current value for such a value, and a whole number keeps its existing range. While a shape is dragged out, an ignored count or axis no longer replaces the drag's starting value, so Escape puts back the values the drag started with. --- crates/tools/src/draw2/family.rs | 108 +++++++++++++++++++++++++++---- 1 file changed, 96 insertions(+), 12 deletions(-) diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index a815c02d2a..bfd930f8b1 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -493,19 +493,16 @@ impl Tool for FamilyTool { "lengthX" => self.length_x = arc_length(v, self.length_x), "lengthY" => self.length_y = arc_length(v, self.length_y), "reference" => self.reference = v.as_u64().unwrap_or(self.reference as u64).min(8) as usize, - "baseAlong" => { - if let Some(s) = v.as_str() { - self.base_along = if s.eq_ignore_ascii_case("y") { "y" } else { "x" }; - } - } + "baseAlong" => self.base_along = base_axis(v).unwrap_or(self.base_along), "slope" => self.slope = v.as_f64().filter(|n| n.is_finite()).map_or(self.slope, |n| n.clamp(-100.0, 100.0)), "fillArc" => self.fill_arc = v.as_bool().unwrap_or(self.fill_arc), // Report and persist the decay that shapes::spiral can actually draw. "decay" => self.decay = v.as_f64().unwrap_or(self.decay).clamp(5.0, 99.99), - "segments" => self.segments = v.as_u64().unwrap_or(10).clamp(2, 1000) as u32, + // A count that is not a whole number (a string, a fraction, a negative) keeps the current count. + "segments" => self.segments = v.as_u64().map_or(self.segments, |n| n.clamp(2, 1000) as u32), "clockwise" => self.clockwise = v.as_bool().unwrap_or(self.clockwise), - "rows" | "concentric" => self.rows = v.as_u64().unwrap_or(5).min(999) as u32, - "columns" | "radial" => self.columns = v.as_u64().unwrap_or(5).min(999) as u32, + "rows" | "concentric" => self.rows = v.as_u64().map_or(self.rows, |n| n.min(999) as u32), + "columns" | "radial" => self.columns = v.as_u64().map_or(self.columns, |n| n.min(999) as u32), "rowSkew" | "concentricSkew" => self.skew[0] = grid_skew(v, self.skew[0]), "columnSkew" | "radialSkew" => self.skew[1] = grid_skew(v, self.skew[1]), "frame" => self.frame = v.as_bool().unwrap_or(self.frame), @@ -519,14 +516,15 @@ impl Tool for FamilyTool { // the match above ignores leaves the drag's starting value as it was. if let Some(b) = self.before_drag.as_mut() { let finite = v.as_f64().is_some_and(f64::is_finite); + let whole = v.as_u64().is_some(); match key { "slope" if finite => b.slope = self.slope, "closed" if v.is_boolean() => b.closed = self.closed, - "baseAlong" if v.is_string() => b.base_along = self.base_along, + "baseAlong" if base_axis(v).is_some() => b.base_along = self.base_along, "decay" if v.as_f64().is_some() => b.decay = self.decay, - "segments" => b.segments = self.segments, - "rows" | "concentric" => b.rows = self.rows, - "columns" | "radial" => b.columns = self.columns, + "segments" if whole => b.segments = self.segments, + "rows" | "concentric" if whole => b.rows = self.rows, + "columns" | "radial" if whole => b.columns = self.columns, "rowSkew" | "concentricSkew" if finite => b.skew[0] = self.skew[0], "columnSkew" | "radialSkew" if finite => b.skew[1] = self.skew[1], _ => {} @@ -555,6 +553,15 @@ impl Tool for FamilyTool { } } +/// An arc's base axis from option value `v`: `"x"` or `"y"` in either case, else `None`. +fn base_axis(v: &Value) -> Option<&'static str> { + match v.as_str()? { + s if s.eq_ignore_ascii_case("x") => Some("x"), + s if s.eq_ignore_ascii_case("y") => Some("y"), + _ => None, + } +} + /// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check /// takes it). fn arc_length(v: &Value, current: f64) -> f64 { @@ -1003,6 +1010,83 @@ mod tests { assert_eq!((o["slope"].clone(), o["closed"].clone(), o["baseAlong"].clone()), (json!(-20.0), json!(false), json!("x"))); } + /// Values that are not whole numbers, as a damaged preferences file can hold them. + fn not_whole_numbers() -> [Value; 9] { + [json!("12"), json!("NaN"), json!(null), json!(true), json!(-3), json!(2.5), json!(1e300), json!({}), json!([7])] + } + + /// A spiral's segments and a grid's dividers keep their current count for a value that is not a + /// whole number; a whole number still sets the count within its range. + #[test] + fn family_tools_keep_their_counts_for_a_value_that_is_not_a_whole_number() { + for (id, key, set, high) in [ + ("spiral", "segments", 23, 1000), + ("rectangularGrid", "rows", 7, 999), + ("rectangularGrid", "columns", 8, 999), + ("polarGrid", "concentric", 7, 999), + ("polarGrid", "radial", 8, 999), + ] { + let mut t = FamilyTool::new(id); + t.set_option(key, &json!(set)); + let before = t.options(); + for v in not_whole_numbers() { + t.set_option(key, &v); + assert_eq!(t.options(), before, "{id} {key} {v}"); + } + t.set_option(key, &json!(u64::MAX)); + assert_eq!(t.options()[key], json!(high), "{id} {key}"); + } + let mut t = FamilyTool::new("spiral"); + t.set_option("segments", &json!(1)); + assert_eq!(t.options()["segments"], json!(2)); + } + + /// The Arc tool keeps its base axis for a value other than x or y. + #[test] + fn arc_keeps_its_base_axis_for_a_value_other_than_x_or_y() { + let mut t = FamilyTool::new("arc"); + t.set_option("baseAlong", &json!("Y")); + for v in [json!("z"), json!(""), json!("xy"), json!(null), json!(1)] { + t.set_option("baseAlong", &v); + assert_eq!(t.options()["baseAlong"], json!("y"), "{v}"); + } + t.set_option("baseAlong", &json!("X")); + assert_eq!(t.options()["baseAlong"], json!("x")); + } + + /// A count or base axis the option ignores while a shape is dragged out leaves the drag's + /// starting value for Escape. + #[test] + fn escape_puts_back_the_drag_start_counts_after_an_ignored_value() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + for (id, keys) in [ + ("spiral", vec!["segments"]), + ("rectangularGrid", vec!["rows", "columns"]), + ("polarGrid", vec!["concentric", "radial"]), + ("arc", vec!["baseAlong"]), + ] { + let mut t = FamilyTool::new(id); + let start = t.options(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 40.0)); + for k in [ToolKey::Up, ToolKey::Right, ToolKey::Letter('f')] { + t.key(&cx, k, Mods::default()); + } + assert_ne!(t.options(), start, "{id}"); + for k in &keys { + for v in not_whole_numbers().into_iter().chain([json!("z")]) { + t.set_option(k, &v); + } + } + t.key(&cx, ToolKey::Escape, Mods::default()); + assert_eq!(t.options(), start, "{id}"); + } + } + /// Alt adjusts the segment count in whole winds while keeping it within 2 to 1000. #[test] fn spiral_drag_alt_keeps_the_segments_within_2_to_1000() { From 1bff8f10713f2bb1890195ac7bc36471ee09a405 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 00:54:19 -0800 Subject: [PATCH 098/126] 3D: Expand Appearance keeps curves on Inflate faces, interior bevel edges and twist cuts Extrude & Bevel and Inflate drew several edges along the art's curves as straight segments with a corner at every sample point, so Object > Expand Appearance gave them corner anchors: - The edges between two bevel steps and between two wall slices had no outline. Every band now gets the outline of both its rings, and the two faces that share a ring draw the same curves. - A twist cut a wall's edge at points on the chord between two samples. The cut corners now lie on the art's curve, and each piece follows its own part of the curve, so the wall meets the cap along the cap's curve. - Inflate's flat back, its side walls, and the cells of its front and puffed back along the outline were polygons. They now follow the art's curves, the cells within the sampling tolerance. The search for the cells' edges along the outline stops after 4,194,304 edges per solid (VectorCraft's own limit); the rest stay straight. Visibility, depth order and face counts are still worked out on the sampled polygons. Tests in crates/three-d/src/solid/tests_curves.rs. --- crates/three-d/src/solid.rs | 3 + crates/three-d/src/solid/build.rs | 70 +++++-- crates/three-d/src/solid/inflate.rs | 138 +++++++++++-- crates/three-d/src/solid/membrane.rs | 21 ++ crates/three-d/src/solid/outline.rs | 47 ++++- crates/three-d/src/solid/rings.rs | 1 + crates/three-d/src/solid/tests_curves.rs | 237 +++++++++++++++++++++++ docs/target-app-parity.md | 3 +- docs/three-d.md | 21 +- 9 files changed, 495 insertions(+), 46 deletions(-) create mode 100644 crates/three-d/src/solid/tests_curves.rs diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 71f039724f..27b63477da 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -575,3 +575,6 @@ mod tests_inflate_shading; #[cfg(test)] mod tests_limits; + +#[cfg(test)] +mod tests_curves; diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index d883ad14b8..20c147b1cd 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -271,14 +271,10 @@ impl<'a> Builder<'a> { /// The band between two partner rings (same length), as one quad per edge, or for a twisted /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the /// direction (before rotation) the band faces away from the solid, for orienting normals. - pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None, None) - } - - /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the - /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. - /// With `side`, each quad carries where its corners lie on the side unrolled flat - /// ([`Facet::surface`]). + /// With `curves`, the pieces of curve the rings' edges follow and the outlines at `a` and `b`, + /// each quad keeps its edges along the profile curved. An edge cut into pieces is cut at points + /// of its curve, each piece taking an equal share of the edge's piece of curve. With `side`, + /// each quad carries where its corners lie on the side unrolled flat ([`Facet::surface`]). pub(super) fn curved_band( &mut self, a: &[V3], @@ -303,9 +299,22 @@ impl<'a> Builder<'a> { for i in 0..n { let j = (i + 1) % n; let pieces = cuts.get(i).copied().unwrap_or(1).max(1); + let span = curves.as_ref().and_then(|w| w.spans.get(i).copied().flatten()); + let places = curves.as_ref().map_or([None, None], |w| w.places); + // Where the edge's curve is at share `s` of it. + let t = |s: f64| span.map_or(0.0, |span| span.t0 + (span.t1 - span.t0) * s); + // A cut corner on a ring that follows a curve lies on the curve, so the pieces' edges + // follow the same curve as the cap's edge they meet. + let corner = |p: V3, q: V3, s: f64, ring: usize| match (span, places.get(ring).copied().flatten()) { + (Some(span), Some(place)) if s > 0.0 && s < 1.0 => { + let v = place(&span, t(s)); + if v.0.is_finite() && v.1.is_finite() && v.2.is_finite() { v } else { lerp(p, q, s) } + } + _ => lerp(p, q, s), + }; for k in 0..pieces { let (s0, s1) = (k as f64 / pieces as f64, (k + 1) as f64 / pieces as f64); - let quad = vec![lerp(a[i], a[j], s0), lerp(a[i], a[j], s1), lerp(b[i], b[j], s1), lerp(b[i], b[j], s0)]; + let quad = vec![corner(a[i], a[j], s0, 0), corner(a[i], a[j], s1, 0), corner(b[i], b[j], s1, 1), corner(b[i], b[j], s0, 1)]; // A twist bends the strip between two slices into a saddle: its normal is the whole // quad's average (Newell's), not one corner's triangle, which leans far to one side. let mut normal = newell(std::slice::from_ref(&quad)); @@ -343,10 +352,14 @@ impl<'a> Builder<'a> { }); } } - if let Some(w) = curves.as_mut().filter(|_| pieces == 1) - && let Some(span) = w.spans.get(i).copied().flatten() + if let Some(w) = curves.as_mut() + && let Some(span) = span { - self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, quad, w.near, w.far, w.budget))); + // An edge cut on its chord, with no place on the curve for its cut corners, + // stays straight. + let near = w.near.filter(|_| pieces == 1 || w.places[0].is_some()); + let far = w.far.filter(|_| pieces == 1 || w.places[1].is_some()); + self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), quad, near, far, w.budget))); } } } @@ -397,9 +410,15 @@ pub(super) struct WallCurves<'a> { pub(super) spans: &'a [Option<Span>], pub(super) near: Option<&'a Along<'a>>, pub(super) far: Option<&'a Along<'a>>, + /// Where a point of a span's curve lies in view space on the band's two rings, for the corners + /// where a twisted wall's edge is cut ([`cuts`]). + pub(super) places: [Option<&'a Place<'a>>; 2], pub(super) budget: &'a mut Budget, } +/// Where the point at `t` on a span's curve lies in view space on one ring. +pub(super) type Place<'a> = dyn Fn(&Span, f64) -> V3 + 'a; + /// Where a band of the side lies on the side unrolled flat ([`super::side`]): the x of each end of /// each edge of its rings, and the y of its two rings. pub(super) struct SideBand<'a> { @@ -704,12 +723,19 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio // and within the sampling tolerance (which the inset rings themselves keep to) where it is. let sampled = (size / 2000.0).max(0.05); let maps: Vec<Placing> = steps.iter().map(|s| Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, s.t), z(s.t))).collect(); - let at: Vec<_> = steps + let places: Vec<_> = steps .iter() .zip(&maps) .map(|(s, m)| { - let (w, camera) = (s.inset, &camera); - move |span: &Span, t: f64| camera.project(m.place(offset(span, t, w))) + let w = s.inset; + move |span: &Span, t: f64| m.place(offset(span, t, w)) + }) + .collect(); + let at: Vec<_> = places + .iter() + .map(|place| { + let camera = &camera; + move |span: &Span, t: f64| camera.project(place(span, t)) }) .collect(); // A step that is not inset moves the art point by point, affinely without perspective. @@ -762,10 +788,16 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio } else { 0.0 }; - // The edges a band shares with a cap follow the cap's curves; the edges between two bands - // stay straight, within the sampling tolerance. - let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); - let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); + // Each ring of a band follows the outline at its step: the edges a band shares with a cap + // follow the cap's curves, and an edge two bands share follows the same curves in both. + let place = |k: usize| places.get(k).map(|p| p as &Place); + let curves = Some(WallCurves { + spans: &traced.spans, + near: along.get(k), + far: along.get(k + 1), + places: [place(k), place(k + 1)], + budget: &mut budget, + }); let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } diff --git a/crates/three-d/src/solid/inflate.rs b/crates/three-d/src/solid/inflate.rs index 812cf88a42..5826c28e6b 100644 --- a/crates/three-d/src/solid/inflate.rs +++ b/crates/three-d/src/solid/inflate.rs @@ -1,7 +1,8 @@ -use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward}; +use super::build::{Builder, Built, Camera, Keep, Order, Place, Placing, Turn, WallCurves, check_bounds, cuts, fit, newell, outward}; use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material}; -use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings}; -use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; +use super::outline::{self, Along, Budget, CURVE_TOLERANCE, EdgeCurve}; +use super::rings::{MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings_traced}; +use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, V3, Vec2, View}; /// The slices the sides are cut into: more to follow a twist or taper. fn slices(o: &Inflate) -> usize { @@ -11,6 +12,8 @@ fn slices(o: &Inflate) -> usize { /// A shape to inflate: its rings and the membrane under them on the grid of the bounds. struct Puff { rings: Vec<Vec<Point>>, + /// The rings with the piece of curve each edge follows. + traced: Vec<Ring>, /// The index of the rings' edges. edges: Edges, cell: f64, @@ -50,7 +53,8 @@ fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result<Op PUFFED.with(|n| n.set(n.get() + 1)); let size = bounds.width().max(bounds.height()); let most = outline_pieces(path, bounds, o)?; - let rings = solid_rings(path, rule, size, MAX_SOLID_POINTS, most)?; + let traced = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most)?; + let rings: Vec<Vec<Point>> = traced.iter().map(|r| r.points.clone()).collect(); if rings.is_empty() { return Ok(None); } @@ -73,7 +77,7 @@ fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result<Op } // A circle of radius r puffs into a half sphere of radius r at 50 % (its membrane peaks at r²/4). let height = 2.0 * m.peak.sqrt() * o.volume / 50.0; - Ok(Some(Puff { rings, edges, cell, nx, ny, m, height })) + Ok(Some(Puff { rings, traced, edges, cell, nx, ny, m, height })) } /// Inflate: the shape puffed out like a cushion, its edge kept where the art's outline is. @@ -209,6 +213,10 @@ thread_local! { /// cells together ([`crate::mesh::flat_triangles`]). pub(super) const MAX_FLAT_WORK: usize = 1 << 26; +/// Most edges of the outline one inflated surface may look at to find the edges of its cells that +/// lie along the outline ([`Edges::holding`]). Past it, the cells' remaining edges stay straight. +pub(super) const MAX_RIM_WORK: usize = 1 << 22; + /// Most corners the pieces of one such cell may have. pub(super) const MAX_FLAT_CORNERS: usize = 4096; @@ -242,7 +250,7 @@ fn mark_surface(b: &mut Builder<'_>, before: usize, points: [Point; 3], center: fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Keep) -> Result<Built, String> { #[cfg(test)] INFLATED.with(|n| n.set(n.get() + 1)); - let Puff { rings, edges, cell, nx, ny, m, height } = p; + let Puff { rings, traced, edges, cell, nx, ny, m, height } = p; let outline: Vec<(Rect, vectorcraft_geom::SubPath)> = rings .iter() .filter_map(|r| { @@ -286,6 +294,58 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee let half = o.depth / 2.0; // The back: turned and scaled by the twist and taper, its puff too. let back_turn = Turn::new(bounds, o.twist, o.taper, 1.0); + // The outline of the front and the back where the surface meets it, through the art's curves: + // the cells' edges along it follow its curves within the sampling tolerance, as the cells' + // corners there lie on its sampled points and edges. + let mut budget = Budget::default(); + let sampled = (bounds.width().max(bounds.height()) / 2000.0).max(0.05); + let (front_map, back_map) = + (Placing::new(&camera, center, Turn::new(bounds, 0.0, 1.0, 0.0), half), Placing::new(&camera, center, back_turn, -half)); + let (front_at, back_at) = ( + |span: &Span, t: f64| camera.project(front_map.place(span.curve.eval(t))), + |span: &Span, t: f64| camera.project(back_map.place(span.curve.eval(t))), + ); + let (front_point, back_point) = (|p: Point| camera.project(front_map.place(p)), |p: Point| camera.project(back_map.place(p))); + let affine = camera.center_and_eye().1.is_none(); + let front_rim = Along { at: &front_at, map: Some(&front_point), affine, tolerance: sampled }; + let back_rim = Along { at: &back_at, map: Some(&back_point), affine, tolerance: sampled }; + // Where each ring's edges start among all the rings' edges, as the edge index counts them. + let starts: Vec<usize> = rings + .iter() + .scan(0usize, |s, r| { + let at = *s; + *s = s.saturating_add(r.len()); + Some(at) + }) + .collect(); + let rim_work = std::cell::Cell::new(MAX_RIM_WORK); + // The pieces of curve the edges of `pieces` (art points, lifted by `lifts`) follow where they + // lie along the outline: an edge whose two ends are on the outline, on one of its edges. + let rim = |pieces: &[Vec<Point>], lifts: &[Vec<f64>]| -> Vec<Vec<Option<EdgeCurve>>> { + pieces + .iter() + .zip(lifts) + .map(|(p, h)| { + let n = p.len(); + (0..n) + .map(|k| { + let (a, b) = (*p.get(k)?, *p.get((k + 1) % n)?); + if h.get(k).copied() != Some(0.0) || h.get((k + 1) % n).copied() != Some(0.0) { + return None; + } + let mut work = rim_work.get(); + let found = edges.holding(a, b, 1e-9, &mut work); + rim_work.set(work); + let (e, sa, sb) = found?; + let r = starts.partition_point(|s| *s <= e).checked_sub(1)?; + let span = traced.get(r)?.spans.get(e - starts.get(r)?)?.as_ref().copied()?; + let t = |s: f64| span.t0 + (span.t1 - span.t0) * s; + (sa != sb).then(|| (span, t(sa), t(sb))) + }) + .collect() + }) + .collect() + }; // The grid's cells, those the surface rises steeply across (near the outline) cut into // halves or quarters each way, so the steep rim is drawn in facets as fine as its curve. // Every corner sits on one fine lattice (a quarter cell), computed the same way wherever it @@ -477,7 +537,10 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if let Some(triangles) = triangles { let order = if flat { Order::Last } else { Order::Depth }; for points in triangles { - let front = points.map(|q| camera.place(q, half + lift(q))); + let lifts = points.map(&lift); + let front: [V3; 3] = std::array::from_fn(|k| camera.place(points[k], half + lifts[k])); + let found = std::cell::OnceCell::new(); + let curves = || found.get_or_init(|| rim(&[points.to_vec()], &[lifts.to_vec()])); let before = b.facets.len(); let outward = newell(&[front.to_vec()]); if smoothed { @@ -485,11 +548,13 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } else { b.face(vec![front.to_vec()], outward, order)?; } + b.outline(before, |c| outline::edges(c, curves(), &front_rim, &mut budget)); if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Front); } if o.both_sides && o.cap { - let back = points.map(|q| camera.place(back_turn.apply(q), -half - lift(q) * back_turn.scale)); + let back: [V3; 3] = + std::array::from_fn(|k| camera.place(back_turn.apply(points[k]), -half - lifts[k] * back_turn.scale)); let before = b.facets.len(); let n = newell(&[back.to_vec()]); // The back winds the same way round as the front, so its outward @@ -506,6 +571,7 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee } else { b.face(vec![back.to_vec()], outward, order)?; } + b.outline(before, |c| outline::edges(c, curves(), &back_rim, &mut budget)); if o.map_surface { mark_surface(&mut b, before, points, center, outward, PlanarFace::Back); } @@ -521,7 +587,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, half + h)).collect()).collect(); let n = newell(&front); let order = if flat { Order::Last } else { Order::Depth }; + let found = std::cell::OnceCell::new(); + let curves = || found.get_or_init(|| rim(&pieces, &lifts)); + let before = b.facets.len(); b.face(front, n, order)?; + b.outline(before, |c| outline::edges(c, curves(), &front_rim, &mut budget)); if o.both_sides && o.cap { // The back winds the same way round as the front, so its outward normal is // reversed. @@ -531,7 +601,9 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee .map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(back_turn.apply(*q), -half - h * back_turn.scale)).collect()) .collect(); let n = newell(&back); + let before = b.facets.len(); b.face(back, V3(-n.0, -n.1, -n.2), order)?; + b.outline(before, |c| outline::edges(c, curves(), &back_rim, &mut budget)); } } } @@ -541,7 +613,12 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee let back: Vec<Vec<V3>> = rings.iter().map(|r| r.iter().map(|p| camera.place(back_turn.apply(*p), -half)).collect()).collect(); // The back turned toward the viewer covers the walls it overlaps, even those nearer than // its center: twisted walls, and the walls of a fill inside the solid of its stroke. + let before = b.len(); b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last)?; + // The flat back is the art turned and scaled: its curves map exactly without perspective. + let along = Along { tolerance: CURVE_TOLERANCE, ..back_rim }; + let traced: Vec<&Ring> = traced.iter().collect(); + b.outline(before, |c| outline::face(&traced, c, &along, &mut budget)); } if o.depth > 0.0 { // The sides, cut into slices that follow a twist or taper. @@ -558,10 +635,45 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee if b.len().saturating_add(edges.saturating_mul(slices)) > MAX_SOLID_FACES { return Err(TOO_COMPLEX_SURFACE.into()); } - let sides = |b: &mut Builder<'_>, pieces: &[Vec<usize>]| -> Result<(), String> { - for (ring, pieces) in rings.iter().zip(pieces) { + // Each slice's ring follows the art's curves, turned and scaled, at its depth. + let maps: Vec<Placing> = (0..=slices) + .map(|k| { + let t = k as f64 / slices as f64; + Placing::new(&camera, center, Turn::new(bounds, o.twist, o.taper, t), half - o.depth * t) + }) + .collect(); + let places: Vec<_> = maps.iter().map(|m| move |span: &Span, t: f64| m.place(span.curve.eval(t))).collect(); + let slice_at: Vec<_> = places + .iter() + .map(|place| { + let camera = &camera; + move |span: &Span, t: f64| camera.project(place(span, t)) + }) + .collect(); + let point_maps: Vec<_> = maps + .iter() + .map(|m| { + let camera = &camera; + move |p: Point| camera.project(m.place(p)) + }) + .collect(); + let along: Vec<Along> = slice_at + .iter() + .zip(&point_maps) + .map(|(at, map)| Along { at, map: Some(map as &dyn Fn(Point) -> Point), affine, tolerance: CURVE_TOLERANCE }) + .collect(); + let place = |k: usize| places.get(k).map(|p| p as &Place); + let sides = |b: &mut Builder<'_>, pieces: &[Vec<usize>], budget: &mut Budget| -> Result<(), String> { + for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(pieces) { for k in 0..slices { - b.band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0))?; + let curves = WallCurves { + spans: &traced.spans, + near: along.get(k), + far: along.get(k + 1), + places: [place(k), place(k + 1)], + budget: &mut *budget, + }; + b.curved_band(&at(ring, k), &at(ring, k + 1), pieces, |i| outward(ring, i, 0.0), Some(curves), None)?; } } Ok(()) @@ -578,11 +690,11 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee own_sides = Some((own, b.mesh.take())); } } - sides(&mut b, &pieces)?; + sides(&mut b, &pieces, &mut budget)?; if let Some((own, faces)) = own_sides { let mut m = Builder::new(&camera, o.cap, false, Keep::Faces); m.mesh = faces; - match sides(&mut m, &own) { + match sides(&mut m, &own, &mut budget) { Ok(()) => b.mesh = m.mesh, Err(_) => b.lose_mesh(), } diff --git a/crates/three-d/src/solid/membrane.rs b/crates/three-d/src/solid/membrane.rs index e8a855e29a..833b9de8a0 100644 --- a/crates/three-d/src/solid/membrane.rs +++ b/crates/three-d/src/solid/membrane.rs @@ -130,6 +130,27 @@ impl Edges { } } + /// The edge that both `a` and `b` lie on within `tolerance`: its index, counted through the + /// rings in order, and how far along it `a` and `b` lie (0 at its start, 1 at its end). Only the + /// bucket of the midpoint of `a` and `b` is looked in, and each edge looked at takes one from + /// `work`, which is not counted against the index's own budget: `None` once `work` is spent. + pub(super) fn holding(&self, a: Point, b: Point, tolerance: f64, work: &mut usize) -> Option<(usize, f64, f64)> { + let m = a.midpoint(b); + let (i, j) = (self.cell(m.x, self.origin.x), self.cell(m.y, self.origin.y)); + let bucket = self.buckets.get((j * self.n as isize + i) as usize)?; + for k in bucket { + *work = work.checked_sub(1)?; + let Some(&(p, q)) = self.edges.get(*k as usize) else { continue }; + let d = q - p; + if d.hypot2() < 1e-18 || segment_distance(a, p, q) > tolerance || segment_distance(b, p, q) > tolerance { + continue; + } + let along = |v: Point| ((v - p).dot(d) / d.hypot2()).clamp(0.0, 1.0); + return Some((*k as usize, along(a), along(b))); + } + None + } + /// Call `f` with each edge whose bounding box overlaps `r` (an edge in several of the /// buckets `r` covers comes more than once). fn each(&self, r: Rect, mut f: impl FnMut(Point, Point)) { diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs index 93d9d70340..75d62251f2 100644 --- a/crates/three-d/src/solid/outline.rs +++ b/crates/three-d/src/solid/outline.rs @@ -173,11 +173,13 @@ pub(super) fn face(rings: &[&Ring], points: &[Vec<Point>], step: &Along, budget: /// The outline of a wall's quad `quad` (`a`, `a'`, `b'`, `b` projected: the edge at `near` from /// `a` to `a'`, then the edge at `far` back from `b'` to `b`), whose edges along the profile follow -/// `span`. An edge without its outline stays straight. `None` when neither edge is curved. -pub(super) fn wall(span: &Span, quad: &[Point], near: Option<&Along>, far: Option<&Along>, budget: &mut Budget) -> Option<PathData> { +/// `span`'s curve from `t.0` to `t.1` (all of `span`, or the piece of it one cut of a twisted wall +/// takes). An edge without its outline stays straight. `None` when neither edge is curved. +pub(super) fn wall(span: &Span, t: (f64, f64), quad: &[Point], near: Option<&Along>, far: Option<&Along>, budget: &mut Budget) -> Option<PathData> { let [a, a2, b2, b] = <[Point; 4]>::try_from(quad).ok()?; - let front = near.and_then(|near| piece(near, span, span.t0, span.t1, (span.t1, span.t0), a, a2, budget)); - let back = far.and_then(|far| piece(far, span, span.t1, span.t0, (span.t0, span.t1), b2, b, budget)); + let (t0, t1) = t; + let front = near.and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, budget)); + let back = far.and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, budget)); if front.is_none() && back.is_none() { return None; } @@ -195,3 +197,40 @@ pub(super) fn wall(span: &Span, quad: &[Point], near: Option<&Along>, far: Optio path.close_path(); Some(PathData::from_bezpath(&path)) } + +/// A piece of curve one edge of a face follows: the span, and the parameters on its curve where the +/// edge starts and ends. +pub(super) type EdgeCurve = (Span, f64, f64); + +/// The outline of a face whose contours `points` (projected) have some edges along pieces of curve: +/// `curves[c][k]` is the piece edge `k` of contour `c` follows, at `step`, or `None` for a straight +/// edge. `None` when no edge is curved. +pub(super) fn edges(points: &[Vec<Point>], curves: &[Vec<Option<EdgeCurve>>], step: &Along, budget: &mut Budget) -> Option<PathData> { + if points.len() != curves.len() || curves.iter().flatten().all(Option::is_none) { + return None; + } + let mut path = BezPath::new(); + let mut curved = false; + for (points, curves) in points.iter().zip(curves) { + let n = points.len(); + let Some(&first) = points.first() else { continue }; + if curves.len() != n { + return None; + } + path.move_to(first); + for (k, c) in curves.iter().enumerate() { + let (p, q) = (points.get(k).copied().unwrap_or(first), points.get((k + 1) % n).copied().unwrap_or(first)); + match c.as_ref().and_then(|(span, t0, t1)| piece(step, span, *t0, *t1, (*t1, *t0), p, q, budget)) { + Some(cubics) => { + curved = true; + cubics.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)); + } + // The edge back to the first point is drawn by `close_path`. + None if k + 1 < n => path.line_to(q), + None => {} + } + } + path.close_path(); + } + curved.then(|| PathData::from_bezpath(&path)) +} diff --git a/crates/three-d/src/solid/rings.rs b/crates/three-d/src/solid/rings.rs index 882bd245af..195fe0039e 100644 --- a/crates/three-d/src/solid/rings.rs +++ b/crates/three-d/src/solid/rings.rs @@ -106,6 +106,7 @@ pub(super) const DEBRIS: f64 = 1e-6; /// contours were merged. An empty answer is an answer: contours that cancel (a square drawn twice /// under even-odd), or that are all thinner than [`DEBRIS`], fill nothing, so nothing is built. /// Each curve takes at most `most` pieces, on the profile as drawn and on the merged outline. +#[cfg(test)] pub(super) fn solid_rings(path: &PathData, rule: FillRule, size: f64, limit: usize, most: u32) -> Result<Vec<Vec<Point>>, String> { Ok(solid_rings_traced(path, rule, size, limit, most)?.into_iter().map(|r| r.points).collect()) } diff --git a/crates/three-d/src/solid/tests_curves.rs b/crates/three-d/src/solid/tests_curves.rs new file mode 100644 index 0000000000..07ba46d19f --- /dev/null +++ b/crates/three-d/src/solid/tests_curves.rs @@ -0,0 +1,237 @@ +use vectorcraft_geom::{BezPath, CubicBez, FillRule, PathData, Point, Rect}; + +use super::build::Turn; +use super::*; + +fn shape(b: &BezPath) -> (PathData, Rect) { + let p = PathData::from_bezpath(b); + let r = p.bounds().unwrap(); + (p, r) +} + +/// Straight on, without perspective. +fn front() -> View { + View { rotation_x: 0.0, rotation_y: 0.0, rotation_z: 0.0, perspective: 0.0, ..View::default() } +} + +/// A circle of four cubics about `c`. +fn circle(c: Point, r: f64) -> BezPath { + let k = 0.552_284_749_830_793_6 * r; + let mut b = BezPath::new(); + b.move_to((c.x + r, c.y)); + b.curve_to((c.x + r, c.y + k), (c.x + k, c.y + r), (c.x, c.y + r)); + b.curve_to((c.x - k, c.y + r), (c.x - r, c.y + k), (c.x - r, c.y)); + b.curve_to((c.x - r, c.y - k), (c.x - k, c.y - r), (c.x, c.y - r)); + b.curve_to((c.x + k, c.y - r), (c.x + r, c.y - k), (c.x + r, c.y)); + b.close_path(); + b +} + +/// A "D" with its counter: straight stems, round bowls, and corners where they meet. +fn letter_d() -> BezPath { + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.line_to((40.0, 0.0)); + b.curve_to((95.0, 0.0), (95.0, 100.0), (40.0, 100.0)); + b.line_to((0.0, 100.0)); + b.close_path(); + b.move_to((20.0, 20.0)); + b.line_to((20.0, 80.0)); + b.line_to((40.0, 80.0)); + b.curve_to((70.0, 80.0), (70.0, 20.0), (40.0, 20.0)); + b.close_path(); + b +} + +fn square(x: f64, y: f64, s: f64) -> BezPath { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + s, y)); + b.line_to((x + s, y + s)); + b.line_to((x, y + s)); + b.close_path(); + b +} + +/// A path's curved segments, segments and anchors. +fn anatomy(p: &PathData) -> [usize; 3] { + let mut n = [0; 3]; + for sp in &p.subpaths { + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + n[0] += (0..count).filter(|i| !sp.segment_is_line(*i)).count(); + n[1] += count; + n[2] += sp.anchors.len(); + } + n +} + +/// A path's curved segments. +fn curves(p: &PathData) -> Vec<CubicBez> { + let mut out = vec![]; + for sp in &p.subpaths { + let count = if sp.closed { sp.anchors.len() } else { sp.anchors.len().saturating_sub(1) }; + out.extend((0..count).filter(|i| !sp.segment_is_line(*i)).map(|i| sp.segment(i))); + } + out +} + +/// `b` flattened to within 1e-6 pt, each point moved by `map`. +fn fine(b: &BezPath, map: impl Fn(Point) -> Point) -> Vec<Vec<Point>> { + let mut out: Vec<Vec<Point>> = vec![]; + vectorcraft_geom::kurbo::flatten(b, 1e-6, |el| match el { + vectorcraft_geom::kurbo::PathEl::MoveTo(p) => out.push(vec![map(p)]), + vectorcraft_geom::kurbo::PathEl::LineTo(p) => out.last_mut().into_iter().for_each(|r| r.push(map(p))), + _ => {} + }); + out +} + +/// How far `c` lies from the polygons `target` at most, at 33 points along it. +fn farthest(c: &CubicBez, target: &[Vec<Point>]) -> f64 { + (0..=32).map(|k| edge_distance(target, c.eval(f64::from(k) / 32.0))).fold(0.0, f64::max) +} + +/// A rounded bevel on both sides steps through many rings between the caps. Every edge along the +/// art's curves, between two bevel steps or two wall slices as well as at a cap, is a cubic: each +/// side facet that follows a curve has both its edges curved, four anchors, and lies within the +/// sampling tolerance of its own polygon. Two visible facets on either side of one ring draw the +/// edge they share as the same curve. +#[test] +fn interior_bevel_edges_keep_the_curves_of_the_art() { + for art in [circle(Point::new(50.0, 50.0), 40.0), letter_d()] { + let (p, b) = shape(&art); + let bevel = Bevel { shape: BevelShape::Rounded, inside: true, width: 4.0, height: 4.0, both_sides: true, ..Bevel::default() }; + let o = Extrude { depth: 50.0, bevel: Some(bevel), ..Extrude::default() }; + let f = extrude(&p, FillRule::EvenOdd, b, o, View { rotation_x: 20.0, rotation_y: 30.0, ..front() }).unwrap(); + let sides: Vec<&Facet> = f.iter().filter(|f| f.side && f.outline.is_some()).collect(); + assert!(sides.len() > 40, "{}", sides.len()); + for side in &sides { + let path = side.path(); + assert_eq!(anatomy(&path), [2, 4, 4], "{path:?}"); + for c in curves(&path) { + assert!(farthest(&c, &side.contours) <= 2.0 * 0.05, "{c:?}"); + } + } + let all: Vec<(usize, CubicBez)> = sides.iter().enumerate().flat_map(|(k, f)| curves(&f.path()).into_iter().map(move |c| (k, c))).collect(); + let mut shared = 0; + for (k, c) in &all { + for (_, d) in all.iter().filter(|(j, d)| j != k && d.p0.distance(c.p3) < 1e-9 && d.p3.distance(c.p0) < 1e-9) { + shared += 1; + let far = (0..=16).map(|u| c.eval(f64::from(u) / 16.0).distance(d.eval(1.0 - f64::from(u) / 16.0))).fold(0.0, f64::max); + assert!(far <= 1e-6, "{far}"); + } + } + assert!(shared > 20, "{shared}"); + } +} + +/// A twist cuts each edge of a wall into pieces at points of the art's curve: every piece keeps +/// both its edges curved, and the pieces at the front draw the cap's edge, within 0.001 pt of the +/// cap's curves without perspective and twice that with it. +#[test] +fn a_twisted_wall_keeps_curves_where_a_twist_cuts_it() { + let art = circle(Point::new(50.0, 50.0), 40.0); + let (p, b) = shape(&art); + // Shallow, so that each slice of the wall is narrower than its edges are long. + let o = Extrude { depth: 2.0, twist: 30.0, ..Extrude::default() }; + let turned = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + for (view, tolerance) in [(turned, outline::CURVE_TOLERANCE), (View { perspective: 60.0, ..turned }, 2.0 * outline::CURVE_TOLERANCE)] { + let f = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap(); + let corners: Vec<Point> = cap.contours.iter().flatten().copied().collect(); + let cap = fine(&cap.path().to_bezpath(), |q| q); + let sides: Vec<&Facet> = f.iter().filter(|f| f.side).collect(); + assert!(sides.len() > 64, "{}", sides.len()); + let (mut at_cap, mut cut) = (0, 0); + for side in &sides { + let path = side.path(); + assert_eq!(anatomy(&path), [2, 4, 4], "{path:?}"); + // The cap's curves are fitted within the curve tolerance in perspective. + for c in curves(&path).iter().filter(|c| edge_distance(&cap, c.p0) <= tolerance && edge_distance(&cap, c.p3) <= tolerance) { + at_cap += 1; + // A piece that starts or ends where the twist cuts the edge, between two of the + // cap's sampled points. + if [c.p0, c.p3].iter().any(|q| corners.iter().all(|v| v.distance(*q) > 1e-6)) { + cut += 1; + } + let far = farthest(c, &cap); + assert!(far <= tolerance + 1e-6, "{far}"); + } + } + assert!(at_cap > 10 && cut > 5, "{at_cap} at the cap, {cut} of them cut"); + } +} + +/// Inflate keeps the art's curves where its faces meet the outline: the flat back is the art +/// turned, one cubic for each of its curves within 0.001 pt; every side facet has both its edges +/// curved; and the front's cells along the outline are curved there, within the sampling +/// tolerance of the art. +#[test] +fn inflate_keeps_the_curves_of_its_outline() { + let art = circle(Point::new(50.0, 50.0), 40.0); + let (p, b) = shape(&art); + let o = Inflate { depth: 20.0, twist: 30.0, ..Inflate::default() }; + let behind = View { rotation_y: 180.0, ..front() }; + let f = inflate(&p, FillRule::EvenOdd, b, o, behind).unwrap(); + let back = f.iter().find(|f| f.depth == f64::MAX).unwrap().path(); + assert_eq!(anatomy(&back), [4, 4, 4], "{back:?}"); + let camera = Camera::new(behind, b, 1.0); + let turn = Turn::new(b, o.twist, o.taper, 1.0); + let target = fine(&art, |q| camera.project(camera.place(turn.apply(q), -o.depth / 2.0))); + for c in curves(&back) { + assert!(farthest(&c, &target) <= outline::CURVE_TOLERANCE + 1e-6, "{c:?}"); + } + + for (o, view) in [ + (o, View { rotation_x: 20.0, rotation_y: 30.0, ..front() }), + (Inflate { both_sides: true, map_surface: true, ..o }, View { rotation_x: 20.0, rotation_y: 30.0, perspective: 60.0, ..front() }), + ] { + let f = inflate(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let sides: Vec<&Facet> = f.iter().filter(|f| f.side).collect(); + assert!(!sides.is_empty()); + assert!(sides.iter().all(|f| anatomy(&f.path())[..2] == [2, 4]), "a side facet with a straight edge along the circle"); + let rim: Vec<&Facet> = f.iter().filter(|f| !f.side && f.outline.is_some()).collect(); + assert!(rim.len() > 20, "{}", rim.len()); + } + + // Seen straight on, the front's curved edges are the art's circle. + let f = inflate(&p, FillRule::EvenOdd, b, Inflate::default(), front()).unwrap(); + let rim: Vec<CubicBez> = f.iter().filter(|f| f.outline.is_some()).flat_map(|f| curves(&f.path())).collect(); + assert!(rim.len() > 20, "{}", rim.len()); + let circle = fine(&art, |q| q); + for c in &rim { + assert!(farthest(c, &circle) <= 0.05 + 1e-6, "{c:?}"); + } +} + +/// A shape of straight edges gets no curves; a tiny circle and a twisted, tapered Inflate keep +/// theirs without points that are not finite. +#[test] +fn straight_tiny_and_twisted_solids_keep_their_curves_bounded() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let bevel = Bevel { shape: BevelShape::Rounded, inside: true, width: 4.0, height: 4.0, both_sides: true, ..Bevel::default() }; + let view = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + let f = extrude(&p, FillRule::EvenOdd, b, Extrude { depth: 50.0, twist: 45.0, bevel: Some(bevel), ..Extrude::default() }, view).unwrap(); + assert!(f.iter().all(|f| f.outline.is_none())); + let f = inflate(&p, FillRule::EvenOdd, b, Inflate { depth: 20.0, ..Inflate::default() }, view).unwrap(); + assert!(f.iter().all(|f| f.outline.is_none())); + + let tiny = PathData::from_bezpath(&circle(Point::new(1.0, 1.0), 0.01)); + let b = tiny.bounds().unwrap(); + for f in [ + extrude( + &tiny, + FillRule::NonZero, + b, + Extrude { depth: 0.02, twist: 90.0, bevel: Some(Bevel { width: 0.002, height: 0.002, ..bevel }), ..Extrude::default() }, + view, + ), + inflate(&tiny, FillRule::NonZero, b, Inflate { depth: 0.02, twist: 360.0, taper: 0.01, both_sides: true, ..Inflate::default() }, view), + ] { + for f in f.unwrap() { + for c in curves(&f.path()) { + assert!([c.p0, c.p1, c.p2, c.p3].iter().all(|q| q.x.is_finite() && q.y.is_finite()), "{c:?}"); + } + } + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..aa80094688 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1687,7 +1687,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`). - The solids of one Extrude & Bevel (both kinds) or Inflate effect on one object, its fill's, its strokes' and a group's members' together, keep up to 163,840 faces (VectorCraft's own limit). Each solid is built in turn; once their faces pass the limit, no later solid is built, the object draws its source art, and applying or editing the effect, Export 3D Object and Expand as Wireframes report that the 3D surface is too complex. Tests `solids::tests::an_objects_solids_count_their_faces_together`, `a_groups_solids_together_past_the_limit_draw_the_source`, `a_fill_and_strokes_together_past_the_limit_draw_the_source`. - Inflate at a Volume of 0 % works out each shape's puff only when its solid is built, so no puff is worked out for the shapes after the face limit stops, and the solids are the same bit for bit; with any volume every puff is worked out first, as the highest one places the eye. The shadow builds no solid for a fully transparent fill or stroke. Tests `solid::tests::a_flat_inflate_solves_each_puff_as_its_solid_is_taken`, `a_flat_inflate_solved_as_taken_matches_one_solved_first`, `shadow::tests::an_inflate_shape_that_casts_nothing_builds_no_solid`. - - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. + - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. A piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. + - The edges of Extrude & Bevel's walls and bevels between two bevel steps or two wall slices follow the art's curves too, the same curves on both faces that meet there; a twist cuts a wall's edge at points of the curve, so each piece meets the cap along its curve; and Inflate keeps the curves of its flat back, its side walls, and its front and puffed back along the outline (within the sampling tolerance there). Tests `solid::tests_curves::interior_bevel_edges_keep_the_curves_of_the_art`, `a_twisted_wall_keeps_curves_where_a_twist_cuts_it`, `inflate_keeps_the_curves_of_its_outline`, `straight_tiny_and_twisted_solids_keep_their_curves_bounded`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `<name>-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. Materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. diff --git a/docs/three-d.md b/docs/three-d.md index 2327eb1c24..4286c88f3e 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -689,15 +689,18 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. meet, again on the merged outline, which can have more points (bars crossing in a grid trace every hole between them); past it, the shape is too complex for the effect. - The faces drawn, exported and made by **Object › Expand Appearance** keep the shape's curves: the caps of - Extrude & Bevel, the flat face of Rotate, and the edges of the walls and bevels where they meet a cap are cubic - curves, with smooth anchors where the art's are smooth, while visibility and depth are worked out on the - sampled points. Without perspective and bevel each curve maps exactly. With perspective, a curve is split into - cubics until each lies within 0.001 pt of the projected outline. A face inset or outset by a bevel follows its - sampled outline within the sampling tolerance above, one curve for each sampled edge through its two sampled - points, so the cap and the walls next to it draw the edge they share as the same curves. The edges between two bevel steps or two wall slices, a - piece of curve that does not fit after 8 halvings, an edge of a twisted wall cut into pieces, and the curves - past 1,048,576 for one solid stay straight. The tolerances and limits are VectorCraft's own values. Inflate's - faces are polygons. + Extrude & Bevel, the flat face of Rotate, and every edge of the walls and bevels along the art's curves (at a + cap, between two bevel steps and between two wall slices) are cubic curves, with smooth anchors where the + art's are smooth, while visibility and depth are worked out on the sampled points. Without perspective and + bevel each curve maps exactly. With perspective, a curve is split into cubics until each lies within 0.001 pt + of the projected outline. A face inset or outset by a bevel follows its sampled outline within the sampling + tolerance above, one curve for each sampled edge through its two sampled points, so two faces that meet draw + the edge they share as the same curves. A twist cuts a wall's edge into pieces at points of the art's curve, + so each piece follows the same curve as the cap it meets. Inflate keeps the curves of its flat back, of its + side walls and of its front and puffed back where they meet the outline, within the sampling tolerance there; + the inside of a puffed surface stays flat facets. A piece of curve that does not fit after 8 halvings, the + curves past 1,048,576 for one solid, and the cells' edges left once Inflate has looked at 4,194,304 edges of + the outline to find them, stay straight. The tolerances and limits are VectorCraft's own values. - Inflate also limits the work of filling its grid, which grows with the outline's points times the grid cells its outline crosses. An outline of tens of thousands of points that crosses nearly every cell (a comb of 4,000 teeth across the shape) is refused because the 3D surface is too complex; a closed path of 65,536 points round a From 0aafbdeb6de417b821d51ee6b511f8af692d375b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 01:38:37 -0800 Subject: [PATCH 099/126] 3D: twisted bevel pieces meet the inset cap at sharp joins A twist cut a beveled edge at points of the art's curve itself, while the inset cap's edge eases its corners' miter offsets across the whole edge. Where the art meets another edge at a sharp angle, the pieces next to the cap drew a different curve from the cap's, leaving a gap of up to about 1.5 pt between them. Each cut corner now takes the edge's corner offsets, eased across the edge as the cap's edge eases them, and each piece follows the whole edge's curve, so the pieces draw the cap's edge within the cap's sampling tolerance, with and without perspective. The tiny-circle test now also requires the solids to keep at least one curve before it checks their control points. --- crates/three-d/src/solid/build.rs | 22 ++++-- crates/three-d/src/solid/outline.rs | 85 +++++++++++++++++++----- crates/three-d/src/solid/tests_curves.rs | 48 ++++++++++++- docs/target-app-parity.md | 2 +- 4 files changed, 135 insertions(+), 22 deletions(-) diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 20c147b1cd..c945d12d1a 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -41,6 +41,11 @@ impl Camera { let f = perspective_scale(self.eye, v.2); Point::new(self.origin.x + v.0 * f, self.origin.y + v.1 * f) } + /// The view-space point at depth `z` that [`Camera::project`] takes to `p`. + pub(super) fn unproject(&self, p: Point, z: f64) -> V3 { + let f = perspective_scale(self.eye, z); + V3((p.x - self.origin.x) / f, (p.y - self.origin.y) / f, z) + } /// The cosine between a face's outward unit normal `n` and the direction from `at` (both in /// view space) to the eye: positive when the face is turned towards the viewer. pub(super) fn facing(&self, at: V3, n: V3) -> f64 { @@ -303,15 +308,24 @@ impl<'a> Builder<'a> { let places = curves.as_ref().map_or([None, None], |w| w.places); // Where the edge's curve is at share `s` of it. let t = |s: f64| span.map_or(0.0, |span| span.t0 + (span.t1 - span.t0) * s); - // A cut corner on a ring that follows a curve lies on the curve, so the pieces' edges - // follow the same curve as the cap's edge they meet. + // A cut corner on a ring that follows a curve lies on the curve, moved by the offsets of + // the edge's corners from it (a bevel's miters), eased across the edge as the cap's edge + // eases them, so the pieces' edges follow the same curve as the cap's edge they meet. The + // offsets are eased as drawn, and the corner keeps the depth they give it in view space. + let camera = self.camera; let corner = |p: V3, q: V3, s: f64, ring: usize| match (span, places.get(ring).copied().flatten()) { (Some(span), Some(place)) if s > 0.0 && s < 1.0 => { - let v = place(&span, t(s)); + let (c, c0, c1) = (place(&span, t(s)), place(&span, span.t0), place(&span, span.t1)); + let (ep, eq) = (outline::fade(s), outline::fade(1.0 - s)); + let (dp, dq) = (p.sub(c0), q.sub(c1)); + let z = c.2 + dp.2 * ep + dq.2 * eq; + let (dp, dq) = (camera.project(p) - camera.project(c0), camera.project(q) - camera.project(c1)); + let v = camera.unproject(camera.project(c) + dp * ep + dq * eq, z); if v.0.is_finite() && v.1.is_finite() && v.2.is_finite() { v } else { lerp(p, q, s) } } _ => lerp(p, q, s), }; + let ends = [[self.camera.project(a[i]), self.camera.project(a[j])], [self.camera.project(b[i]), self.camera.project(b[j])]]; for k in 0..pieces { let (s0, s1) = (k as f64 / pieces as f64, (k + 1) as f64 / pieces as f64); let quad = vec![corner(a[i], a[j], s0, 0), corner(a[i], a[j], s1, 0), corner(b[i], b[j], s1, 1), corner(b[i], b[j], s0, 1)]; @@ -359,7 +373,7 @@ impl<'a> Builder<'a> { // stays straight. let near = w.near.filter(|_| pieces == 1 || w.places[0].is_some()); let far = w.far.filter(|_| pieces == 1 || w.places[1].is_some()); - self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), quad, near, far, w.budget))); + self.outline(before, |c| c.first().and_then(|quad| outline::wall(&span, (t(s0), t(s1)), ends, quad, near, far, w.budget))); } } } diff --git a/crates/three-d/src/solid/outline.rs b/crates/three-d/src/solid/outline.rs index 75d62251f2..b2491896d7 100644 --- a/crates/three-d/src/solid/outline.rs +++ b/crates/three-d/src/solid/outline.rs @@ -2,7 +2,7 @@ //! wall along the profile follow the profile's curves as cubics, while each facet's polygon stays //! the shape that visibility and depth are worked out on. -use vectorcraft_geom::{BezPath, CubicBez, ParamCurve, PathData, Point}; +use vectorcraft_geom::{BezPath, CubicBez, ParamCurve, PathData, Point, Vec2}; use super::rings::{Ring, Span}; @@ -75,15 +75,54 @@ fn fit(g: &dyn Fn(f64) -> Point, p: Point, q: Point, a: f64, b: f64, tolerance: fit(g, p, m, a, mid, tolerance, depth + 1, out) && fit(g, m, q, mid, b, tolerance, depth + 1, out) } +/// How much of a corner's offset from the outline is left at share `x` of the way from the corner +/// to where the offset is eased out: 1 at the corner, 0 from 1 on, with no slope at either. +pub(super) fn fade(x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + 1.0 - x * x * (3.0 - 2.0 * x) +} + +/// 1 at `from`, 0 from `to` on ([`fade`] over `t`). +fn ease(t: f64, from: f64, to: f64) -> f64 { + if to == from { 1.0 } else { fade((t - from) / (to - from)) } +} + +/// The edge a piece of a wall's edge is cut from: its corners lie off the outline by `d.0` where +/// the edge starts on its span's curve (`t.0`) and by `d.1` where it ends (`t.1`). Each offset is +/// eased out across the whole edge, as a cap's edge eases it, so the pieces follow the cap's curve. +#[derive(Clone, Copy)] +struct Whole { + t: (f64, f64), + d: (Vec2, Vec2), +} + +impl Whole { + /// The outline at `t` on `span`'s curve, moved by the corners' offsets eased across the edge. + fn at(&self, step: &Along, span: &Span, t: f64) -> Point { + (step.at)(span, t) + self.d.0 * ease(t, self.t.0, self.t.1) + self.d.1 * ease(t, self.t.1, self.t.0) + } +} + /// The cubics from `p` to `q` along the piece of `span`'s curve from `t0` to `t1` at `step`, or /// `None` when they do not fit, or would take the budget past [`MAX_OUTLINE_CURVES`]. /// /// `p` and `q` are the face's own corners, which a bevel's miter can move off the curve's offset /// where the curve meets another edge at an angle. The difference is eased out from `p` by `fade.0` /// and into `q` from `fade.1` (the ends of the first and last sampled edge), as the face's polygon -/// does over those edges, so the curves meet the face's corners. +/// does over those edges, so the curves meet the face's corners. With `whole`, the piece is cut from +/// that edge, and the curve it follows is the whole edge's, with `p` and `q` measured from it. #[allow(clippy::too_many_arguments)] -fn piece(step: &Along, span: &Span, t0: f64, t1: f64, fade: (f64, f64), p: Point, q: Point, budget: &mut Budget) -> Option<Vec<CubicBez>> { +fn piece( + step: &Along, + span: &Span, + t0: f64, + t1: f64, + fade: (f64, f64), + p: Point, + q: Point, + whole: Option<Whole>, + budget: &mut Budget, +) -> Option<Vec<CubicBez>> { if let Some(map) = step.map { let c = span.curve.subsegment(t0..t1); let c = CubicBez::new(p, map(c.p1), map(c.p2), q); @@ -94,13 +133,9 @@ fn piece(step: &Along, span: &Span, t0: f64, t1: f64, fade: (f64, f64), p: Point return (budget.0 <= MAX_OUTLINE_CURVES).then(|| vec![c]); } } - let (dp, dq) = (p - (step.at)(span, t0), q - (step.at)(span, t1)); - // 1 at the end, 0 from `to` on, with no slope at either. - let ease = |t: f64, from: f64, to: f64| { - let x = if to == from { 1.0 } else { ((t - from) / (to - from)).clamp(0.0, 1.0) }; - 1.0 - x * x * (3.0 - 2.0 * x) - }; - let g = |t: f64| (step.at)(span, t) + dp * ease(t, t0, fade.0) + dq * ease(t, t1, fade.1); + let base = |t: f64| whole.map_or_else(|| (step.at)(span, t), |w| w.at(step, span, t)); + let (dp, dq) = (p - base(t0), q - base(t1)); + let g = |t: f64| base(t) + dp * ease(t, t0, fade.0) + dq * ease(t, t1, fade.1); let mut out = vec![]; if !fit(&g, p, q, t0, t1, step.tolerance, 0, &mut out) { return None; @@ -141,7 +176,7 @@ fn contour(path: &mut BezPath, ring: &Ring, points: &[Point], step: &Along, budg (j, t1, last) = (j + 1, next.t1, next.t0); } let (p, q) = (points.get(i).copied().unwrap_or(first), end(j)); - match piece(step, &span, span.t0, t1, (span.t1, last), p, q, budget) { + match piece(step, &span, span.t0, t1, (span.t1, last), p, q, None, budget) { Some(curves) => { curved = true; for c in curves { @@ -174,12 +209,30 @@ pub(super) fn face(rings: &[&Ring], points: &[Vec<Point>], step: &Along, budget: /// The outline of a wall's quad `quad` (`a`, `a'`, `b'`, `b` projected: the edge at `near` from /// `a` to `a'`, then the edge at `far` back from `b'` to `b`), whose edges along the profile follow /// `span`'s curve from `t.0` to `t.1` (all of `span`, or the piece of it one cut of a twisted wall -/// takes). An edge without its outline stays straight. `None` when neither edge is curved. -pub(super) fn wall(span: &Span, t: (f64, f64), quad: &[Point], near: Option<&Along>, far: Option<&Along>, budget: &mut Budget) -> Option<PathData> { +/// takes). `ends` are the corners of the whole edges at `near` and at `far` (projected, where each +/// starts and ends on all of `span`), so that a piece follows the curve the whole edge does, as the +/// cap's edge it meets. An edge without its outline stays straight. `None` when neither edge is +/// curved. +#[allow(clippy::too_many_arguments)] +pub(super) fn wall( + span: &Span, + t: (f64, f64), + ends: [[Point; 2]; 2], + quad: &[Point], + near: Option<&Along>, + far: Option<&Along>, + budget: &mut Budget, +) -> Option<PathData> { let [a, a2, b2, b] = <[Point; 4]>::try_from(quad).ok()?; let (t0, t1) = t; - let front = near.and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, budget)); - let back = far.and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, budget)); + let whole = |step: &Along, [p, q]: [Point; 2]| { + let d = (p - (step.at)(span, span.t0), q - (step.at)(span, span.t1)); + let finite = [d.0, d.1].iter().all(|d| d.x.is_finite() && d.y.is_finite()); + finite.then_some(Whole { t: (span.t0, span.t1), d }) + }; + let [near_ends, far_ends] = ends; + let front = near.and_then(|near| piece(near, span, t0, t1, (t1, t0), a, a2, whole(near, near_ends), budget)); + let back = far.and_then(|far| piece(far, span, t1, t0, (t0, t1), b2, b, whole(far, far_ends), budget)); if front.is_none() && back.is_none() { return None; } @@ -220,7 +273,7 @@ pub(super) fn edges(points: &[Vec<Point>], curves: &[Vec<Option<EdgeCurve>>], st path.move_to(first); for (k, c) in curves.iter().enumerate() { let (p, q) = (points.get(k).copied().unwrap_or(first), points.get((k + 1) % n).copied().unwrap_or(first)); - match c.as_ref().and_then(|(span, t0, t1)| piece(step, span, *t0, *t1, (*t1, *t0), p, q, budget)) { + match c.as_ref().and_then(|(span, t0, t1)| piece(step, span, *t0, *t1, (*t1, *t0), p, q, None, budget)) { Some(cubics) => { curved = true; cubics.iter().for_each(|c| path.curve_to(c.p1, c.p2, c.p3)); diff --git a/crates/three-d/src/solid/tests_curves.rs b/crates/three-d/src/solid/tests_curves.rs index 07ba46d19f..4d00fe8353 100644 --- a/crates/three-d/src/solid/tests_curves.rs +++ b/crates/three-d/src/solid/tests_curves.rs @@ -162,6 +162,50 @@ fn a_twisted_wall_keeps_curves_where_a_twist_cuts_it() { } } +/// A half disc: a straight diameter and a round arc, meeting it at right angles. +fn half_disc() -> BezPath { + let k = 0.552_284_749_830_793_6 * 50.0; + let mut b = BezPath::new(); + b.move_to((0.0, 50.0)); + b.line_to((100.0, 50.0)); + b.curve_to((100.0, 50.0 - k), (50.0 + k, 0.0), (50.0, 0.0)); + b.curve_to((50.0 - k, 0.0), (0.0, 50.0 - k), (0.0, 50.0)); + b.close_path(); + b +} + +/// With a bevel, the cap is inset, and its corners where the arc meets the diameter at a right +/// angle lie off the curve's inset by the miter. A twist cuts the band next to the cap into pieces: +/// the pieces that start or end at one of the cap's corners draw the cap's edge, within the cap's +/// sampling tolerance of its curves, with no gap where they meet it. +#[test] +fn twisted_bevel_pieces_meet_the_cap_at_sharp_joins() { + let (p, b) = shape(&half_disc()); + let bevel = Bevel { inside: true, width: 4.0, height: 1.0, ..Bevel::default() }; + let o = Extrude { depth: 4.0, twist: 30.0, bevel: Some(bevel), ..Extrude::default() }; + let turned = View { rotation_x: 20.0, rotation_y: 30.0, ..front() }; + for view in [turned, View { perspective: 60.0, ..turned }] { + let f = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap(); + let cap = f.iter().find(|f| f.depth == f64::MAX).unwrap(); + let corners: Vec<Point> = cap.contours.iter().flatten().copied().collect(); + let cap = fine(&cap.path().to_bezpath(), |q| q); + let mut pieces = 0; + for side in f.iter().filter(|f| f.side) { + for c in curves(&side.path()) { + let at_corner = |q: Point| corners.iter().any(|v| v.distance(q) < 1e-6); + // One end at a corner of the cap, the other where the twist cuts the edge. + if at_corner(c.p0) == at_corner(c.p3) { + continue; + } + pieces += 1; + let far = farthest(&c, &cap); + assert!(far <= 2.0 * 0.05 + 1e-6, "{far}: {c:?}"); + } + } + assert!(pieces > 10, "{pieces}"); + } +} + /// Inflate keeps the art's curves where its faces meet the outline: the flat back is the art /// turned, one cubic for each of its curves within 0.001 pt; every side facet has both its edges /// curved; and the front's cells along the outline are curved there, within the sampling @@ -228,7 +272,9 @@ fn straight_tiny_and_twisted_solids_keep_their_curves_bounded() { ), inflate(&tiny, FillRule::NonZero, b, Inflate { depth: 0.02, twist: 360.0, taper: 0.01, both_sides: true, ..Inflate::default() }, view), ] { - for f in f.unwrap() { + let f = f.unwrap(); + assert!(f.iter().any(|f| !curves(&f.path()).is_empty()), "no curve on a tiny circle"); + for f in f { for c in curves(&f.path()) { assert!([c.p0, c.p1, c.p2, c.p3].iter().all(|q| q.x.is_finite() && q.y.is_finite()), "{c:?}"); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index aa80094688..e176ac62a9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1688,7 +1688,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The solids of one Extrude & Bevel (both kinds) or Inflate effect on one object, its fill's, its strokes' and a group's members' together, keep up to 163,840 faces (VectorCraft's own limit). Each solid is built in turn; once their faces pass the limit, no later solid is built, the object draws its source art, and applying or editing the effect, Export 3D Object and Expand as Wireframes report that the 3D surface is too complex. Tests `solids::tests::an_objects_solids_count_their_faces_together`, `a_groups_solids_together_past_the_limit_draw_the_source`, `a_fill_and_strokes_together_past_the_limit_draw_the_source`. - Inflate at a Volume of 0 % works out each shape's puff only when its solid is built, so no puff is worked out for the shapes after the face limit stops, and the solids are the same bit for bit; with any volume every puff is worked out first, as the highest one places the eye. The shadow builds no solid for a fully transparent fill or stroke. Tests `solid::tests::a_flat_inflate_solves_each_puff_as_its_solid_is_taken`, `a_flat_inflate_solved_as_taken_matches_one_solved_first`, `shadow::tests::an_inflate_shape_that_casts_nothing_builds_no_solid`. - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. A piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - - The edges of Extrude & Bevel's walls and bevels between two bevel steps or two wall slices follow the art's curves too, the same curves on both faces that meet there; a twist cuts a wall's edge at points of the curve, so each piece meets the cap along its curve; and Inflate keeps the curves of its flat back, its side walls, and its front and puffed back along the outline (within the sampling tolerance there). Tests `solid::tests_curves::interior_bevel_edges_keep_the_curves_of_the_art`, `a_twisted_wall_keeps_curves_where_a_twist_cuts_it`, `inflate_keeps_the_curves_of_its_outline`, `straight_tiny_and_twisted_solids_keep_their_curves_bounded`. + - The edges of Extrude & Bevel's walls and bevels between two bevel steps or two wall slices follow the art's curves too, the same curves on both faces that meet there; a twist cuts a wall's edge at points of the curve, so each piece meets the cap along its curve, a bevel's inset cap included; and Inflate keeps the curves of its flat back, its side walls, and its front and puffed back along the outline (within the sampling tolerance there). Tests `solid::tests_curves::interior_bevel_edges_keep_the_curves_of_the_art`, `a_twisted_wall_keeps_curves_where_a_twist_cuts_it`, `twisted_bevel_pieces_meet_the_cap_at_sharp_joins`, `inflate_keeps_the_curves_of_its_outline`, `straight_tiny_and_twisted_solids_keep_their_curves_bounded`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `<name>-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). The graphics wrapped around Revolve's side export the same way, as a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles, with its end caps and cut sides plain. Materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`, `a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side`, `a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn`, `export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format`, `a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side`. From 64dd48d801df4746891e26ab6b8371b4a25fced8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 02:52:41 -0800 Subject: [PATCH 100/126] PSD import: apply Invert, Threshold and Posterize adjustment layers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open with a PSD or PSB file's layers as objects now reads the nvrt, thrs and post blocks of the PSD file format specification and merges each such adjustment layer with the visible layers below it in its group, changing their colors. Clipped to a layer, it changes only that layer and the layers clipped to it. In a pass-through group with nothing below it in the group, it changes what is below the group when the group is merged. Each channel is taken as an 8-bit sRGB value: Invert turns v into 255 - v, Threshold compares the Rec. 709 luminance with its level, and Posterize maps each channel to the nearest of its evenly spaced levels. The adjusted color is composited in the layer's blend mode at its opacity and fill opacity, through its layer mask. A hidden one is left out. One that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read and one whose merge needs more memory than allowed are not applied and are counted in the existing adjustment-layer warning. Other adjustment kinds are still not applied. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/psdlayers.rs | 428 ++++++++++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 347 ++++++++++++++ crates/engine/tests/import_fuzz.rs | 3 +- docs/mcp.md | 24 +- docs/target-app-parity.md | 3 +- 5 files changed, 747 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 17e6c3f814..5f3c0a6b01 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -32,12 +32,30 @@ //! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its //! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need //! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers -//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is -//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no -//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched -//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others -//! are clipped to and of layers in a pass-through group with a layer in another mode, and other -//! Knockout values, aren't applied; the warnings count them and the hidden layers left out. +//! below it, one that layers are clipped to, one clipped to another, an Invert, Threshold or +//! Posterize adjustment layer, or one below a merged layer) is always left out, with the layers +//! clipped to it. +//! +//! An Invert, Threshold or Posterize adjustment layer, as the import option describes for +//! adjustment layers, is merged with the visible layers below it in its group, which it changes; +//! clipped to a layer, it changes only the layers merged into that one. The rules are VectorCraft's +//! own: each color channel is taken as an 8-bit value of the sRGB color the layers are drawn in, +//! Invert turns `v` into `255 − v`, Threshold makes a pixel white when the luminance of its color +//! (Rec. 709 weights on linear sRGB, encoded back to 0..255) is above the level and black +//! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher +//! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, +//! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One +//! with nothing visible below it in its group changes nothing; in a pass-through group it changes +//! what is below the group when the group is merged, and otherwise isn't applied. One that layers +//! are clipped to, and one clipped to another adjustment layer, isn't applied. +//! +//! Other adjustment layers, Invert, Threshold and Posterize data that can't be read (a level out of +//! range, too short, or a second adjustment block on the layer), fill layers that store no pixels and +//! whose fill isn't read or whose shape is a vector mask, layer effects that are switched on, vector +//! masks, and the knockouts of top-level layers, of clipped layers, of layers that others are clipped +//! to and of layers in a pass-through group with a layer in another mode, and other Knockout values, +//! and adjustments whose merge needs more memory than allowed aren't applied; the warnings count them +//! and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the @@ -193,8 +211,9 @@ enum Content { Pixels, /// A type layer: its pixels come in. Type, - /// An adjustment layer: not applied. - Adjustment, + /// An adjustment layer: the adjustment applied (`None` for another kind, or data that can't be + /// read, which isn't applied). + Adjustment(Option<Adjust>), /// A solid color fill layer: its stored pixels, or its color over the whole canvas when it /// stores none (nothing when the color can't be read, or when its shape is a vector mask). Solid(Option<Paint>), @@ -202,6 +221,58 @@ enum Content { Fill, } +/// An adjustment the import applies. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Adjust { + /// `nvrt`: each color channel's value `v` (0..255) becomes `255 − v`. + Invert, + /// `thrs`: pixels whose luminance is above the level (1..255) become white, the others black. + Threshold(u8), + /// `post`: each color channel takes the nearest of this many (2..255) evenly spaced levels. + Posterize(u8), +} + +impl Adjust { + /// The adjustment of key `key` whose data is `data`; `None` when the data can't be read or its + /// value is out of range. Invert has no data; Threshold's level and Posterize's count of levels + /// are a 16-bit number followed by 2 bytes of padding, as psd-tools (MIT) reads them + /// (<https://github.com/psd-tools/psd-tools>, `psd/adjustments.py`); data shorter than the 4 + /// bytes can't be read. + fn read(key: &[u8; 4], data: &[u8]) -> Option<Self> { + let value = || data.get(..4).map(|v| u16::from_be_bytes([v[0], v[1]])); + match key { + b"nvrt" => Some(Adjust::Invert), + b"thrs" => u8::try_from(value()?).ok().filter(|&l| l >= 1).map(Adjust::Threshold), + b"post" => u8::try_from(value()?).ok().filter(|&n| n >= 2).map(Adjust::Posterize), + _ => None, + } + } + + /// Straight RGB, 0..1, adjusted. Each channel is taken as an 8-bit value. Threshold measures + /// the sRGB relative luminance (Rec. 709 weights on the linear values), encoded back to 0..255: + /// above the level is white, at or below it black. Posterize maps a value to the nearest of + /// its levels `k × 255 / (n − 1)`, the higher one on a tie. + fn apply(self, rgb: [f32; 3]) -> [f32; 3] { + use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear}; + let v = rgb.map(byte); + match self { + Adjust::Invert => v.map(|v| f32::from(255 - v) / 255.0), + Adjust::Threshold(level) => { + let lin = v.map(|v| srgb_to_linear(f32::from(v) / 255.0)); + let y = byte(linear_to_srgb(0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2])); + [if y > level { 1.0 } else { 0.0 }; 3] + } + Adjust::Posterize(n) => { + let steps = u32::from(n) - 1; + v.map(|v| { + let k = (2 * u32::from(v) * steps + 255) / 510; + ((2 * k * 255 + steps) / (2 * steps)) as f32 / 255.0 + }) + } + } + } +} + /// A solid color fill layer's color. #[derive(Clone, Copy, Debug, PartialEq)] enum Paint { @@ -333,6 +404,8 @@ impl Record<'_> { // Effects in a descriptor (`lfx2`, `lmfx`) say whether they are switched on; the older // `lrFX` block is counted whenever it is there. let (mut effects, mut old_effects) = (None, false); + // Whether an adjustment block has been read. + let mut adjusted = false; while e.rest().len() >= 12 { let (Ok(signature), Ok(key)) = (e.array::<4>(), e.array::<4>()) else { break }; if !matches!(&signature, b"8BIM" | b"8B64") { @@ -363,7 +436,12 @@ impl Record<'_> { b"lrFX" => old_effects = true, b"vmsk" | b"vsms" => self.vector_mask = true, b"knko" => self.knockout = data.first().copied().unwrap_or(0), - k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, + // A second adjustment block, with other blocks between them or not, makes the + // layer's adjustment unreadable. + k if ADJUSTMENTS.contains(&k) => { + let again = std::mem::replace(&mut adjusted, true); + self.content = Content::Adjustment(Adjust::read(k, data).filter(|_| !again)); + } _ => {} } // Some writers pad blocks further: skip to the next signature. @@ -390,12 +468,20 @@ impl Record<'_> { matches!(self.content, Content::Solid(Some(_))) && self.stores_nothing() && !self.vector_mask } + /// The adjustment the layer applies, if it is an adjustment layer of a kind the import applies. + fn adjust(&self) -> Option<Adjust> { + match self.content { + Content::Adjustment(a) => a, + _ => None, + } + } + /// Does the layer cover the whole canvas without drawing (an adjustment layer, or a fill that /// stores no pixels, has no vector mask and isn't drawn from its color)? Layers clipped to it /// show over the whole canvas. fn covers_without_drawing(&self) -> bool { match self.content { - Content::Adjustment => true, + Content::Adjustment(_) => true, Content::Solid(None) | Content::Fill => self.stores_nothing() && !self.vector_mask, _ => false, } @@ -701,6 +787,9 @@ enum Drawn { struct Notes { types: usize, adjustments: usize, + /// Adjustment layers of a kind the import applies that it couldn't apply (warned of with + /// `adjustments`). + unadjusted: usize, fills: usize, effects: usize, vector_masks: usize, @@ -730,6 +819,8 @@ struct Counts { clipped_out: usize, /// The groups found to read no pixels. blank: usize, + /// The adjustment layers counted as not applied (see [`Builder::unadjust`]). + unadjusted: usize, } /// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place @@ -778,7 +869,7 @@ impl Notes { let [types, adjustments, fills, effects, masks, knockouts, hidden, clipped_out, unmerged, unclipped] = LAYER_WARNINGS; let mut out = vec![]; note(&mut out, self.types, types); - note(&mut out, self.adjustments, adjustments); + note(&mut out, self.adjustments + self.unadjusted, adjustments); note(&mut out, self.fills, fills); note(&mut out, self.effects, effects); note(&mut out, self.vector_masks, masks); @@ -793,7 +884,7 @@ impl Notes { out } - fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts { + fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize, unadjusted: usize) -> Counts { Counts { spent, skipped, @@ -803,6 +894,7 @@ impl Notes { unclipped: self.unclipped, clipped_out: self.clipped_out, blank, + unadjusted, } } } @@ -842,6 +934,10 @@ struct Builder<'a, F> { unclipped: Vec<bool>, /// Those records, in the order they were counted. unclip_log: Vec<usize>, + /// The records counted as adjustment layers the import applies that weren't applied. + unadjusted: Vec<bool>, + /// Those records, in the order they were counted. + unadjust_log: Vec<usize>, /// The records that came in as layers of the document (hidden ones too, with `hidden`): not left /// out, though a drawing for a merge that wasn't made counted them. kept: Vec<bool>, @@ -922,7 +1018,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { let h = self.h; let max_side = if h.psb { 300_000 } else { 30_000 }; let (w, rows) = match rec.content { - Content::Adjustment => return Ok(None), + Content::Adjustment(_) => return Ok(None), // A fill layer that stores no pixels (a shape layer stores its shape's; one that // doesn't, with only its vector mask, isn't drawn). Content::Solid(Some(paint)) if rec.color_over_canvas() => { @@ -1058,8 +1154,14 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } self.refund(spent)?; // The merge doesn't fit: this layer and the next ones clipped to the same - // base come in as layers of their own. + // base come in as layers of their own; an adjustment layer, which would + // change more than its base, isn't applied. unclipped = true; + if self.adjustment(&body)?.is_some() { + self.squeezed += 1; + self.unadjust(i); + continue; + } self.unclip(i); out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); } @@ -1089,25 +1191,37 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { #[allow(clippy::too_many_arguments)] fn clip(&mut self, out: &mut [Unit<'_>], b: usize, body: &Body<'_>, i: usize, name: &str, blend: Blend, opacity: f32) -> Result<bool, String> { let Some(u) = out.get(b) else { return Ok(true) }; - let (whole, undrawn, fill, base_opacity) = { + let (whole, undrawn, fill, base_opacity, base_adjusts, base_adjustment) = { let r = self.record(u.record)?; let layer = matches!(u.body, Body::Layer(_)); - (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity) + // The base as a layer, or as the canvas of the layers already clipped to it. + let adjustment = (layer || u.clip.is_some()) && matches!(r.content, Content::Adjustment(_)); + (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity, layer && r.adjust().is_some(), adjustment) }; // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. if undrawn && u.clip.is_none() { self.clip_out(i); return Ok(true); } - let layer = match self.draw_body(body, Some(i))? { - Drawn::Nothing => return Ok(true), - Drawn::TooLarge => return Ok(false), - Drawn::Canvas(c) => c, + // A clipped adjustment layer changes the merged canvas in place, through its layer mask. + let adjust = self.adjustment(body)?; + let layer = match adjust { + Some(_) => Canvas::default(), + None => match self.draw_body(body, Some(i))? { + Drawn::Nothing => return Ok(true), + Drawn::TooLarge => return Ok(false), + Drawn::Canvas(c) => c, + }, }; let room = self.room(); let layer_bytes = 16 * layer.px.len() as u64; let Some(u) = out.get_mut(b) else { return Ok(true) }; if u.clip.is_none() { + // An adjustment layer that others are clipped to isn't applied. + if base_adjusts { + let record = u.record; + self.unadjust(record); + } let (canvas, clip) = if whole { (Canvas::default(), Clip::Whole) } else { @@ -1134,6 +1248,18 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { u.opacity = base_opacity; } let Body::Merged(c) = &mut u.body else { return Ok(true) }; + if let Some(a) = adjust { + // Clipped to an adjustment layer, it would change the layers below that one: not applied. + if base_adjustment { + self.unadjust(i); + return Ok(true); + } + let mask = self.mask(i, false)?; + adjust_onto(c, a, blend, opacity, mask.as_ref(), i); + u.name.push_str(" + "); + u.name.push_str(name); + return Ok(true); + } match &u.clip { Some(Clip::Shape(_)) => { if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { @@ -1191,7 +1317,8 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { }; match content { Content::Type => self.notes.types += 1, - Content::Adjustment => self.notes.adjustments += 1, + // One the import applies is counted only where it isn't (see `unadjust`). + Content::Adjustment(None) => self.notes.adjustments += 1, // A fill drawn from neither its pixels nor its color. Content::Fill | Content::Solid(None) if empty => self.notes.fills += 1, Content::Solid(Some(_)) if empty && vector_mask => self.notes.fills += 1, @@ -1286,6 +1413,82 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } } + /// Count record `i` as an adjustment layer the import applies that wasn't applied (once). + fn unadjust(&mut self, i: usize) { + if let Some(s) = self.unadjusted.get_mut(i) + && !*s + { + *s = true; + self.notes.unadjusted += 1; + self.unadjust_log.push(i); + } + } + + /// The adjustment `body` applies: a layer record that is an adjustment layer the import applies. + fn adjustment(&self, body: &Body<'_>) -> Result<Option<Adjust>, String> { + match body { + Body::Layer(i) => Ok(self.record(*i)?.adjust()), + _ => Ok(None), + } + } + + /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to + /// change what is below the group), those kept in the pass-through groups of `out` included. + fn pending(&self, out: &[Unit<'_>], level: Level) -> Result<Vec<usize>, String> { + let mut records = vec![]; + if level != Level::Pass { + return Ok(records); + } + for u in out { + if self.adjustment(&u.body)?.is_some() { + records.push(u.record); + } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) { + records.extend(self.leading(items)?.0); + } + } + Ok(records) + } + + /// The adjustment layers the import applies that a pass-through group with the layers `items` + /// keeps to change what is below it: from the first one with nothing that draws below it in the + /// group (hidden and clipped layers, other adjustment layers and fills that draw nothing aren't + /// counted), it and every one above it, in the pass-through groups inside it too. Also whether + /// anything in `items` draws. + fn leading(&self, items: &[Item]) -> Result<(Vec<usize>, bool), String> { + let (mut records, mut draws) = (vec![], false); + for item in items { + match item { + Item::Layer(i) => { + let r = self.record(*i)?; + if r.hidden || r.clipped { + continue; + } + if r.adjust().is_some() { + if !draws || !records.is_empty() { + records.push(*i); + } + } else if !r.covers_without_drawing() { + draws = true; + } + } + Item::Group(g, children) => { + let r = self.record(*g)?; + if r.hidden { + continue; + } + if r.blend == Blend::Pass && (!draws || !records.is_empty()) { + let (inner, inner_draws) = self.leading(children)?; + records.extend(inner); + draws |= inner_draws; + } else { + draws = true; + } + } + } + } + Ok((records, draws)) + } + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group /// the layers with a shallow knockout, merged with those below. fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result<Vec<Unit<'i>>, String> { @@ -1322,6 +1525,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { continue; } Knocked::Merged(canvas) => { + // Adjustment layers kept below it in the group are merged with nothing to change. + for r in self.pending(&out, level)? { + self.unadjust(r); + } self.take_merge(&mut out, &u, canvas); if let Blend::Other(other) = u.blend && !self.notes.merged.contains(&other.label()) @@ -1350,42 +1557,25 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } } } + if self.adjustment(&u.body)?.is_some() { + self.adjust_below(&mut out, u, level)?; + continue; + } let Blend::Other(other) = u.blend else { out.push(u); continue; }; // A merge that can't be made counts nothing its groups would have counted. let saved = self.saved(); + let pending = self.pending(&out, level)?; let outer = self.try_from_here(); - let made = match out.as_mut_slice() { - // Onto the previous merge alone: composited onto its canvas, in place. - [prev] if prev.is_merge() => { - let mut acc = match &mut prev.body { - Body::Merged(c) => Some(std::mem::take(c)), - _ => None, - }; - let made = self.composite(&mut acc, &u); - if let Body::Merged(c) = &mut prev.body { - *c = acc.unwrap_or_default(); - } - if made? { - prev.name.push_str(" + "); - prev.name.push_str(&u.name); - true - } else { - false - } - } - _ => match self.merge(&out, &u)? { - Some(canvas) => { - self.take_merge(&mut out, &u, canvas); - true - } - None => false, - }, - }; + let made = self.merge_into(&mut out, &u)?; self.tried(outer, made)?; if made { + // Adjustment layers kept below it in the group are merged with nothing to change. + for r in pending { + self.unadjust(r); + } if !self.notes.merged.contains(&other.label()) { self.notes.merged.push(other.label()); } @@ -1400,9 +1590,96 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Ok(out) } + /// `out` replaced by one layer, the merge of its visible units with `top` (see + /// [`Self::take_merge`]). `false` when the canvas would need more memory than allowed. + fn merge_into<'i>(&mut self, out: &mut Vec<Unit<'i>>, top: &Unit<'_>) -> Result<bool, String> { + match out.as_mut_slice() { + // Onto the previous merge alone: composited onto its canvas, in place. + [prev] if prev.is_merge() => { + let mut acc = match &mut prev.body { + Body::Merged(c) => Some(std::mem::take(c)), + _ => None, + }; + let made = self.composite(&mut acc, top); + if let Body::Merged(c) = &mut prev.body { + *c = acc.unwrap_or_default(); + } + if made? { + prev.name.push_str(" + "); + prev.name.push_str(&top.name); + Ok(true) + } else { + Ok(false) + } + } + _ => match self.merge(out, top)? { + Some(canvas) => { + self.take_merge(out, top, canvas); + Ok(true) + } + None => Ok(false), + }, + } + } + + /// Adjustment layer `u` (one the import applies), at `level`, merged with the visible units + /// `out` below it in its list: they become one layer, adjusted. A hidden one would need the + /// merge and is left out. With nothing visible below it that draws (other adjustment layers and + /// fills that draw nothing don't count), or at 0 opacity, it changes nothing + /// and comes in as nothing, except in a pass-through group, where it is kept to change what is + /// below the group when the group is drawn onto it; there, once one is kept (in the group or in + /// a pass-through group in it), the ones above it are kept too, in order. One that layers are clipped to, and one whose merge needs more memory + /// than allowed, isn't applied, and is counted. + fn adjust_below<'i>(&mut self, out: &mut Vec<Unit<'i>>, u: Unit<'i>, level: Level) -> Result<(), String> { + if !u.visible { + self.skip(u.record); + return Ok(()); + } + // One that layers are clipped to, kept as a layer because they drew nothing or their merge + // didn't fit, isn't applied. + if u.base { + self.unadjust(u.record); + return Ok(()); + } + if u.opacity <= 0.0 { + return Ok(()); + } + let mut below = false; + for b in out.iter() { + match &b.body { + // An adjustment layer, or a fill that draws nothing, has nothing to change. + Body::Layer(i) if self.record(*i)?.covers_without_drawing() => {} + _ => below |= b.visible, + } + } + // Kept below it in the group, or in a pass-through group below it there. + let pending = !self.pending(out, level)?.is_empty(); + if level == Level::Pass && (pending || !below) { + out.push(u); + return Ok(()); + } + if !below { + return Ok(()); + } + let saved = self.saved(); + let outer = self.try_from_here(); + let made = self.merge_into(out, &u)?; + self.tried(outer, made)?; + if !made { + self.restore(saved)?; + self.squeezed += 1; + self.unadjust(u.record); + } else if let Blend::Other(other) = u.blend + && !self.notes.merged.contains(&other.label()) + { + self.notes.merged.push(other.label()); + } + Ok(()) + } + /// The counts as they are, for [`Self::restore`]. fn saved(&self) -> Counts { - self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()) + self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len(), self.unadjust_log.len()) } /// The counts as they were before a merge that couldn't be made, the bytes it spent counted as @@ -1442,6 +1719,12 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1); } } + for i in self.unadjust_log.split_off(c.unadjusted) { + if let Some(s) = self.unadjusted.get_mut(i) { + *s = false; + self.notes.unadjusted = self.notes.unadjusted.saturating_sub(1); + } + } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; Ok(()) @@ -1563,7 +1846,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Body::Layer(i) => { let rec = self.record(*i)?; match rec.content { - Content::Adjustment => continue, + Content::Adjustment(_) => continue, Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)], _ => { let (w, h) = rec.bounds.size(); @@ -1643,6 +1926,17 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } return Ok(true); } + // An adjustment layer changes `acc` where it is, through its layer mask. + if let Some(a) = self.adjustment(&u.body)? { + if let Some(c) = acc.as_mut() { + let mask = match u.mask_of { + Some(i) => self.mask(i, false)?, + None => None, + }; + adjust_onto(c, a, u.blend, u.opacity, mask.as_ref(), u.record); + } + return Ok(true); + } let c = match self.draw_body(&u.body, u.mask_of)? { Drawn::Nothing => return Ok(true), Drawn::Canvas(c) => c, @@ -1760,6 +2054,12 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { if let Some(k) = self.kept.get_mut(u.record) { *k = true; } + // An adjustment layer kept in a pass-through group with nothing below it in the group: the + // layers below the group aren't changed by it. + if self.adjustment(&u.body)?.is_some() { + self.unadjust(u.record); + return Ok(None); + } let children = match &u.body { Body::Layer(i) => match self.image(*i)? { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], @@ -1870,6 +2170,32 @@ fn fade(after: &mut Canvas, before: Option<&Canvas>, opacity: f32, mask: Option< } } +/// `c` changed by adjustment `a` (of record `record`): at each pixel, the adjusted color is +/// composited over the color as it was in `blend`, at `opacity` times the value of `mask` (as +/// [`fade`] takes it) there. The transparency of each pixel stays as it was. +fn adjust_onto(c: &mut Canvas, a: Adjust, blend: Blend, opacity: f32, mask: Option<&(i64, i64, image::GrayImage, u8)>, record: usize) { + let width = c.width.max(1); + let opacity = opacity.clamp(0.0, 1.0); + for (k, p) in c.px.iter_mut().enumerate() { + if p[3] <= 0.0 { + continue; + } + let (x, y) = (c.left + (k % width) as i64, c.top + (k / width) as i64); + let m = mask.map_or(255, |(left, top, m, default)| { + let inside = (*left..*left + i64::from(m.width())).contains(&x) && (*top..*top + i64::from(m.height())).contains(&y); + if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { *default } + }); + let t = coverage(blend, opacity * f32::from(m) / 255.0, x, y, record); + if t <= 0.0 { + continue; + } + let rgb = [p[0], p[1], p[2]]; + let [r, g, b] = a.apply(rgb); + let mixed = over(blend, [rgb[0], rgb[1], rgb[2], 1.0], [r, g, b, t]); + *p = [mixed[0], mixed[1], mixed[2], p[3]]; + } +} + /// `src` (of record `record`) at `opacity` composited onto `acc` (nothing when `None`) in `blend`, /// on a canvas covering both (`acc` itself when it covers `src`; a larger one is counted with /// `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a larger @@ -2027,6 +2353,8 @@ pub(super) fn import( clipped_out_log: vec![], unclipped: vec![false; records.len()], unclip_log: vec![], + unadjusted: vec![false; records.len()], + unadjust_log: vec![], kept: vec![false; records.len()], spent: Cell::new(0), wasted: Cell::new(0), diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index d5dccfd662..80d9fba25f 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1201,6 +1201,353 @@ fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() { assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}"); } +/// An adjustment layer of key `key` with `data`, storing no pixels. +fn adjustment(name: &'static str, key: &[u8; 4], data: &[u8]) -> L { + L { blocks: vec![(*key, data.to_vec())], ..layer(name, [0, 0, 0, 0], [0; 4]) } +} + +/// The colors of a 1-pixel-high layer's image, left to right. +fn row_of(s: &Session, l: &Node) -> Vec<[u8; 4]> { + let px = image_of(s, l).1; + (0..px.width()).map(|x| px.get_pixel(x, 0).0).collect() +} + +/// Invert, Threshold and Posterize adjustment layers merge with the visible layers below them, which +/// they change; the layers above stay apart. Invert turns each value `v` into `255 − v`; Threshold +/// at 128 makes a pixel white when its luminance is above 128 and black at or below it; Posterize at +/// 4 levels maps each channel to the nearest of 0, 85, 170 and 255. +#[test] +fn invert_threshold_and_posterize_merge_with_the_layers_below() { + let top = layer("Top", [0, 0, 1, 1], [1, 2, 3, 255]); + for (depth, psb) in [(8, false), (16, false), (8, true), (16, true)] { + let layers = [ + layer("Dark", [0, 0, 1, 1], [10, 20, 30, 255]), + layer("Light", [0, 1, 1, 2], [200, 150, 100, 128]), + adjustment("Invert", b"nvrt", &[]), + top.clone(), + ]; + let (s, r) = open(&file(2, 1, &layers, depth, false, psb), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Dark + Light + Invert", "Top"], "{depth} {psb}: {r}"); + assert_eq!(r["warnings"], json!([]), "{depth} {psb}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255], [55, 105, 155, 128]], "{depth} {psb}: transparency stays"); + assert_eq!(row_of(&s, &d.layers[1]), [[1, 2, 3, 255]], "{depth} {psb}: the layer above isn't changed"); + } + let grays = [ + layer("128", [0, 0, 1, 1], [128, 128, 128, 255]), + layer("129", [0, 1, 1, 2], [129, 129, 129, 255]), + layer("Light", [0, 2, 1, 3], [200, 150, 100, 255]), + layer("Dark", [0, 3, 1, 4], [10, 20, 30, 255]), + ]; + let layers = [&grays[..], &[adjustment("Threshold", b"thrs", &[0, 128, 0, 0])][..]].concat(); + let (s, r) = open(&file(4, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["128 + 129 + Light + Dark + Threshold"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]]); + let layers = + [layer("A", [0, 0, 1, 1], [42, 43, 128, 255]), layer("B", [0, 1, 1, 2], [212, 213, 0, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0])]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["A + B + Posterize"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[0, 85, 170, 255], [170, 255, 0, 255]]); +} + +/// An adjustment layer's opacity, layer mask and blend mode decide how much of the adjusted color +/// replaces the color below. +#[test] +fn an_adjustment_layer_takes_its_opacity_mask_and_blend_mode() { + let black = || layer("Black", [0, 0, 1, 2], [0, 0, 0, 255]); + let half = L { opacity: 128, ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(2, 1, &[black(), half], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[128, 128, 128, 255]; 2], "{r}"); + // Black in the mask leaves the first pixel as it was; outside, the mask's default (white) applies it. + let masked = L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(2, 1, &[black(), masked], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255]], "{r}"); + assert!(d.layers[0].extras().mask.is_none(), "the mask is spent on the merge"); + // A disabled mask applies it everywhere. + let off = L { mask: Some(([0, 0, 1, 1], 255, 2, vec![0])), ..adjustment("Invert", b"nvrt", &[]) }; + let (s, _) = open(&file(2, 1, &[black(), off], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]; 2]); + // Multiply: the inverted color (55, 155, 205) multiplies the color below. + let multiply = L { blend: b"mul ", ..adjustment("Invert", b"nvrt", &[]) }; + let (s, _) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [200, 100, 50, 255]), multiply], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[43, 61, 40, 255]]); + // In a mode VectorCraft lacks, the warnings name the mode, as for other layers merged for it. + let dodge = L { blend: b"lddg", ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), dodge], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(r["warnings"], json!([merged])); +} + +/// Clipped to a layer, an adjustment layer changes only that layer and the layers clipped to it. +#[test] +fn a_clipped_adjustment_layer_changes_only_its_base() { + let layers = [ + layer("Other", [0, 1, 1, 2], [10, 10, 10, 255]), + layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Other", "Base + Invert"], "{r}"); + assert_eq!(r["warnings"], json!([])); + assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 10, 10, 255]], vec![[55, 255, 255, 255]])); + // Over a layer clipped to the same base, and only inside the base's shape. + let layers = [ + layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }, + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Photo + Invert"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 0, 255]]); + // Clipped to another adjustment layer, it isn't applied: the layers keep their colors. + let layers = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + adjustment("Curves", b"curv", &[0; 4]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) }, + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Curves + Photo"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 20, 30, 255]], vec![[0, 0, 255, 255]])); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // Its layer mask isn't read then: one too large to read doesn't stop the file opening. + let mut masked = layers; + masked[3].mask = Some(([0, 0, 1, 40_000], 0, 0, vec![200])); + let (s, r) = open(&file(1, 1, &masked, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Curves + Photo"], "{r}"); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // An Invert layer that a layer drawing nothing is clipped to isn't applied either. + let layers = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Empty", [0, 0, 0, 0], [0; 4]) }, + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"])); +} + +/// A hidden adjustment layer changes nothing and is left out, with or without the hidden layers; one +/// with nothing below it, or in an isolated group with nothing below it there, changes nothing. +#[test] +fn hidden_and_lone_adjustment_layers_change_nothing() { + for hidden in [false, true] { + let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), L { hidden: true, ..adjustment("Invert", b"nvrt", &[]) }]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Under"], &json!([HIDDEN_1])), "{hidden}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); + } + let (s, r) = open(&file(1, 1, &[adjustment("Invert", b"nvrt", &[]), layer("Top", [0, 0, 1, 1], [10, 20, 30, 255])], 8, false, false), json!({})); + assert_eq!((s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Top"], &json!([]))); + let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Isolated", b"norm")]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), &r["warnings"]), (vec!["Under", "Isolated"], &json!([]))); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); +} + +/// In a pass-through group with nothing below it in the group, an adjustment layer changes what is +/// below the group when the group is merged; when the group comes in as layers, it isn't applied. +#[test] +fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() { + let layers = |dodge: bool| { + let mut l = vec![layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass")]; + if dodge { + l.push(L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }); + } + l + }; + let (s, r) = open(&file(1, 1, &layers(true), 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]]); + let (s, r) = open(&file(1, 1, &layers(false), 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Folder"], "{r}"); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"])); + // Two at the bottom of the group both change what is below it, in order: inverted, then + // posterized to 4 levels (without the Invert the color would posterize to black). + let stacked = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &stacked, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}"); + // One above a layer of the group, with one kept below that layer, is kept too: the group draws + // them in order over what is below it. + let between = [ + layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + layer("Top", [0, 1, 1, 2], [100, 100, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(2, 1, &between, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255], [85, 85, 85, 255]], "{r}"); + // Another adjustment layer below it in the group draws nothing, so it still changes what is + // below the group. + let over_curves = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Curves", b"curv", &[0; 4]), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &over_curves, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}"); + // One kept in a pass-through group inside the group keeps the ones above it too: inverted, then + // posterized to 4 levels. + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}"); + // Without the merge, the group comes in as layers and both are counted as not applied. + let (s, r) = open(&file(1, 1, &nested[..7], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Folder"], "{r}"); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // Merged in the group with a layer in a mode VectorCraft lacks, it has nothing to change. + let inside = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &inside, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!((names, &r["warnings"]), (vec!["Under", "Folder"], &json!(["1 adjustment layer was not applied", merged])), "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); +} + +/// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level +/// out of range, data too short, or a second adjustment block on the layer. +#[test] +fn adjustment_data_that_cant_be_read_isnt_applied() { + let mut twice = adjustment("Twice", b"nvrt", &[]); + twice.blocks.push((*b"post", vec![0, 4, 0, 0])); + let mut apart = adjustment("Apart", b"nvrt", &[]); + apart.blocks.extend([(*b"SoCo", vec![]), (*b"post", vec![0, 4, 0, 0])]); + let cases = [ + adjustment("Level 0", b"thrs", &[0, 0, 0, 0]), + adjustment("Level 256", b"thrs", &[1, 0, 0, 0]), + adjustment("No level", b"thrs", &[]), + adjustment("No padding", b"thrs", &[0, 128]), + adjustment("No padding", b"post", &[0, 4]), + adjustment("1 level", b"post", &[0, 1, 0, 0]), + adjustment("256 levels", b"post", &[1, 0, 0, 0]), + twice, + apart, + ]; + for bad in cases { + let what = bad.name; + let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), bad], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{what}: {r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]], "{what}"); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]), "{what}"); + } + // The highest level and count are read. + let under = |c: u8| layer("Under", [0, 0, 1, 1], [c, c, c, 255]); + let (s, r) = open(&file(1, 1, &[under(254), adjustment("Max", b"thrs", &[0, 255, 0, 0])], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[0, 0, 0, 255]], "{r}"); + let (s, r) = open(&file(1, 1, &[under(7), adjustment("Max", b"post", &[0, 255, 0, 0])], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[7, 7, 7, 255]], "{r}"); +} + +/// An adjustment layer whose merge needs more memory than allowed isn't applied: the layers below +/// it stay as they are, with a warning. +#[test] +fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), layer("Beside", [2, 2, 4, 4], [1, 2, 3, 255]), adjustment("Invert", b"nvrt", &[])]; + let f = file(4, 4, &layers, 8, false, false); + // Each 2 × 2 layer fits 128 bytes; the 4 × 4 canvas of both doesn't. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Beside"]); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Beside + Invert"]); + assert!(warnings.is_empty(), "{warnings:?}"); + // Clipped: the base's canvas with its shape doesn't fit 300 bytes, so the adjustment is left + // out rather than applied to everything below. + let layers = [layer("Base", [0, 0, 4, 4], [10, 20, 30, 255]), L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base"]); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + // A layer clipped to an Invert layer whose merge doesn't fit comes in unclipped, and the Invert + // layer isn't applied to the layers below it. + let layers = [ + layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Photo", [0, 0, 4, 4], [1, 2, 3, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under", "Photo"], "{warnings:?}"); + assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}"); +} + +/// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. +#[test] +fn damaged_adjustment_layers_never_panic() { + let layers = [ + layer("A", [0, 0, 2, 2], [255, 0, 0, 255]), + L { mask: Some(([0, 0, 1, 1], 0, 0, vec![200])), ..adjustment("Invert", b"nvrt", &[]) }, + L { clipped: true, ..adjustment("Threshold", b"thrs", &[0, 128, 0, 0]) }, + adjustment("Posterize", b"post", &[0, 3, 0, 0]), + ]; + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let good = file(2, 2, &layers, 8, false, false); + assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some()); + for i in 0..good.len() { + for v in [0, 1, 0x7f, 0x80, 0xff] { + let mut f = good.clone(); + f[i] = v; + let _ = psdlayers::import(&f, true, 1 << 30, cms); + let _ = psdlayers::import(&f, false, 64, cms); + } + } + for n in 0..good.len() { + let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + } +} + /// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public /// descriptions: <https://helpx.adobe.com/photoshop/desktop/repair-retouch/adjust-light-tone/blending-mode-descriptions.html> /// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 9c83f697da..b655ed0eb5 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2095,7 +2095,8 @@ proptest! { /// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden /// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count. - /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.) + /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`, and + /// Invert, Threshold and Posterize layers by `tests_psdlayers::damaged_adjustment_layers_never_panic`.) /// Neither does `document.psdInfo`, nor placing them with their layers as objects. #[test] fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::<u8>()), 0..12)) { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..5e4b1ddf55 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10872,8 +10872,8 @@ clipping mask into one layer and discards hidden layers that require merging; th imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with `layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with -the layers below them. `document.open` does not apply adjustments, applies only shallow knockouts inside groups, and -otherwise merges a layer by its blend mode alone, as the rules below say. +the layers below them. `document.open` applies only Invert, Threshold and Posterize adjustments, applies only +shallow knockouts inside groups, and otherwise merges a layer by its blend mode alone, as the rules below say. The rest are VectorCraft's own rules: @@ -10909,10 +10909,22 @@ The rest are VectorCraft's own rules: stores. A solid color fill layer that stores no pixels and has no vector mask comes in as an image of its color (RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers clipped to it are left out. -- Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, - the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with - layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are - not applied; the `warnings` count them. +- An Invert, Threshold or Posterize adjustment layer (`nvrt`, `thrs` and `post` in the PSD file format + specification) is merged with the visible layers below it in its group, which it changes. Clipped to a layer, it + changes only that layer and the layers clipped to it. Each color channel is taken as an 8-bit sRGB value: Invert + turns `v` into `255 − v`; Threshold makes a pixel white when its luminance (Rec. 709 weights on linear sRGB, + encoded back to 0..255) is above the level (1 to 255) and black otherwise; Posterize maps each channel to the + nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the + color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and + transparency is kept. A hidden one is left out. One with nothing visible below it in its group changes nothing; in + a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + applied. +- Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to + another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on + one layer) or whose merge needs more memory than allowed, fill layers that store no pixels and whose fill isn't + read, layer effects that are switched on, the other knockouts (top-level layers, clipped layers, layers that others + are clipped to, Pass Through groups with layers in other modes, other Knockout values, and merges that need more + memory than allowed) and vector masks are not applied; the `warnings` count them. - Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits. - A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image with a warning, and when the merged image can't be read either, the file is refused with an error. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..2f1aee44ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2323,7 +2323,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group changes nothing, and in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 248936eec3db137fb1e523481aa534f347b62faf Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 04:32:16 -0800 Subject: [PATCH 101/126] Tests: the test262 runner parses and runs the Annex B tests The test262 runner read only test/language and a few built-ins folders, so the Annex B tests were never counted, among them the for-in variable with an initializer that must parse in sloppy code and give a SyntaxError in strict code. - annex_b_parse_subset parses every test under test/annexB/language without a feature tag, of any edition, in the modes its flags give, and writes annexb-parse-failures.txt. - annex_b_runs runs those tests and the test/annexB/built-ins tests for String, Date, RegExp and Function through the interpreter and writes annexb-language-failures.txt and annexb-builtins-failures.txt. The escape and unescape folders still run once, with the ES5 built-ins. - A suite without test/annexB skips both; a folder there with nothing to parse or run fails them. Conformance failures stay in the reports. - The runner reads only regular files inside the suite: it does not follow symbolic links, refuses an includes: name that leaves harness/, refuses a file over 8 MiB before reading it, and fails on a folder it cannot read instead of skipping it. Docs: docs/target-app-parity.md, the xtask test262 module comment. --- crates/js/tests/test262.rs | 495 +++++++++++++++++++++++++++++-------- docs/target-app-parity.md | 1 + xtask/src/test262.rs | 4 +- 3 files changed, 400 insertions(+), 100 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index bf32bcfcd6..8ae4d36f6a 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -27,6 +27,17 @@ //! an ES5 section apart from the other tests without a feature tag; its failures go to //! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness //! or test file cannot be read, or when no ES5 test runs. +//! +//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every +//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset +//! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the +//! folders [`ANNEX_B_BUILT_INS`] names through the interpreter (failures in +//! `annexb-language-failures.txt` and `annexb-builtins-failures.txt`). A suite without +//! `test/annexB/` skips them; a folder there with no test to parse or run fails them. +//! +//! The runner reads only regular files inside the suite: it does not follow symbolic links, refuses +//! an `includes:` name that leaves the `harness/` folder, and refuses a file over +//! [`MAX_FILE_BYTES`] before reading it. A folder or file it cannot read fails the test. use std::collections::HashSet; use std::path::{Path, PathBuf}; @@ -56,23 +67,89 @@ fn suite_dir() -> Option<PathBuf> { dirs.pop() } -/// The `.js` files under `dir`, sorted, with the `_FIXTURE` helper files left out. -fn test_files(dir: &Path) -> Vec<PathBuf> { +/// The largest test or harness file read (the largest file in the pinned suite is 3,234,014 bytes). +const MAX_FILE_BYTES: u64 = 8 << 20; + +/// The value of `result`; an error fails the test with its message. +fn or_fail<T: Default>(result: Result<T, String>) -> T { + assert!(result.is_ok(), "{}", result.as_ref().err().map_or("", String::as_str)); + result.unwrap_or_default() +} + +/// `dir` joined with the `/`-separated path `rel`. An empty, `.` or `..` component, one holding a +/// `\` or `:`, and a component that is a symbolic link give an error, so the path stays inside +/// `dir`. A component that does not exist is not checked further. +fn inside(dir: &Path, rel: &str) -> Result<PathBuf, String> { + let mut path = dir.to_path_buf(); + for part in rel.split('/') { + if part.is_empty() || part == "." || part == ".." || part.contains(['\\', ':']) { + return Err(format!("{rel} is not a path inside {}", dir.display())); + } + path.push(part); + if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(format!("{} is a symbolic link; the runner reads only files inside the suite", path.display())); + } + } + Ok(path) +} + +/// Reads a test or harness file: a regular file (not a symbolic link) of at most +/// [`MAX_FILE_BYTES`], with invalid UTF-8 replaced. +fn read_source(path: &Path) -> Result<String, String> { + let meta = std::fs::symlink_metadata(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if !meta.is_file() { + return Err(format!("{} is not a regular file", path.display())); + } + if meta.len() > MAX_FILE_BYTES { + return Err(format!("{} is {} bytes, over the {MAX_FILE_BYTES}-byte limit", path.display(), meta.len())); + } + let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + +/// The `.js` files under `dir`, sorted, with the `_FIXTURE` helper files and symbolic links left +/// out. A folder or entry that cannot be read gives an error. +fn test_files(dir: &Path) -> Result<Vec<PathBuf>, String> { let mut out = Vec::new(); let mut stack = vec![dir.to_path_buf()]; while let Some(d) = stack.pop() { - let Ok(entries) = std::fs::read_dir(&d) else { continue }; - for entry in entries.flatten() { + let entries = std::fs::read_dir(&d).map_err(|e| format!("cannot read {}: {e}", d.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("cannot read {}: {e}", d.display()))?; let path = entry.path(); - if path.is_dir() { + let kind = entry.file_type().map_err(|e| format!("cannot read {}: {e}", path.display()))?; + if kind.is_dir() { stack.push(path); - } else if path.extension().is_some_and(|e| e == "js") && !path.to_string_lossy().contains("_FIXTURE") { + } else if kind.is_file() && path.extension().is_some_and(|e| e == "js") && !path.to_string_lossy().contains("_FIXTURE") { out.push(path); } } } out.sort(); - out + Ok(out) +} + +/// The modes a test runs in, `true` for strict mode code: both, unless its `onlyStrict`, +/// `noStrict` or `raw` flag says otherwise. +fn modes(meta: &Meta) -> &'static [bool] { + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if has("raw") || has("noStrict") { + &[false] + } else if has("onlyStrict") { + &[true] + } else { + &[false, true] + } +} + +/// The test is a script without a feature tag and, unless `any_edition` is set, names an ES5 +/// section. The Annex B tests name the edition they were written for with `esid:`, so they are +/// read with `any_edition`. +fn eligible(meta: &Meta, any_edition: bool) -> bool { + (meta.es5 || any_edition) + && meta.features.is_empty() + && !meta.flags.iter().any(|f| f == "module") + && meta.negative_phase.as_deref() != Some("resolution") } /// A YAML flow list (`[a, b]`) or the block list (`- a` lines) after a key. @@ -127,70 +204,15 @@ fn es5_parse_subset() { println!("test262: SKIPPED (no suite; run cargo xtask test262)"); return; }; - let language = dir.join("test").join("language"); + let language = or_fail(inside(&dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); - let files = test_files(&language); + let files = or_fail(test_files(&language)); assert!(!files.is_empty(), "no tests under {}", language.display()); - // VECTORCRAFT_TEST262_VERBOSE=1 prints each test before it is parsed. - let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); - - let (mut positive, mut negative, mut with_features, mut modules) = (0usize, 0usize, 0usize, 0usize); - let (mut passed, mut failed) = (0usize, 0usize); - // The tests without a feature tag that name no ES5 section: files, runs passed and failed. - let (mut later, mut later_passed, mut later_failed) = (0usize, 0usize, 0usize); - let mut failures = String::new(); - let mut later_failures = String::new(); - for path in &files { - let source = String::from_utf8_lossy(&std::fs::read(path).unwrap()).into_owned(); - let meta = meta(&source); - if !meta.features.is_empty() { - with_features += 1; - continue; - } - if meta.flags.iter().any(|f| f == "module") || meta.negative_phase.as_deref() == Some("resolution") { - modules += 1; - continue; - } - let expect_error = meta.negative_phase.as_deref() == Some("parse"); - if !meta.es5 { - later += 1; - } else if expect_error { - negative += 1; - } else { - positive += 1; - } - let has = |flag: &str| meta.flags.iter().any(|f| f == flag); - let modes: &[bool] = if has("raw") || has("noStrict") { - &[false] - } else if has("onlyStrict") { - &[true] - } else { - &[false, true] - }; - for &strict in modes { - if verbose { - eprintln!("{} ({})", path.display(), if strict { "strict" } else { "sloppy" }); - } - let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() }; - let result = parse(&text, &Options::default()); - let (pass, fail, list) = - if meta.es5 { (&mut passed, &mut failed, &mut failures) } else { (&mut later_passed, &mut later_failed, &mut later_failures) }; - if result.is_err() == expect_error { - *pass += 1; - } else { - *fail += 1; - let rel = path.strip_prefix(&dir).unwrap_or(path).display().to_string().replace('\\', "/"); - let mode = if strict { "strict" } else { "sloppy" }; - let outcome = match &result { - Ok(_) => "parsed; a SyntaxError was expected".to_string(), - Err(e) => e.to_string(), - }; - list.push_str(&format!("{rel} ({mode}): {outcome}\n")); - } - } - } + let ParseRun { main: es5, later: other, with_features, modules } = or_fail(parse_files(&dir, &files, false)); + let (positive, negative, passed, failed) = (es5.positive, es5.negative, es5.passed, es5.failed); + let (later, later_passed, later_failed) = (other.positive + other.negative, other.passed, other.failed); let report = dir.join("failures.txt"); - std::fs::write(&report, format!("# ES5 subset\n{failures}\n# Other tests without a feature tag\n{later_failures}")).unwrap(); + std::fs::write(&report, format!("# ES5 subset\n{}\n# Other tests without a feature tag\n{}", es5.failures, other.failures)).unwrap(); println!( "test262 ES5 parse subset ({}): {} tests ({positive} that must parse, {negative} that must give a SyntaxError), \ {passed} runs passed, {failed} failed. Other tests without a feature tag: {later} tests, {later_passed} runs passed, \ @@ -201,6 +223,112 @@ fn es5_parse_subset() { ); } +#[test] +fn annex_b_parse_subset() { + let Some(dir) = suite_dir() else { + println!("test262 Annex B parse: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let language = or_fail(inside(&dir, "test/annexB/language")); + if !language.exists() { + println!("test262 Annex B parse: SKIPPED ({} has no test/annexB/language)", dir.display()); + return; + } + let files = or_fail(test_files(&language)); + let ParseRun { main, with_features, modules, .. } = or_fail(parse_files(&dir, &files, true)); + assert!(main.positive + main.negative > 0, "no Annex B tests to parse under {}", language.display()); + let report = dir.join("annexb-parse-failures.txt"); + if let Err(e) = std::fs::write(&report, &main.failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 Annex B language parse: {} tests ({} that must parse, {} that must give a SyntaxError), {} runs passed, {} failed. \ + Skipped {with_features} tests with feature tags and {modules} module tests. Failures: {}", + main.positive + main.negative, + main.positive, + main.negative, + main.passed, + main.failed, + report.display() + ); +} + +/// The parse counts of one group of tests. +#[derive(Default)] +struct ParseCounts { + /// Tests that must parse. + positive: usize, + /// Tests that must give a `SyntaxError`. + negative: usize, + passed: usize, + failed: usize, + failures: String, +} + +/// The counts of [`parse_files`]. +#[derive(Default)] +struct ParseRun { + /// The tests that name an ES5 section, or every eligible test when any edition is read. + main: ParseCounts, + /// The other tests without a feature tag. + later: ParseCounts, + with_features: usize, + modules: usize, +} + +/// Parses each of `files` in the modes its flags give. With `any_edition`, every test without a +/// feature tag is counted in [`ParseRun::main`]; otherwise only those that name an ES5 section. +fn parse_files(dir: &Path, files: &[PathBuf], any_edition: bool) -> Result<ParseRun, String> { + // VECTORCRAFT_TEST262_VERBOSE=1 prints each test before it is parsed. + let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); + let mut run = ParseRun::default(); + for path in files { + let source = read_source(path)?; + let meta = meta(&source); + if !meta.features.is_empty() { + run.with_features += 1; + continue; + } + if !eligible(&meta, true) { + run.modules += 1; + continue; + } + let counts = if eligible(&meta, any_edition) { &mut run.main } else { &mut run.later }; + if meta.negative_phase.as_deref() == Some("parse") { + counts.negative += 1; + } else { + counts.positive += 1; + } + let rel = path.strip_prefix(dir).unwrap_or(path).display().to_string().replace('\\', "/"); + for &strict in modes(&meta) { + let mode = if strict { "strict" } else { "sloppy" }; + if verbose { + eprintln!("{} ({mode})", path.display()); + } + match parse_check(&source, &meta, strict) { + Ok(()) => counts.passed += 1, + Err(outcome) => { + counts.failed += 1; + counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n")); + } + } + } + } + Ok(run) +} + +/// Parses `source` as sloppy or strict mode code (with `"use strict";` before it); `Err` describes +/// a result other than the one the metadata expects (a `SyntaxError` for `negative: phase: parse`). +fn parse_check(source: &str, meta: &Meta, strict: bool) -> Result<(), String> { + let expect_error = meta.negative_phase.as_deref() == Some("parse"); + let text = if strict { format!("\"use strict\";\n{source}") } else { source.to_string() }; + match parse(&text, &Options::default()) { + Ok(_) if expect_error => Err("parsed; a SyntaxError was expected".to_string()), + Err(e) if !expect_error => Err(e.to_string()), + _ => Ok(()), + } +} + /// Globals and method names the interpreter does not provide yet: a test that names one, in its /// own source or in a harness file it includes, is skipped. const MISSING_BUILTINS: &str = "String Number Boolean Date RegExp print $262 $DONE Symbol Proxy Reflect Promise Map Set WeakMap \ @@ -233,6 +361,14 @@ const ES5_BUILT_INS: &[&str] = &[ "annexB/built-ins/unescape", ]; +/// The tests of the Annex B syntax and semantics (ECMA-262 Annex B.1 and B.3). +const ANNEX_B_LANGUAGE: &str = "annexB/language"; + +/// The folders under `test/annexB/built-ins/` with tests without a feature tag, other than the +/// `escape` and `unescape` folders [`ES5_BUILT_INS`] runs: `substr`, `getYear`, `setYear`, +/// `toGMTString`, the legacy `RegExp` features and the `Function` tests. +const ANNEX_B_BUILT_INS: &[&str] = &["annexB/built-ins/Date", "annexB/built-ins/Function", "annexB/built-ins/RegExp", "annexB/built-ins/String"]; + /// The names in [`MISSING_BUILTINS`] that `String`, `Number`, `RegExp` and `Date` provide. const TEXT_BUILTINS: &str = "String Number Date RegExp charAt charCodeAt fromCharCode substring substr split replace match search exec test \ toUpperCase toLowerCase trim toFixed toPrecision toExponential now"; @@ -335,10 +471,20 @@ impl RunCounts { self.tests, self.passed, self.failed, self.panicked, self.skipped ) } + + /// Adds the counts and failures of `other`. + fn add(&mut self, other: RunCounts) { + self.tests += other.tests; + self.skipped += other.skipped; + self.passed += other.passed; + self.failed += other.failed; + self.panicked += other.panicked; + self.failures.push_str(&other.failures); + } } fn run_language_subset(dir: &Path) { - let language = dir.join("test").join("language"); + let language = or_fail(inside(dir, "test/language")); assert!(language.is_dir(), "{} is not a test262 checkout", dir.display()); let missing = missing_builtins(&[TEXT_BUILTINS]); let (es5, _) = run_tests(dir, &language, &missing, false); @@ -377,17 +523,11 @@ fn run_built_ins(dir: &Path) { let missing = missing_builtins(&[TEXT_BUILTINS]); let mut all = RunCounts::default(); for folder in ES5_BUILT_INS { - let root = dir.join("test").join(folder); + let root = or_fail(inside(dir, &format!("test/{folder}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); let (es5, later) = run_tests(dir, &root, &missing, folder.starts_with("annexB")); - for counts in [es5, later] { - all.tests += counts.tests; - all.skipped += counts.skipped; - all.passed += counts.passed; - all.failed += counts.failed; - all.panicked += counts.panicked; - all.failures.push_str(&counts.failures); - } + all.add(es5); + all.add(later); } assert!(all.tests > 0, "no ES5 built-ins tests ran under {}", dir.display()); let report = dir.join("built-ins-failures.txt"); @@ -414,7 +554,7 @@ fn run_text_builtins(dir: &Path) { let mut report = String::new(); let mut panicked = 0; for name in ["String", "Number", "RegExp", "Date"] { - let root = dir.join("test").join("built-ins").join(name); + let root = or_fail(inside(dir, &format!("test/built-ins/{name}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); let missing = if name == "String" { missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) } else { missing_builtins(&[TEXT_BUILTINS]) }; @@ -436,39 +576,27 @@ fn run_text_builtins(dir: &Path) { /// negative parse tests, each in a new realm after the harness. Returns the counts for the tests /// that name an ES5 section and, when `later` is set, for the others (otherwise those are left out). fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (RunCounts, RunCounts) { - let harness_dir = dir.join("harness"); - let read = |p: &Path| { - let bytes = std::fs::read(p).map_err(|e| format!("cannot read {}: {e}", p.display())); - assert!(bytes.is_ok(), "{}", bytes.as_ref().err().map_or("", String::as_str)); - String::from_utf8_lossy(&bytes.unwrap_or_default()).into_owned() - }; - let prelude = format!("{}\n{}\n", read(&harness_dir.join("assert.js")), read(&harness_dir.join("sta.js"))); + // A harness file is named by the test's `includes:`, so it is read only inside `harness/`. + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); let verbose = std::env::var_os("VECTORCRAFT_TEST262_VERBOSE").is_some(); let (mut es5_counts, mut later_counts) = (RunCounts::default(), RunCounts::default()); - for path in test_files(root) { - let source = read(&path); + for path in or_fail(test_files(root)) { + let source = or_fail(read_source(&path)); let meta = meta(&source); - let negative_parse = matches!(meta.negative_phase.as_deref(), Some("parse" | "resolution")); - if (!meta.es5 && !later) || !meta.features.is_empty() || negative_parse || meta.flags.iter().any(|f| f == "module") { + if !eligible(&meta, later) || meta.negative_phase.as_deref() == Some("parse") { continue; } let counts = if meta.es5 { &mut es5_counts } else { &mut later_counts }; - let includes: String = meta.includes.iter().map(|i| read(&harness_dir.join(i)) + "\n").collect(); + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); if meta.flags.iter().any(|f| f == "async") || needs_missing_builtin(&[&source, &includes], missing) { counts.skipped += 1; continue; } counts.tests += 1; let has = |flag: &str| meta.flags.iter().any(|f| f == flag); - let modes: &[bool] = if has("raw") || has("noStrict") { - &[false] - } else if has("onlyStrict") { - &[true] - } else { - &[false, true] - }; let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); - for &strict in modes { + for &strict in modes(&meta) { let mode = if strict { "strict" } else { "sloppy" }; if verbose { eprintln!("{rel} ({mode})"); @@ -494,6 +622,63 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> ( (es5_counts, later_counts) } +#[test] +fn annex_b_runs() { + let Some(dir) = suite_dir() else { + println!("test262 Annex B interpreter: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_annex_b(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// Runs the tests without a feature tag under [`ANNEX_B_LANGUAGE`] and under each folder +/// [`ANNEX_B_BUILT_INS`] names, of any edition, prints the counts of each and writes the failures +/// to `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. +fn run_annex_b(dir: &Path) { + let annex_b = or_fail(inside(dir, "test/annexB")); + if !annex_b.exists() { + println!("test262 Annex B interpreter: SKIPPED ({} has no test/annexB)", dir.display()); + return; + } + let mut panicked = 0; + let mut built_ins_report = String::new(); + for folder in std::iter::once(&ANNEX_B_LANGUAGE).chain(ANNEX_B_BUILT_INS) { + let root = or_fail(inside(dir, &format!("test/{folder}"))); + if !root.exists() { + println!("test262 {folder}: SKIPPED (not in this suite)"); + continue; + } + let missing = if folder.ends_with("/String") { + missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) + } else { + missing_builtins(&[TEXT_BUILTINS]) + }; + let (es5, later) = run_tests(dir, &root, &missing, true); + let mut counts = RunCounts::default(); + counts.add(es5); + counts.add(later); + assert!(counts.tests + counts.skipped > 0, "no Annex B tests to run under {}", root.display()); + panicked += counts.panicked; + println!("test262 {folder} through the interpreter: {}.", counts.summary()); + if *folder == ANNEX_B_LANGUAGE { + let path = dir.join("annexb-language-failures.txt"); + if let Err(e) = std::fs::write(&path, &counts.failures) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 {folder} failures: {}", path.display()); + } else { + built_ins_report.push_str(&format!("# {folder}\n{}\n", counts.failures)); + } + } + let path = dir.join("annexb-builtins-failures.txt"); + if let Err(e) = std::fs::write(&path, &built_ins_report) { + println!("could not write {}: {e}", path.display()); + } + println!("test262 Annex B built-ins failures: {}", path.display()); + assert_eq!(panicked, 0, "the interpreter panicked; see the Annex B failure files in {}", dir.display()); +} + /// `needs_missing_builtin` with `Map`, `Symbol` and `Set` missing. fn skips(sources: &[&str]) -> bool { let missing: HashSet<&str> = ["Map", "Symbol", "Set"].into_iter().collect(); @@ -558,3 +743,115 @@ fn a_source_that_does_not_parse_as_es5_skips() { assert!(skips(&["var x = 1;", "const y = 2;"])); assert!(skips(&["var s = `${x}`;"])); } + +#[test] +fn annex_b_runs_read_the_language_tree_and_the_built_ins_folders_not_run_elsewhere() { + assert_eq!(ANNEX_B_LANGUAGE, "annexB/language"); + for folder in ["annexB/built-ins/String", "annexB/built-ins/Date", "annexB/built-ins/RegExp", "annexB/built-ins/Function"] { + assert!(ANNEX_B_BUILT_INS.contains(&folder), "{folder} is not read"); + } + // `escape` and `unescape` run with the ES5 built-ins, so they are not run twice. + for folder in ANNEX_B_BUILT_INS { + assert!(!ES5_BUILT_INS.contains(folder), "{folder} runs twice"); + assert!(folder.starts_with("annexB/built-ins/"), "{folder} is not an Annex B built-ins folder"); + } +} + +/// A test written for a later edition, naming its section with `esid:` only. +const ESID_ONLY: &str = "/*---\nesid: sec-example\ndescription: a test of a later edition\n---*/\nvar a = 1;\n"; + +#[test] +fn tests_that_name_only_a_later_section_are_read_with_any_edition() { + let later = meta(ESID_ONLY); + assert!(!later.es5); + assert!(eligible(&later, true)); + assert!(!eligible(&later, false)); + let es5 = meta("/*---\nes5id: 12.6.4\n---*/\nvar a = 1;\n"); + assert!(eligible(&es5, false)); + let tagged = meta("/*---\nesid: sec-example\nfeatures: [let]\n---*/\nlet a = 1;\n"); + assert!(!eligible(&tagged, true)); + let module = meta("/*---\nesid: sec-example\nflags: [module]\n---*/\nvar a = 1;\n"); + assert!(!eligible(&module, true)); +} + +/// A strict-only test that expects a `SyntaxError` for an initializer on a for-in variable. +const STRICT_FOR_IN_INITIALIZER: &str = + "/*---\nesid: sec-example\nnegative:\n phase: parse\n type: SyntaxError\nflags: [onlyStrict]\n---*/\nfor (var a = 0 in {}) {}\n"; + +/// A sloppy-only test with an initializer on a for-in variable, which must parse. +const SLOPPY_FOR_IN_INITIALIZER: &str = "/*---\nesid: sec-example\nflags: [noStrict]\n---*/\nvar n = 0;\nfor (var a = 1 in {}) { n += 1; }\n"; + +#[test] +fn a_for_in_initializer_is_a_syntax_error_in_strict_code_only() { + let strict = meta(STRICT_FOR_IN_INITIALIZER); + assert_eq!(strict.negative_phase.as_deref(), Some("parse")); + assert_eq!(modes(&strict), &[true]); + assert_eq!(parse_check(STRICT_FOR_IN_INITIALIZER, &strict, true), Ok(())); + assert!(parse_check(STRICT_FOR_IN_INITIALIZER, &strict, false).is_err(), "the initializer parses in sloppy code"); + + let sloppy = meta(SLOPPY_FOR_IN_INITIALIZER); + assert_eq!(sloppy.negative_phase, None); + assert_eq!(modes(&sloppy), &[false]); + assert_eq!(parse_check(SLOPPY_FOR_IN_INITIALIZER, &sloppy, false), Ok(())); + assert!(parse_check(SLOPPY_FOR_IN_INITIALIZER, &sloppy, true).is_err(), "the initializer parses in strict code"); + + assert_eq!(modes(&meta(ESID_ONLY)), &[false, true]); + assert_eq!(modes(&meta("/*---\nflags: [raw]\n---*/\n")), &[false]); +} + +/// A new, empty folder under the system's temporary folder for one test. +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-test262-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + or_fail(std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))); + dir +} + +#[test] +fn the_walk_reads_only_test_files_inside_the_folder() { + let dir = scratch("walk"); + std::fs::create_dir_all(dir.join("suite/sub")).unwrap(); + std::fs::write(dir.join("suite/b.js"), "").unwrap(); + std::fs::write(dir.join("suite/sub/a.js"), "").unwrap(); + std::fs::write(dir.join("suite/c_FIXTURE.js"), "").unwrap(); + std::fs::write(dir.join("suite/notes.txt"), "").unwrap(); + assert_eq!(test_files(&dir.join("suite")), Ok(vec![dir.join("suite/b.js"), dir.join("suite/sub/a.js")])); + assert!(test_files(&dir.join("absent")).is_err(), "a missing folder is skipped silently"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[cfg(unix)] +#[test] +fn the_walk_does_not_follow_symbolic_links() { + let dir = scratch("links"); + std::fs::create_dir_all(dir.join("suite")).unwrap(); + std::fs::create_dir_all(dir.join("outside")).unwrap(); + std::fs::write(dir.join("outside/x.js"), "").unwrap(); + std::fs::write(dir.join("suite/a.js"), "").unwrap(); + std::os::unix::fs::symlink(dir.join("outside"), dir.join("suite/linked")).unwrap(); + std::os::unix::fs::symlink(dir.join("outside/x.js"), dir.join("suite/x.js")).unwrap(); + assert_eq!(test_files(&dir.join("suite")), Ok(vec![dir.join("suite/a.js")])); + assert!(read_source(&dir.join("suite/x.js")).is_err(), "a linked file is read"); + assert!(inside(&dir.join("suite"), "linked/x.js").is_err(), "a path through a linked folder is allowed"); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn harness_names_stay_inside_the_suite() { + let dir = Path::new("suite"); + assert_eq!(inside(dir, "harness/compareArray.js"), Ok(dir.join("harness").join("compareArray.js"))); + for name in ["harness/../../secret.js", "harness/./a.js", "/etc/passwd", "harness//a.js", "harness/a\\..\\b.js", "harness/C:a.js", ""] { + assert!(inside(dir, name).is_err(), "{name:?} is allowed"); + } +} + +#[test] +fn a_file_over_the_limit_is_refused_before_it_is_read() { + let dir = scratch("size"); + let path = dir.join("big.js"); + std::fs::File::create(&path).unwrap().set_len(MAX_FILE_BYTES + 1).unwrap(); + assert!(read_source(&path).is_err_and(|e| e.contains("over the")), "an oversized file is read"); + std::fs::File::create(&path).unwrap().set_len(4).unwrap(); + assert_eq!(read_source(&path), Ok("\0\0\0\0".to_string())); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..4ac30a925d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1077,6 +1077,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. + - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite and do not fail the tests. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `<!DOCTYPE>` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. diff --git a/xtask/src/test262.rs b/xtask/src/test262.rs index dfed1d8ae3..7ee456a6c2 100644 --- a/xtask/src/test262.rs +++ b/xtask/src/test262.rs @@ -4,7 +4,9 @@ //! runs `vectorcraft-js`'s `test262` tests, which parse the ES5 parse subset, run the ES5 //! `test/language` tests and the tests of the ES5 built-ins under `test/built-ins` and //! `test/annexB/built-ins` that need only the interpreter's built-ins, run the `test/built-ins` -//! tests for `String`, `Number`, `RegExp` and `Date`, and print each one's counts. +//! tests for `String`, `Number`, `RegExp` and `Date`, parse and run the `test/annexB/language` +//! tests and run the other `test/annexB/built-ins` tests (`String`, `Date`, `RegExp` and +//! `Function`), and print each one's counts. //! //! It also fetches `json2.js`, Douglas Crockford's public-domain JSON polyfill //! (https://github.com/douglascrockford/JSON-js), at a pinned commit, checks it against its SHA-256 From 35e43f9cfef483d5840c8a8baa88d1ba4832ed14 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 04:57:17 -0800 Subject: [PATCH 102/126] Swatch libraries: library tints and gradients link to their colors in any order A library tint or gradient whose global or spot color comes in under a numbered name now links to that copy whichever order the swatches are picked in, when the color was added by an earlier call, and when a pattern's art brought the color or took the document's copy of it. Adding the same tints again finds the ones added before. - Each tint's or gradient's color is looked up for itself before anything is added, past a process swatch of the same paint and past a color group of that name. A numbered copy that the library's own swatch of that name is stays that swatch's, and a new copy skips the library's other names. - A tint links to a global or spot color of the same kind only, and to a color this call picks rather than to a copy a pattern took. - Links are set as soon as the color's name is known. A tint waiting for a color that a pattern's art brings learns its name from an import into a copy, so the pattern does not add a second tint. - A swatch a pattern brought takes a picked swatch's place only when its colors link where the picked one's do. - A stop linked to the Registration swatch counts as linked. - library.use, Add to Swatches and the reuse check share one import probe (patternlib::probe_import), and the probed copy is kept instead of importing a second time. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/clipboard/resources.rs | 5 +- crates/engine/src/cmd/library.rs | 30 +- crates/engine/src/cmd/patternlib.rs | 81 ++-- crates/engine/src/cmd/swatchlib.rs | 247 +++++++++-- crates/engine/src/tests/swatchlib.rs | 418 +++++++++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 7 files changed, 686 insertions(+), 104 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 4d1c3aa53a..c20c763495 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -623,9 +623,8 @@ impl SwatchChoices { Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }), } } - /// Add for every conflict, as a library pattern is added to a document: each global or spot - /// color of its art whose name the document gives another color comes in under a numbered - /// name, or as the document's numbered copy of that name with the same color. + /// Add for every conflict: each pasted swatch whose name the document gives another color + /// comes in renamed. pub(crate) fn add_all() -> Self { Self { all: SwatchChoice::Add, by_name: BTreeMap::new() } } diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 6bbb4049e0..ecbfa760bb 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -20,7 +20,6 @@ use serde_json::{Map, Value, json}; use vectorcraft_color::{Color, GradientPaint, Paint}; use vectorcraft_doc::{Appearance, Node, NodeId, TextStyleDef}; -use super::clipboard::SwatchChoices; use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, color_value, has_doc, ids_param, index_opt, ok, point_param, str_param}; use crate::Clipboard; @@ -1353,32 +1352,13 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> { if clip.nodes.is_empty() { return Err(damaged()); } - // A global or spot color the pattern's art links to keeps the library's color: when the - // document gives its name another color, it comes in under a numbered name ("Ink 2"), as - // Add to Swatches brings a library pattern's colors. - let mut choices = SwatchChoices::add_all(); - // The pattern's name in the document, worked out on a copy: nothing to add is no edit. + // The pattern's name in the document, worked out on a copy: nothing to add is no edit. A global + // or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings + // a library pattern's colors. let current = s.doc()?.doc.clone(); - let mut probe = (*current).clone(); - let mut imported = clip.import_into(&mut probe, &choices, false)?; - let pattern_of = |i: &super::clipboard::resources::Imported| { - i.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name.as_str()).and_then(|r| r["to"].as_str()).unwrap_or(&name).to_string() - }; - // A pattern used before a color of its art kept the library's color has its art linked to the - // document's own color of that name: when merging those colors reuses a pattern of the document - // that keeping them would add again, they merge. - if current.pattern(&pattern_of(&imported)).is_none() - && imported.renamed.iter().any(|r| r["kind"] == "swatch") - && super::patternlib::has_candidate(¤t, &doc, &name) - { - let mut merged = (*current).clone(); - let found = clip.import_into(&mut merged, &SwatchChoices::default(), false)?; - if current.pattern(&pattern_of(&found)).is_some() { - (choices, probe, imported) = (SwatchChoices::default(), merged, found); - } - } + let (choices, probe, imported) = super::patternlib::probe_import(¤t, &doc, &name, &clip)?; drop(current); - let target = pattern_of(&imported); + let target = super::patternlib::imported_name(&imported, &name); let paint = vectorcraft_doc::pattern::pattern_paint(&target); // A pattern the document holds without a swatch (an imported SVG's) gets one. let has_swatch = diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 84453f4268..28ec9a80af 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -85,22 +85,29 @@ pub fn swatch_source(w: &Swatch) -> Option<Arc<Document>> { library_doc(b.id).filter(|d| d.pattern(pattern).is_some()) } +/// Swatches as (the swatch's name in a library, its name in a document). +pub(crate) type SwatchNames = Vec<(String, String)>; + /// Add pattern `name` of library `lib` to `d` with the resources its art uses, as pasting art /// painted with it does: the same pattern there already is used, and a name another pattern or /// swatch has gets a number → the pattern's name in `d`, and the swatches the import added for -/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out. +/// the pattern's art: (the swatch's name in `lib`, its name in `d`), pattern swatches left out, +/// and the swatches `d` had that the art took under another name than its own, in the same form. /// A global or spot color whose name `d` gives another color comes in under a free name, as Add /// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors /// merge instead when that reuses a pattern of `d` that keeping them would add again -/// ([`merge_reuses`]). -pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, Vec<(String, String)>)> { +/// ([`probe_import`]). +pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> { let gathered = gather(lib, name); - let merge = !gathered.swatches.is_empty() - && has_candidate(d, lib, name) - && probe(d, &gathered, &SwatchChoices::add_all()).and_then(|with_add| merge_reuses(d, &gathered, name, &with_add)).is_some(); - let choices = if merge { SwatchChoices::default() } else { SwatchChoices::add_all() }; let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect(); - let imported = gathered.import_into(d, &choices, false)?; + // Without a color to merge or a pattern to reuse, the document is not copied. + let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) { + let (_, probed, imported) = probe_import(d, lib, name, &gathered)?; + *d = probed; + imported + } else { + gathered.import_into(d, &SwatchChoices::add_all(), false)? + }; let from = |to: &str| { let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str()); renamed.unwrap_or(to).to_string() @@ -110,7 +117,14 @@ pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(St .filter(|w| !had.contains(&w.name) && !matches!(w.paint, Paint::Pattern { .. })) .map(|w| (from(&w.name), w.name.clone())) .collect(); - Ok((imported_name(&imported, name), added)) + let reused = imported + .renamed + .iter() + .filter(|r| r["kind"] == "swatch") + .filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string()))) + .filter(|(_, to)| had.contains(to)) + .collect(); + Ok((imported_name(&imported, name), added, reused)) } /// Pattern `name` of `lib` with the resources its art uses, as an object painted with it is copied. @@ -119,8 +133,13 @@ fn gather(lib: &Document, name: &str) -> Clipboard { Clipboard::gather(lib, vec![user]) } +/// The names in `lib` of the swatches that pattern `name` of `lib` brings with its art. +pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::HashSet<String> { + gather(lib, name).swatches.into_iter().map(|w| w.name).collect() +} + /// The name pattern `name` has in the document `imported` went into. -fn imported_name(imported: &Imported, name: &str) -> String { +pub(crate) fn imported_name(imported: &Imported, name: &str) -> String { let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str()); renamed.unwrap_or(name).to_string() } @@ -128,8 +147,8 @@ fn imported_name(imported: &Imported, name: &str) -> String { /// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding /// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as /// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted -/// with, is imported into a copy of `d`, so that those resources are compared too, with the colors -/// of its art merged when [`merge_reuses`] says so. +/// with, is imported into a copy of `d` as [`probe_import`] does, so that those resources are +/// compared too. pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 @@ -148,11 +167,8 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio if !has_candidate(d, lib, name) { return None; } - let with_add = probe(d, &gathered, &SwatchChoices::add_all())?; - if with_add.added == 0 { - return Some(imported_name(&with_add, name)); - } - merge_reuses(d, &gathered, name, &with_add).filter(|m| m.added == 0).map(|m| imported_name(&m, name)) + let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?; + (imported.added == 0).then(|| imported_name(&imported, name)) } /// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name @@ -166,22 +182,25 @@ pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool { d.patterns.iter().any(|p| copy(&p.name) && p.art.len() == def.art.len() && bare(p) == bare(def)) } -/// What importing `gathered` into a copy of `d` with `choices` does. -fn probe(d: &Document, gathered: &Clipboard, choices: &SwatchChoices) -> Option<Imported> { - let mut probe = d.clone(); - gathered.import_into(&mut probe, choices, false).ok() -} - -/// When importing `gathered` (pattern `name`) into `d` with Add (`with_add`) adds the pattern again -/// because a global or spot color of its art comes in numbered, while merging those colors reuses a -/// pattern of `d`, what merging does. Such a pattern has its art linked to the document's own colors -/// of those names, as pasting with Merge, or adding it from a library before, leaves it. -fn merge_reuses(d: &Document, gathered: &Clipboard, name: &str, with_add: &Imported) -> Option<Imported> { +/// Import `gathered`, which paints with pattern `name` of `lib`, into a copy of `d` → the swatch +/// choices used, the copy and what the import did. A global or spot color whose name `d` gives +/// another color comes in under a free name (Add). Those colors merge instead when Add would add +/// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to +/// the document's own colors of those names, as pasting with Merge, or adding it from a library +/// before, leaves it. +pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> { let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some(); - if reused(with_add) || !with_add.renamed.iter().any(|r| r["kind"] == "swatch") { - return None; + let mut with_add = d.clone(); + let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?; + if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { + let mut merged = d.clone(); + if let Ok(found) = gathered.import_into(&mut merged, &SwatchChoices::default(), false) + && reused(&found) + { + return Ok((SwatchChoices::default(), merged, found)); + } } - probe(d, gathered, &SwatchChoices::default()).filter(reused) + Ok((SwatchChoices::add_all(), with_add, added)) } /// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index bf564bcede..40b20e5c3a 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"). A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint links to its color under the name that color has in the document. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1011,6 +1011,89 @@ fn free_in(taken: &mut HashSet<String>, base: &str) -> String { name } +/// [`free_in`] for a library swatch's copy: a numbered name also skips the names `reserved` says +/// the library's other swatches have, so that a later add finds the copy as this swatch's. +fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) -> bool) -> String { + let name = if taken.contains(base) { + (2..).map(|i| format!("{base} {i}")).find(|n| !taken.contains(n) && !reserved(n)).unwrap_or_else(|| base.to_string()) + } else { + base.to_string() + }; + taken.insert(name.clone()); + name +} + +/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors +/// under the names `links` gives them, for each whose colors `links` names now, in one pass over +/// the document's swatches. +fn settle(d: &mut vectorcraft_doc::Document, pending: &mut Vec<(String, &Swatch)>, links: &std::collections::HashMap<String, String>) { + let mut done: std::collections::HashMap<String, Paint> = std::collections::HashMap::new(); + pending.retain(|(name, w)| { + let all = all_linked(&w.paint, links); + if all { + done.insert(name.clone(), relinked(&w.paint, links)); + } + !all + }); + if !done.is_empty() { + for x in d.swatches_iter_mut() { + if let Some(paint) = done.get(&x.name) { + x.paint = paint.clone(); + } + } + } +} + +/// Whether paint `a` shows what paint `b` shows: the same color, or the same gradient with the +/// colors its stops show, whichever swatches those colors link to. +fn shows(a: &Paint, b: &Paint) -> bool { + let unlinked = |p: &Paint| match p { + Paint::Gradient(g) => { + let mut g = g.clone(); + g.swatch = None; + g.gradient.stops.iter_mut().for_each(|s| s.swatch = None); + Paint::Gradient(g) + } + other => other.clone(), + }; + match (a.color(), b.color()) { + (Some(x), Some(y)) => x == y, + _ => unlinked(a) == unlinked(b), + } +} + +/// The names of the swatches the colors of paint `p` link to: a tint's base color, or the colors +/// of a gradient's stops. +fn linked_names(p: &Paint) -> Vec<&str> { + match p { + Paint::Solid { swatch: Some(b), .. } => vec![b.as_str()], + Paint::Gradient(g) => g.gradient.stops.iter().filter_map(|s| s.swatch.as_deref()).collect(), + _ => vec![], + } +} + +/// Paint `p` with each link to a swatch that `links` names changed to the name it maps to. +fn relinked(p: &Paint, links: &std::collections::HashMap<String, String>) -> Paint { + let mut out = p.clone(); + let swap = |name: &mut String| { + if let Some(to) = links.get(name.as_str()) { + *name = to.clone(); + } + }; + match &mut out { + Paint::Solid { swatch: Some(b), .. } => swap(b), + Paint::Gradient(g) => g.gradient.stops.iter_mut().filter_map(|s| s.swatch.as_mut()).for_each(swap), + _ => {} + } + out +} + +/// Whether `links` names every swatch the colors of paint `p` link to, the built-in Registration +/// swatch aside (every document has it under its own name). +fn all_linked(p: &Paint, links: &std::collections::HashMap<String, String>) -> bool { + linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n)) +} + fn add(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "swatch.library.add"; let (info, lib) = library_param(s, p, C)?; @@ -1042,42 +1125,69 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { copies.entry(base).or_default().push(w); } } - // A numbered copy whose name a picked library swatch has stands for that swatch alone. - let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); - // `paint` is `w`'s paint with a tint's base color under the name the base has in the document. - let there = |w: &Swatch, paint: &Paint| match (&w.paint, &patterns) { + // The library's swatches by name (the first of a name wins), looked up once. + let mut lib_by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); + for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) { + lib_by_name.entry(w.name.as_str()).or_insert(w); + } + let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect(); + // A color whose name the document gives another color, or a color group, is the numbered copy + // of it that an earlier add or a pattern's art brought in, when that copy is the same color. A + // numbered copy whose name the library gives a swatch of the same paint stands for that swatch + // alone, as adding that swatch finds it under its own name. Paints are compared with their + // colors linked as `links` says ([`relinked`]). + let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot; + let numbered = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap<String, String>| { + let c = copies.get(w.name.as_str())?; + let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint); + let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w)); + found.map(|x| x.name.clone()) + }; + let unlinked = std::collections::HashMap::new(); + // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. + let there = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap<String, String>| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } _ => match by_name.get(w.name.as_str()) { Some(x) if x.paint == *paint => Some(w.name.clone()), - // A color whose name the document gives another color is the numbered copy of it that - // an earlier add or a pattern's art brought in, when that copy is the same color. - Some(_) => copies - .get(w.name.as_str()) - .and_then(|c| { - c.iter().find(|x| !picked_names.contains(x.name.as_str()) && x.paint == *paint && x.global == w.global && x.spot == w.spot) - }) - .map(|x| x.name.clone()), + Some(_) => numbered(w, paint, links), + None if group_names.contains(w.name.as_str()) => numbered(w, paint, links), None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), }, }; + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // The global or spot color of the document that library color `b` is: its own name, or the + // numbered copy of it that adding `b` would find. While no color or color group has its name, + // a numbered copy is looked for only when this call does not add `b` under its own name. + let base_in_doc = |b: &Swatch| match by_name.get(b.name.as_str()) { + Some(x) if x.paint == b.paint && same_kind(x, b) => Some(b.name.clone()), + Some(_) => numbered(b, &b.paint, &unlinked), + None if group_names.contains(b.name.as_str()) || !picked_names.contains(b.name.as_str()) => numbered(b, &b.paint, &unlinked), + None => None, + }; + // The library's global and spot colors that the picked tints and gradients link to, with the + // name each has in the document: library name → document name. Each is looked up for itself, + // whether or not this call picks it, once. + let mut base_names: std::collections::HashMap<String, String> = std::collections::HashMap::new(); + let mut looked_up: HashSet<&str> = HashSet::new(); + for (_, w) in &picked { + for base in linked_names(&w.paint) { + if !looked_up.insert(base) { + continue; + } + if let Some(n) = lib_by_name.get(base).filter(|b| b.global || b.spot).and_then(|b| base_in_doc(b)) { + base_names.insert(base.to_string(), n); + } + } + } // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; let mut fresh = vec![]; for &(group, w) in &picked { - // A tint of a color the document has under a numbered name is compared linked to that name. - let relinked = match &w.paint { - Paint::Solid { swatch: Some(base), .. } => existing.iter().find(|(l, n)| l == base && n != base).map(|(_, n)| { - let mut paint = w.paint.clone(); - if let Paint::Solid { swatch: Some(b), .. } = &mut paint { - *b = n.clone(); - } - paint - }), - _ => None, - }; - match there(w, relinked.as_ref().unwrap_or(&w.paint)) { + // A tint or gradient is compared with its colors linked to the names they have here. + let paint = relinked(&w.paint, &base_names); + match there(w, &paint, &base_names) { Some(name) => existing.push((w.name.clone(), name)), None => fresh.push((group, w)), } @@ -1087,8 +1197,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // library swatch of this call stands for are added too; they are listed after the others and // are never the one `apply` paints with. let mut brought_alone: Vec<(String, String)> = vec![]; - // Library name → the name of the document's swatch for it, for the tints added here. - let mut links: std::collections::HashMap<String, String> = existing.iter().cloned().collect(); + // Library name → the name of the document's global or spot color for it, which the tints and + // gradients added here link to: one that is global or spot as the library color is. + let base_of = |l: &str, n: &str| { + let (Some(w), Some(x)) = (lib_by_name.get(l), by_name.get(n)) else { return false }; + (x.global || x.spot) && same_kind(x, w) + }; + let mut links: std::collections::HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); + links.extend(base_names); let added: Vec<(String, String)> = if fresh.is_empty() { vec![] } else { @@ -1104,13 +1220,40 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // The swatches the patterns imported in this call brought with their art: (library // name, document name). let mut brought: Vec<(String, String)> = vec![]; + // The swatches added here with a link `links` did not name yet: (document name, library + // swatch). + let mut pending: Vec<(String, &Swatch)> = vec![]; for (group, w) in fresh { let (name, sw) = if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { // The pattern comes with its swatch; a pattern the document has without one // gets one. The swatch a pattern that comes in brings is named after the pattern: // it takes the library swatch's name and color group instead. + // The tints and gradients added so far link to their colors first, so that the + // pattern's art finds them. A color they wait for that the pattern's art brings + // is named by importing the pattern into a copy first. + let brings = if pending.is_empty() { Default::default() } else { patternlib::brought_names(src, pattern) }; + let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n); + if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { + let mut probe = d.clone(); + let (_, colors, took) = patternlib::import(&mut probe, src, pattern)?; + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + if probe.swatch(to).is_some_and(|x| x.global || x.spot) { + links.entry(from.clone()).or_insert_with(|| to.clone()); + } + } + } + settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors) = patternlib::import(d, src, pattern)?; + let (target, colors, took) = patternlib::import(d, src, pattern)?; + // A global or spot color the pattern brought, or took from the document under + // a numbered name, is the one the library's tints of it link to, unless the + // document already has one for it. A color this call picks is added under + // its own name instead of the one the pattern took. + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + if d.swatch(to).is_some_and(|x| x.global || x.spot) { + links.entry(from.clone()).or_insert_with(|| to.clone()); + } + } brought.extend(colors); if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { reused.push((w.name.clone(), name)); @@ -1137,9 +1280,20 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } else { // A color a pattern added earlier in this call brought with its art is that // swatch when it shows the library swatch's color: it moves to the library - // swatch's place. - let same = - |to: &str| d.swatch(to).is_some_and(|x| x.paint.color() == w.paint.color() && x.global == w.global && x.spot == w.spot); + // swatch's place, when its colors link where the library swatch's do: to the + // names `links` gives them, and not elsewhere for a color this call has yet to + // add. + let fits = |x: &Paint| { + let (ours, theirs) = (linked_names(&w.paint), linked_names(x)); + ours.len() == theirs.len() + && ours.iter().zip(&theirs).all(|(l, t)| match links.get(*l) { + Some(to) => to == t, + None => !picked_names.contains(l), + }) + }; + let same = |to: &str| { + d.swatch(to).is_some_and(|x| shows(&x.paint, &w.paint) && x.global == w.global && x.spot == w.spot && fits(&x.paint)) + }; let at = brought.iter().position(|(from, to)| *from == w.name && same(to)); let moved = at.map(|i| brought.swap_remove(i).1).and_then(|n| { let i = d.swatches.iter().position(|x| x.name == n)?; @@ -1148,20 +1302,23 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { match moved { Some(sw) => (sw.name.clone(), sw), None => { - let name = free_in(&mut taken, &w.name); - let mut sw = Swatch { name: name.clone(), ..(*w).clone() }; - // A tint links to its base color under the name the base has in the - // document. - if let Paint::Solid { swatch: Some(base), .. } = &mut sw.paint - && let Some(to) = links.get(base.as_str()) - { - *base = to.clone(); + // A numbered copy skips the names of the library's other swatches, + // which a later add looks up as theirs. + let name = free_copy_in(&mut taken, &w.name, |n| lib_by_name.contains_key(n)); + // A tint or gradient links to its colors under the names they have in + // the document; a color that comes in later in this call is linked + // when it has come in. + let paint = relinked(&w.paint, &links); + if !all_linked(&w.paint, &links) { + pending.push((name.clone(), w)); } - (name, sw) + (name.clone(), Swatch { name, paint, ..(*w).clone() }) } } }; - links.insert(w.name.clone(), name.clone()); + if sw.global || sw.spot { + links.insert(w.name.clone(), name.clone()); + } match group { Some(g) => { let found = placed.iter().find(|(n, _)| *n == g).map(|&(_, i)| i); @@ -1182,6 +1339,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } out.push((w.name.clone(), name)); } + let later: std::collections::HashMap<String, Paint> = pending.into_iter().map(|(name, w)| (name, relinked(&w.paint, &links))).collect(); + if !later.is_empty() { + for x in d.swatches_iter_mut() { + if let Some(paint) = later.get(&x.name) { + x.paint = paint.clone(); + } + } + } Ok((out, reused, brought)) })?; existing.extend(reused); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index da044f78e6..875d9b5e28 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -660,6 +660,153 @@ fn a_library_tint_follows_its_color_to_its_numbered_name() { assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 2", "Ink half"])), "{again}"); } +/// A library tint picked before its global color still follows the color to its numbered name. +#[test] +fn a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]})); + assert_eq!(r["added"], json!(["Ink half", "Ink 2"]), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Ink"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half", "Ink 2"])), "{again}"); +} + +/// A library tint added without its global color finds the numbered copy an earlier add brought. +#[test] +fn a_library_tint_added_alone_finds_its_colors_numbered_copy() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(r["added"], json!(["Ink half"]), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}"); +} + +/// A library tint added alone links to the numbered copy of its own color, not to another library +/// color's copy of the same paint. +#[test] +fn a_library_tint_added_alone_skips_another_library_colors_copy() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 3"]), "{r}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 3"), "{r}"); +} + +/// A library tint added alone finds its color's numbered copy when a color group of the document +/// has the color's name. +#[test] +fn a_library_tint_finds_its_colors_copy_beside_a_group_of_its_name() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + run(&mut s, "swatch.newGroup", json!({"name": "Ink", "colors": ["#123456"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{r}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); +} + +/// A library pattern whose art uses a tint of a library color added earlier in the same call +/// does not bring a second copy of that tint, also when the call does not pick the color. +#[test] +fn a_pattern_after_its_tint_in_one_call_does_not_copy_the_tint() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": 50, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + for names in [json!(["Ink", "Ink half", "Squares"]), json!(["Ink half", "Ink", "Squares"]), json!(["Ink half", "Squares"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}"); + } +} + +/// A library color added under a numbered name skips the names of the library's other swatches, +/// so adding it again finds that copy. +#[test] +fn a_library_colors_copy_skips_the_librarys_other_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!(r["added"], json!(["Ink 3"]), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink 3"])), "{again}"); +} + +/// A library tint links to a global color even when the document has a process color of the same +/// name and paint, which the picked library color matches: the pattern's art brings the global one. +#[test] +fn a_library_tint_links_to_the_global_color_a_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink", "Ink half", "Tiles"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.global), "{names}: {r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}"); + } +} + +/// A library tint added with a pattern whose art brought the tint's global color under a numbered +/// name is a tint of that numbered color. +#[test] +fn a_library_tint_follows_the_color_a_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Ink 2"))), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{r}"); +} + /// A numbered copy of a color's name that the library also has as a swatch of its own stands for /// that swatch alone, even when both library swatches have its color. #[test] @@ -676,6 +823,237 @@ fn a_numbered_copy_the_library_also_names_is_not_shared() { assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}"); } +/// A numbered copy of a color's name that the library also has as a swatch of another color is +/// still the copy of the color: adding the color after a pattern brought it under that name adds +/// no other copy. +#[test] +fn a_numbered_copy_named_like_another_library_color_is_found() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{r}"); +} + +/// A library tint picked before its global color links to the color under the name it comes in +/// with, not to a numbered copy of the same color when the document has none of the color's name. +#[test] +fn a_library_tint_links_to_its_color_under_the_name_it_comes_in_with() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + for names in [json!(["Ink half", "Ink"]), json!(["Ink", "Ink half"])] { + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{names}: {r}"); + run(&mut s, "swatch.delete", json!({"names": ["Ink half", "Ink"]})); + } +} + +/// A library tint of a spot color links to the spot color a pattern's art brought, not to the +/// document's global process color of the same name and paint. +#[test] +fn a_library_spot_tint_links_to_the_spot_color_not_a_process_one() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + for names in [json!(["Ink", "Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}"); + } +} + +/// A numbered copy that the library's own swatch of that name is (the same paint, whatever its +/// kind) is not also taken for the library color it is numbered after. +#[test] +fn a_numbered_copy_the_library_has_by_paint_is_not_shared() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff"})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}"); +} + +/// A library tint added with a pattern whose art took the document's numbered copy of the tint's +/// color is a tint of that copy. +#[test] +fn a_library_tint_follows_the_numbered_color_a_pattern_took() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + for names in [json!(["Tiles", "Ink half"]), json!(["Ink half", "Tiles"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink"), ["Ink 2"], "{names}: {r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{names}: {r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{names}: {again}"); + } +} + +/// A numbered copy that the library's own tint of that name is, once its color is linked as the +/// document has it, is not also taken for the library tint it is numbered after. +#[test] +fn a_numbered_tint_the_library_has_is_not_shared() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.new", json!({"name": "Half 2", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Half", "color": "#00ff00"})); + run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Half 2"]})); + assert_eq!(tint_base(&s, "Half 2").as_deref(), Some("Ink 2")); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Half", "Half 2"]})); + assert_eq!(r["existing"], json!(["Half 2"]), "{r}"); + assert_eq!(r["added"].as_array().map(Vec::len), Some(1), "{r}"); +} + +/// Adding a library color the document has as a process color of the same paint, with its tint, +/// again adds no other copy of the tint. +#[test] +fn a_library_tint_of_a_color_the_document_has_as_process_is_added_once() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + let before = named_after(&s, "Ink half"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!(named_after(&s, "Ink half"), before, "{r} then {again}"); +} + +/// A library tint added with a pattern the document already has (pasted with Merge, so it brings +/// no colors), through the pattern's own swatch or another library swatch of it, is added once, +/// however often the two are added. +#[test] +fn a_library_tint_with_a_pattern_the_document_has_is_added_once() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Dots", |d, _| { + let paint = vectorcraft_doc::pattern::pattern_paint("Squares"); + d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink half"]})); + let before = named_after(&s, "Ink half"); + for pattern in ["Squares", "Dots"] { + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": [pattern, "Ink half"]})); + assert_eq!(named_after(&s, "Ink half"), before, "{pattern}: {first} then {again}"); + } +} + +/// A library gradient whose stops link to a color and to the Registration swatch, picked before a +/// pattern whose art brings the color under a numbered name, is not added a second time. +#[test] +fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "swatch": "[Registration]"}]}); + run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Fade", "Squares"]})); + assert_eq!(named_after(&s, "Fade"), ["Fade"], "{r}"); +} + +/// A library tint follows its color when the call picks the color, even when a pattern added +/// before it took the document's numbered copy of that color, with the color itself or with the +/// tint in its art. +#[test] +fn a_library_tint_follows_its_picked_color_not_the_copy_a_pattern_took() { + for tint in [100, 50] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "tint": tint, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let names = json!(["Tiles", "Ink half", "Ink"]); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let picked = r["added"].as_array().and_then(|a| a.iter().find(|n| n.as_str().is_some_and(|n| n.starts_with("Ink half"))).cloned()); + let picked = picked.and_then(|n| n.as_str().map(str::to_string)).unwrap_or_default(); + assert_eq!(tint_base(&s, &picked).as_deref(), Some("Ink"), "tint {tint}: {r}"); + let before = named_after(&s, "Ink half"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Ink half"), before, "tint {tint}: {again}"); + } +} + /// A library tint is not taken for the tint a pattern brought back in the library color's place /// when that tint shows the document's own color (the pattern's art links to it, as pasting with /// Merge leaves it): it comes in as a tint of the library color's numbered copy. @@ -708,6 +1086,46 @@ fn a_library_tint_is_not_the_one_a_merged_pattern_brought() { assert_eq!(tint_base(&s, &tint).as_deref(), Some("Ink 2"), "{r}"); } +/// A library gradient is not taken for the gradient a pattern brought back in its place when that +/// gradient's stops show the document's own color. +#[test] +fn a_library_gradient_is_not_the_one_a_merged_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let fade = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}); + run(&mut s, "swatch.new", json!({"name": "Fade", "gradient": fade})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Fade", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Squares", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + run(&mut s, "swatch.delete", json!({"names": ["Fade"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Squares", "Ink", "Fade"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); + let fade = r["added"][1].as_str().unwrap_or_default().to_string(); + assert!(fade.starts_with("Fade"), "{r}"); + let (first, link) = match doc(&s).swatch(&fade).map(|w| &w.paint) { + Some(Paint::Gradient(g)) => (g.gradient.stops.first().map(|stop| stop.color), g.gradient.stops.first().and_then(|stop| stop.swatch.clone())), + _ => (None, None), + }; + assert_eq!(link.as_deref(), Some("Ink 2"), "the stop links to the library's color: {r}"); + let blue = match doc(&s).swatch("Ink 2").map(|w| &w.paint) { + Some(Paint::Solid { color, .. }) => Some(*color), + _ => None, + }; + assert!(blue.is_some() && first == blue, "{r}"); +} + #[test] fn swatch_exchange_files_load_add_and_list_as_user_libraries() { let bytes = vectorcraft_testkit::ase::sample(); diff --git a/docs/mcp.md b/docs/mcp.md index bddbbe38e8..af535e4ff7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5805,7 +5805,9 @@ color the pattern's art links to keeps the library's color: when the document gi in under a numbered name ("Ink 2") and the pattern links to that. A library color whose name the document gives another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name -is used as it is. `added` lists the colors the pattern's art brings too. A document with +is used as it is. A library tint or gradient links to its colors under the names those colors have in the document, +whether a color is picked before or after it, was added earlier or came with a pattern's art. `added` lists the colors +the pattern's art brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`<file>` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. @@ -6022,8 +6024,7 @@ fill or stroke with it, as one undo step, and returns the pattern's name in the color the pattern's art links to keeps the item's color, as with `swatch.library.add`: when the document gives its name another color, it comes in under a numbered name ("Ink 2"), or as the document's numbered copy of the same color, and the pattern links to it. A pattern the document holds with its art linked to the document's own color of that name is -reused. `library.get` -lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`. +reused. `library.get` lists them as `gradients: [{name, gradient}]` and `patterns: [{name, pattern, thumbnail}]`. Items can be put in user-named groups, which the panel shows as collapsible sections after the ungrouped items (its search field filters every item by name; `library.get` lists them all to filter). `library.createGroup {library?, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..3965f265bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). A global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name, and adding it again uses that numbered copy; a library tint links to it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 3f243e90f83fce176d2e6e43a57748b84fa4de8b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 05:13:35 -0800 Subject: [PATCH 103/126] Tests: an unreadable Annex B folder fails the test262 runner The Annex B runners checked their folders with Path::exists, which returns false when the metadata cannot be read, so a folder that could not be searched skipped the tests as if it were absent. They now use try_exists: only an absent folder skips, and a metadata error fails the test. The parity doc now says that an interpreter panic fails annex_b_runs and makes cargo xtask test262 exit non-zero, while conformance failures do not. --- crates/js/tests/test262.rs | 35 +++++++++++++++++++++++++++-------- docs/target-app-parity.md | 2 +- 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 8ae4d36f6a..c94451a772 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -93,6 +93,17 @@ fn inside(dir: &Path, rel: &str) -> Result<PathBuf, String> { Ok(path) } +/// `dir` joined with `rel` as [`inside`] gives it, or `None` when nothing is at that path. A path +/// whose metadata cannot be read, such as one under a folder that cannot be searched, gives an error. +fn present(dir: &Path, rel: &str) -> Result<Option<PathBuf>, String> { + let path = inside(dir, rel)?; + match path.try_exists() { + Ok(true) => Ok(Some(path)), + Ok(false) => Ok(None), + Err(e) => Err(format!("cannot read {}: {e}", path.display())), + } +} + /// Reads a test or harness file: a regular file (not a symbolic link) of at most /// [`MAX_FILE_BYTES`], with invalid UTF-8 replaced. fn read_source(path: &Path) -> Result<String, String> { @@ -229,11 +240,10 @@ fn annex_b_parse_subset() { println!("test262 Annex B parse: SKIPPED (no suite; run cargo xtask test262)"); return; }; - let language = or_fail(inside(&dir, "test/annexB/language")); - if !language.exists() { + let Some(language) = or_fail(present(&dir, "test/annexB/language")) else { println!("test262 Annex B parse: SKIPPED ({} has no test/annexB/language)", dir.display()); return; - } + }; let files = or_fail(test_files(&language)); let ParseRun { main, with_features, modules, .. } = or_fail(parse_files(&dir, &files, true)); assert!(main.positive + main.negative > 0, "no Annex B tests to parse under {}", language.display()); @@ -636,19 +646,17 @@ fn annex_b_runs() { /// [`ANNEX_B_BUILT_INS`] names, of any edition, prints the counts of each and writes the failures /// to `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. fn run_annex_b(dir: &Path) { - let annex_b = or_fail(inside(dir, "test/annexB")); - if !annex_b.exists() { + if or_fail(present(dir, "test/annexB")).is_none() { println!("test262 Annex B interpreter: SKIPPED ({} has no test/annexB)", dir.display()); return; } let mut panicked = 0; let mut built_ins_report = String::new(); for folder in std::iter::once(&ANNEX_B_LANGUAGE).chain(ANNEX_B_BUILT_INS) { - let root = or_fail(inside(dir, &format!("test/{folder}"))); - if !root.exists() { + let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { println!("test262 {folder}: SKIPPED (not in this suite)"); continue; - } + }; let missing = if folder.ends_with("/String") { missing_builtins(&[TEXT_BUILTINS, STRING_METHODS_SHARED_WITH_ARRAY]) } else { @@ -845,6 +853,17 @@ fn harness_names_stay_inside_the_suite() { } } +#[test] +fn an_unreadable_annex_b_folder_fails_and_only_an_absent_one_skips() { + let dir = scratch("present"); + std::fs::create_dir_all(dir.join("test/annexB")).unwrap(); + assert_eq!(present(&dir, "test/annexB"), Ok(Some(dir.join("test").join("annexB")))); + assert_eq!(present(&dir, "test/annexB/language"), Ok(None)); + // A NUL byte in the path makes its metadata unreadable on every platform. + assert!(present(Path::new("suite\0dir"), "test/annexB").is_err(), "a path whose metadata cannot be read is skipped as absent"); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn a_file_over_the_limit_is_refused_before_it_is_read() { let dir = scratch("size"); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4ac30a925d..7d08b30b56 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1077,7 +1077,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite and do not fail the tests. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. + - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `<!DOCTYPE>` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. From bd752e95ade0be5f861eda9c98298636e64df4d4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 05:17:25 -0800 Subject: [PATCH 104/126] Tests: an Annex B folder whose tests are all skipped fails annex_b_runs counted skipped tests toward its check that a folder has tests to run, so a folder where every test needs a missing built-in or is asynchronous passed without running anything. It now requires at least one test to run, as the ES5 groups do. --- crates/js/tests/test262.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index c94451a772..639b024776 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -666,7 +666,7 @@ fn run_annex_b(dir: &Path) { let mut counts = RunCounts::default(); counts.add(es5); counts.add(later); - assert!(counts.tests + counts.skipped > 0, "no Annex B tests to run under {}", root.display()); + assert!(counts.tests > 0, "no Annex B tests ran under {}", root.display()); panicked += counts.panicked; println!("test262 {folder} through the interpreter: {}.", counts.summary()); if *folder == ANNEX_B_LANGUAGE { @@ -864,6 +864,19 @@ fn an_unreadable_annex_b_folder_fails_and_only_an_absent_one_skips() { std::fs::remove_dir_all(&dir).unwrap(); } +#[test] +fn an_annex_b_folder_whose_tests_are_all_skipped_fails() { + let dir = scratch("all-skipped"); + std::fs::create_dir_all(dir.join("harness")).unwrap(); + std::fs::create_dir_all(dir.join("test/annexB/language")).unwrap(); + std::fs::write(dir.join("harness/assert.js"), "").unwrap(); + std::fs::write(dir.join("harness/sta.js"), "").unwrap(); + std::fs::write(dir.join("test/annexB/language/a.js"), "/*---\nesid: sec-x\nflags: [async]\n---*/\n").unwrap(); + let outcome = std::panic::catch_unwind(|| run_annex_b(&dir)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(outcome.is_err(), "a folder where every test is skipped passes"); +} + #[test] fn a_file_over_the_limit_is_refused_before_it_is_read() { let dir = scratch("size"); From 4ed3826e3bbe6244b96b3371e7b782ece0df7465 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 05:21:17 -0800 Subject: [PATCH 105/126] Tests: an Annex B tree without its language folder fails A suite with test/annexB but no test/annexB/language skipped the Annex B parse test and the language group of annex_b_runs. Both now skip only when test/annexB is absent, and fail when it is present without its language folder. The Annex B built-ins folders still skip one by one. --- crates/js/tests/test262.rs | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 639b024776..23337128bb 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -240,12 +240,20 @@ fn annex_b_parse_subset() { println!("test262 Annex B parse: SKIPPED (no suite; run cargo xtask test262)"); return; }; - let Some(language) = or_fail(present(&dir, "test/annexB/language")) else { - println!("test262 Annex B parse: SKIPPED ({} has no test/annexB/language)", dir.display()); + parse_annex_b(&dir); +} + +/// Parses the tests without a feature tag under `test/annexB/language`, of any edition, prints the +/// counts and writes the failures to `annexb-parse-failures.txt` beside the suite. +fn parse_annex_b(dir: &Path) { + if or_fail(present(dir, "test/annexB")).is_none() { + println!("test262 Annex B parse: SKIPPED ({} has no test/annexB)", dir.display()); return; - }; + } + // A suite with `test/annexB` and no `test/annexB/language` fails in the walk. + let language = or_fail(inside(dir, "test/annexB/language")); let files = or_fail(test_files(&language)); - let ParseRun { main, with_features, modules, .. } = or_fail(parse_files(&dir, &files, true)); + let ParseRun { main, with_features, modules, .. } = or_fail(parse_files(dir, &files, true)); assert!(main.positive + main.negative > 0, "no Annex B tests to parse under {}", language.display()); let report = dir.join("annexb-parse-failures.txt"); if let Err(e) = std::fs::write(&report, &main.failures) { @@ -654,6 +662,7 @@ fn run_annex_b(dir: &Path) { let mut built_ins_report = String::new(); for folder in std::iter::once(&ANNEX_B_LANGUAGE).chain(ANNEX_B_BUILT_INS) { let Some(root) = or_fail(present(dir, &format!("test/{folder}"))) else { + assert!(*folder != ANNEX_B_LANGUAGE, "{} has test/annexB but no test/{folder}", dir.display()); println!("test262 {folder}: SKIPPED (not in this suite)"); continue; }; @@ -877,6 +886,20 @@ fn an_annex_b_folder_whose_tests_are_all_skipped_fails() { assert!(outcome.is_err(), "a folder where every test is skipped passes"); } +#[test] +fn an_annex_b_tree_without_its_language_folder_fails() { + let dir = scratch("no-language"); + std::fs::create_dir_all(dir.join("harness")).unwrap(); + std::fs::create_dir_all(dir.join("test/annexB/built-ins")).unwrap(); + std::fs::write(dir.join("harness/assert.js"), "").unwrap(); + std::fs::write(dir.join("harness/sta.js"), "").unwrap(); + let parsed = std::panic::catch_unwind(|| parse_annex_b(&dir)); + let ran = std::panic::catch_unwind(|| run_annex_b(&dir)); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(parsed.is_err(), "the parse test skips a suite without test/annexB/language"); + assert!(ran.is_err(), "the interpreter test skips a suite without test/annexB/language"); +} + #[test] fn a_file_over_the_limit_is_refused_before_it_is_read() { let dir = scratch("size"); From aecf4b12846a6eff063a479add90abc6fdb15be2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 04:03:36 -0800 Subject: [PATCH 106/126] PSD import: keep adjustment layers pending over layers that draw nothing - A hidden pass-through group, kept with the hidden layers, and an adjustment layer at 0 opacity or 0 fill no longer hold back the adjustment layers above them in a pass-through group. - Layers that draw nothing (no pixels stored, 0 opacity, or 0 fill with nothing clipped to them) and groups of only such layers don't count as content below an adjustment layer, so in a pass-through group it still changes what is below the group. Layers clipped to a layer at 0 fill or to an adjustment layer count as content. - An adjustment layer whose layer mask is too large for the memory allowed is counted as not applied, merged or clipped, instead of stopping the layered import. --- crates/engine/src/cmd/fileio/psdlayers.rs | 168 ++++++++++++---- .../engine/src/cmd/fileio/tests_psdlayers.rs | 184 ++++++++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 4 files changed, 318 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 5f3c0a6b01..5fc6916c5e 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -45,7 +45,9 @@ //! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher //! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, //! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One -//! with nothing visible below it in its group changes nothing; in a pass-through group it changes +//! with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 +//! opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) +//! changes nothing; in a pass-through group it changes //! what is below the group when the group is merged, and otherwise isn't applied. One that layers //! are clipped to, and one clipped to another adjustment layer, isn't applied. //! @@ -54,7 +56,7 @@ //! whose fill isn't read or whose shape is a vector mask, layer effects that are switched on, vector //! masks, and the knockouts of top-level layers, of clipped layers, of layers that others are clipped //! to and of layers in a pass-through group with a layer in another mode, and other Knockout values, -//! and adjustments whose merge needs more memory than allowed aren't applied; the warnings count them +//! and adjustments whose merge, their layer mask included, needs more memory than allowed aren't applied; the warnings count them //! and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, @@ -487,6 +489,12 @@ impl Record<'_> { } } + /// Does the layer draw nothing (an adjustment layer, or one that stores no pixels and isn't a + /// fill drawn from its color over the canvas; see [`Builder::image`])? + fn draws_nothing(&self) -> bool { + self.covers_without_drawing() || (self.stores_nothing() && !self.color_over_canvas()) + } + /// Is the layer a fill that stores no pixels and whose shape is a vector mask, so that it /// isn't drawn? fn undrawn_shape(&self) -> bool { @@ -1089,6 +1097,22 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Ok(Some((i64::from(m.bounds.left), i64::from(m.bounds.top), img, read(m.default)))) } + /// Does record `i`'s layer mask, switched on, fit the memory allowed for reading it with + /// [`Self::mask`]? `true` when it has none, and when its size is damaged (reading it says so). + fn mask_fits(&self, i: usize) -> Result<bool, String> { + let rec = self.record(i)?; + let Some(m) = rec.mask.filter(|m| !m.disabled) else { return Ok(true) }; + if !rec.channels.iter().any(|(c, _)| *c == -2) { + return Ok(true); + } + let (w, rows) = m.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + if w > max_side || rows > max_side { + return Ok(true); + } + Ok(self.fits((row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64)).is_ok()) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1205,6 +1229,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } // A clipped adjustment layer changes the merged canvas in place, through its layer mask. let adjust = self.adjustment(body)?; + // Its layer mask too large to read needs more memory than allowed. + if adjust.is_some() && !base_adjustment && !self.mask_fits(i)? { + return Ok(false); + } let layer = match adjust { Some(_) => Canvas::default(), None => match self.draw_body(body, Some(i))? { @@ -1433,13 +1461,15 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to - /// change what is below the group), those kept in the pass-through groups of `out` included. + /// change what is below the group), those kept in the visible pass-through groups of `out` + /// included. fn pending(&self, out: &[Unit<'_>], level: Level) -> Result<Vec<usize>, String> { let mut records = vec![]; if level != Level::Pass { return Ok(records); } - for u in out { + // A hidden unit, kept with the hidden layers, or one at 0 opacity, changes nothing. + for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { if self.adjustment(&u.body)?.is_some() { records.push(u.record); } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) { @@ -1451,44 +1481,98 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { /// The adjustment layers the import applies that a pass-through group with the layers `items` /// keeps to change what is below it: from the first one with nothing that draws below it in the - /// group (hidden and clipped layers, other adjustment layers and fills that draw nothing aren't - /// counted), it and every one above it, in the pass-through groups inside it too. Also whether - /// anything in `items` draws. + /// group (hidden and clipped layers, other adjustment layers, layers and groups at 0 opacity, and + /// layers and groups that draw nothing aren't counted), it and every one above it, in the + /// pass-through groups inside it too; one at 0 opacity isn't kept. Also whether anything in + /// `items` draws. fn leading(&self, items: &[Item]) -> Result<(Vec<usize>, bool), String> { let (mut records, mut draws) = (vec![], false); - for item in items { - match item { - Item::Layer(i) => { - let r = self.record(*i)?; - if r.hidden || r.clipped { - continue; - } - if r.adjust().is_some() { - if !draws || !records.is_empty() { - records.push(*i); - } - } else if !r.covers_without_drawing() { - draws = true; + for (k, item) in items.iter().enumerate() { + let (i, r, children) = match item { + Item::Layer(i) => (*i, self.record(*i)?, None), + Item::Group(g, children) => (*g, self.record(*g)?, Some(children)), + }; + // A clipped one draws as part of the one it is clipped to. + if r.hidden || r.clipped { + continue; + } + let (clips, drawn) = self.base_draws(items, k)?; + // One that layers are clipped to isn't kept, and a pass-through group they are clipped to + // is drawn alone (see `clip`). One at 0 opacity changes nothing (see `adjust_below`). + let keeps = !clips && r.opacity * r.fill > 0.0 && (!draws || !records.is_empty()); + match children { + None if r.adjust().is_some() && !clips => { + if keeps { + records.push(i); } } - Item::Group(g, children) => { - let r = self.record(*g)?; - if r.hidden { - continue; - } - if r.blend == Blend::Pass && (!draws || !records.is_empty()) { - let (inner, inner_draws) = self.leading(children)?; - records.extend(inner); - draws |= inner_draws; - } else { - draws = true; - } + Some(children) if r.blend == Blend::Pass && keeps => { + let (inner, inner_draws) = self.leading(children)?; + records.extend(inner); + draws |= inner_draws; } + _ => draws |= drawn, } } Ok((records, draws)) } + /// Does anything in `items` draw: a visible layer or group that isn't clipped and draws (see + /// [`Self::base_draws`])? + fn draws(&self, items: &[Item]) -> Result<bool, String> { + for (k, item) in items.iter().enumerate() { + let r = match item { + Item::Layer(i) => self.record(*i)?, + Item::Group(g, _) => self.record(*g)?, + }; + if !r.hidden && !r.clipped && self.base_draws(items, k)?.1 { + return Ok(true); + } + } + Ok(false) + } + + /// For item `k` of `items`, visible and not clipped: whether visible layers are clipped to it, + /// and whether it draws, above 0 opacity: by its own pixels (a group's, those of its layers) + /// above 0 fill, or by those of the layers clipped to it that draw, which show in its pixels at + /// any fill, or over the canvas when it is a layer that covers it without drawing. + fn base_draws(&self, items: &[Item], k: usize) -> Result<(bool, bool), String> { + let Some(item) = items.get(k) else { return Ok((false, false)) }; + let (r, own) = self.pixels(item)?; + let covers = matches!(item, Item::Layer(_)) && r.covers_without_drawing(); + let (mut clips, mut clips_draw) = (false, false); + for above in items.get(k + 1..).unwrap_or_default() { + let c = match above { + Item::Layer(i) => self.record(*i)?, + Item::Group(g, _) => self.record(*g)?, + }; + if !c.clipped { + break; + } + if c.hidden { + continue; + } + clips = true; + if !clips_draw && c.opacity * c.fill > 0.0 { + clips_draw = self.pixels(above)?.1; + } + } + let drawn = (r.fill > 0.0 && own) || (clips_draw && (covers || own)); + Ok((clips, r.opacity > 0.0 && drawn)) + } + + /// `item`'s record, and whether it has pixels of its own: a layer that draws, or a group with + /// something in it that draws (see [`Self::draws`]). + fn pixels(&self, item: &Item) -> Result<(&Record<'_>, bool), String> { + Ok(match item { + Item::Layer(i) => { + let r = self.record(*i)?; + (r, !r.draws_nothing()) + } + Item::Group(g, children) => (self.record(*g)?, self.draws(children)?), + }) + } + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group /// the layers with a shallow knockout, merged with those below. fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result<Vec<Unit<'i>>, String> { @@ -1625,7 +1709,8 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { /// Adjustment layer `u` (one the import applies), at `level`, merged with the visible units /// `out` below it in its list: they become one layer, adjusted. A hidden one would need the /// merge and is left out. With nothing visible below it that draws (other adjustment layers and - /// fills that draw nothing don't count), or at 0 opacity, it changes nothing + /// layers and groups that draw nothing or are at 0 opacity don't count), or at 0 opacity, it + /// changes nothing /// and comes in as nothing, except in a pass-through group, where it is kept to change what is /// below the group when the group is drawn onto it; there, once one is kept (in the group or in /// a pass-through group in it), the ones above it are kept too, in order. One that layers are clipped to, and one whose merge needs more memory @@ -1645,12 +1730,15 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { return Ok(()); } let mut below = false; - for b in out.iter() { - match &b.body { - // An adjustment layer, or a fill that draws nothing, has nothing to change. - Body::Layer(i) if self.record(*i)?.covers_without_drawing() => {} - _ => below |= b.visible, - } + for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { + below |= match &b.body { + // An adjustment layer, a layer that draws nothing, or a group of such layers, has + // nothing to change. + Body::Layer(i) => !self.record(*i)?.draws_nothing(), + Body::Group(_, items) => self.draws(items)?, + // Clipped layers merged with a base that has no pixels have none either. + Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), + }; } // Kept below it in the group, or in a pass-through group below it there. let pending = !self.pending(out, level)?.is_empty(); @@ -1930,6 +2018,8 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { if let Some(a) = self.adjustment(&u.body)? { if let Some(c) = acc.as_mut() { let mask = match u.mask_of { + // A layer mask too large to read needs more memory than allowed. + Some(i) if !self.mask_fits(i)? => return Ok(false), Some(i) => self.mask(i, false)?, None => None, }; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 80d9fba25f..8ebc3a9f24 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1456,6 +1456,171 @@ fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); } +/// The layer of a pass-through group's sublayers whose name ends with `end`. +fn sublayer<'d>(folder: &'d Node, end: &str) -> &'d Node { + let children = folder.children().map(Vec::as_slice).unwrap_or_default(); + let names: Vec<&str> = children.iter().map(|c| name(c)).collect(); + children.iter().find(|c| name(c).ends_with(end)).unwrap_or_else(|| panic!("no sublayer ending with {end} in {names:?}")) +} + +/// An adjustment layer that changes nothing, in a hidden pass-through group or at 0 opacity or 0 +/// fill, keeps no adjustment layer above it in the group from merging with the layers below it: +/// the gray 100 posterizes to 85. +#[test] +fn adjustment_layers_that_change_nothing_hold_none_back() { + let invert = |opacity: u8, fill: u8| { + let mut l = L { opacity, ..adjustment("Invert", b"nvrt", &[]) }; + l.blocks.push((*b"iOpa", vec![fill])); + l + }; + let cases = [("hidden group", true, invert(255, 255)), ("0 opacity", false, invert(0, 255)), ("0 fill", false, invert(255, 0))]; + for (what, hidden, invert) in cases { + let layers = [ + group_end(), + group_end(), + invert, + L { hidden, ..group("Inner", b"pass") }, + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Folder"], "{what}: {r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Photo + Posterize")), [[85, 85, 85, 255]], "{what}: {r}"); + } +} + +/// A layer that stores no pixels draws nothing: an adjustment layer above it in a pass-through group, +/// directly or in a pass-through group inside it, still changes what is below the group. +#[test] +fn an_adjustment_layer_over_layers_that_draw_nothing_changes_what_is_below_the_group() { + let empty = || layer("Empty", [0, 0, 0, 0], [0; 4]); + let direct = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + empty(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); + // Inverted in the inner group, then posterized to 4 levels. + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + empty(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); + // Nor does a group of such layers, in any mode, or a layer at 0 opacity: below them, directly + // or in the inner group, Invert and Posterize still change what is below the outer group. + let mut no_fill = layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]); + no_fill.blocks.push((*b"iOpa", vec![0])); + let photo = || layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]); + let below: [(&str, Vec<L>); 5] = [ + ("empty group", vec![group_end(), empty(), group("Empty", b"norm")]), + ("empty pass-through group", vec![group_end(), empty(), group("Empty", b"pass")]), + ("0 opacity", vec![L { opacity: 0, ..layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]) }]), + ("0 fill in a group", vec![group_end(), no_fill, group("Empty", b"norm")]), + ("group clipped to an empty layer", vec![empty(), group_end(), photo(), L { clipped: true, ..group("Clipped", b"norm") }]), + ]; + for (what, nothing) in below { + let direct = [ + &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end()][..], + ¬hing, + &[adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }], + ] + .concat(); + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{what}: {r}"); + let nested = [ + &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), group_end()][..], + ¬hing, + &[ + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ], + ] + .concat(); + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{what}: {r}"); + } +} + +/// Layers clipped to a layer at 0 fill, or to an adjustment layer, draw: an adjustment layer above +/// them in a pass-through group merges with them and is applied. +#[test] +fn an_adjustment_layer_over_clipped_layers_merges_with_them() { + let mut clear = layer("Base", [0, 0, 1, 1], [0, 0, 0, 255]); + clear.blocks.push((*b"iOpa", vec![0])); + let photo = || L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) }; + let layers = [ + group_end(), + group_end(), + clear, + photo(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(r["warnings"], json!([merged]), "{r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}"); + // The same with a group at 0 fill as the base. + let mut clear_group = group("Base", b"norm"); + clear_group.blocks.push((*b"iOpa", vec![0])); + let layers = [ + group_end(), + group_end(), + group_end(), + layer("Black", [0, 0, 1, 1], [0, 0, 0, 255]), + clear_group, + photo(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(r["warnings"], json!([merged]), "{r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}"); + // Clipped to an Invert layer, which isn't applied then, the photo shows over the canvas, and + // Posterize merges with it: the gray 100 posterizes to 85. + let layers = [ + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]) }, + group("Folder", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{r}"); +} + /// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level /// out of range, data too short, or a second adjustment block on the layer. #[test] @@ -1523,6 +1688,25 @@ fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() { assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}"); } +/// An adjustment layer whose layer mask is too large for the memory allowed isn't applied, merged +/// with the layers below it or clipped to one, and the file still opens with its layers. +#[test] +fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + // The 100 × 100 mask takes more than 128 bytes; the 1-pixel layer below it doesn't. + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![0; 10_000])), ..adjustment("Invert", b"nvrt", &[]) }; + for clipped in [false, true] { + let f = file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), masked(clipped)], 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{clipped}: {warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}"); + // With the memory for it, the mask's black leaves the layer as it was. + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Invert"], "{clipped}: {warnings:?}"); + assert!(warnings.is_empty(), "{clipped}: {warnings:?}"); + } +} + /// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. #[test] fn damaged_adjustment_layers_never_panic() { diff --git a/docs/mcp.md b/docs/mcp.md index 5e4b1ddf55..2194a45351 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10916,12 +10916,13 @@ The rest are VectorCraft's own rules: encoded back to 0..255) is above the level (1 to 255) and black otherwise; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and - transparency is kept. A hidden one is left out. One with nothing visible below it in its group changes nothing; in - a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer + that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such + layers) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on - one layer) or whose merge needs more memory than allowed, fill layers that store no pixels and whose fill isn't + one layer) or whose merge, its layer mask included, needs more memory than allowed, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are not applied; the `warnings` count them. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2f1aee44ba..b42ce17573 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2324,7 +2324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group changes nothing, and in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 9772495468fe65352fa37b46b047f8b6412f8223 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 05:42:17 -0800 Subject: [PATCH 107/126] Swatch libraries: check the color names a pattern copy gives When a library tint waits for a color that a pattern's art brings, swatch.library.add learns the color's name by importing the pattern into a copy of the document. The import into the document now confirms those names: when it gives a color another name, or none, the tints linked from the copy are linked again. - library.use and Add to Swatches report an error from the import that merges a pattern's colors instead of falling back to adding them. - The params text, docs/mcp.md and docs/target-app-parity.md say that a tint or gradient links to the numbered copy its global or spot color comes in under or already has, and name a gradient test. - The new code uses the HashMap import, and one helper relinks the added tints and gradients at both places that did it. --- crates/engine/src/cmd/patternlib.rs | 5 +- crates/engine/src/cmd/swatchlib.rs | 114 ++++++++++++++++++---------- docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 81 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 28ec9a80af..e8cffa24aa 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -194,9 +194,8 @@ pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: & let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?; if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) { let mut merged = d.clone(); - if let Ok(found) = gathered.import_into(&mut merged, &SwatchChoices::default(), false) - && reused(&found) - { + let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?; + if reused(&found) { return Ok((SwatchChoices::default(), merged, found)); } } diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 40b20e5c3a..c120f45038 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint links to its color under the name that color has in the document. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1024,22 +1024,36 @@ fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) } /// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors -/// under the names `links` gives them, for each whose colors `links` names now, in one pass over -/// the document's swatches. -fn settle(d: &mut vectorcraft_doc::Document, pending: &mut Vec<(String, &Swatch)>, links: &std::collections::HashMap<String, String>) { - let mut done: std::collections::HashMap<String, Paint> = std::collections::HashMap::new(); +/// under the names `links` gives them, for each whose colors `links` names now. Those leave +/// `pending` and are returned. +fn settle<'a>( + d: &mut vectorcraft_doc::Document, + pending: &mut Vec<(String, &'a Swatch)>, + links: &HashMap<String, String>, +) -> Vec<(String, &'a Swatch)> { + let mut done = vec![]; pending.retain(|(name, w)| { let all = all_linked(&w.paint, links); if all { - done.insert(name.clone(), relinked(&w.paint, links)); + done.push((name.clone(), *w)); } !all }); - if !done.is_empty() { - for x in d.swatches_iter_mut() { - if let Some(paint) = done.get(&x.name) { - x.paint = paint.clone(); - } + relink_in(d, &done, links); + done +} + +/// Give the swatches of `d` that `list` names (document name, library swatch) the library swatch's +/// paint with its colors linked to the names `links` gives them, in one pass over the document's +/// swatches. +fn relink_in(d: &mut vectorcraft_doc::Document, list: &[(String, &Swatch)], links: &HashMap<String, String>) { + if list.is_empty() { + return; + } + let paints: HashMap<&str, Paint> = list.iter().map(|(name, w)| (name.as_str(), relinked(&w.paint, links))).collect(); + for x in d.swatches_iter_mut() { + if let Some(paint) = paints.get(x.name.as_str()) { + x.paint = paint.clone(); } } } @@ -1073,7 +1087,7 @@ fn linked_names(p: &Paint) -> Vec<&str> { } /// Paint `p` with each link to a swatch that `links` names changed to the name it maps to. -fn relinked(p: &Paint, links: &std::collections::HashMap<String, String>) -> Paint { +fn relinked(p: &Paint, links: &HashMap<String, String>) -> Paint { let mut out = p.clone(); let swap = |name: &mut String| { if let Some(to) = links.get(name.as_str()) { @@ -1090,7 +1104,7 @@ fn relinked(p: &Paint, links: &std::collections::HashMap<String, String>) -> Pai /// Whether `links` names every swatch the colors of paint `p` link to, the built-in Registration /// swatch aside (every document has it under its own name). -fn all_linked(p: &Paint, links: &std::collections::HashMap<String, String>) -> bool { +fn all_linked(p: &Paint, links: &HashMap<String, String>) -> bool { linked_names(p).iter().all(|n| *n == REGISTRATION || links.contains_key(*n)) } @@ -1114,7 +1128,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // up once so that a large palette takes linear time. let mut by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); // The document's numbered copies ("Ink 2") by the name they are numbered after, in order. - let mut copies: std::collections::HashMap<&str, Vec<&Swatch>> = std::collections::HashMap::new(); + let mut copies: HashMap<&str, Vec<&Swatch>> = HashMap::new(); for w in d.swatches_iter() { let std::collections::hash_map::Entry::Vacant(e) = by_name.entry(w.name.as_str()) else { continue }; e.insert(w); @@ -1126,7 +1140,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } } // The library's swatches by name (the first of a name wins), looked up once. - let mut lib_by_name: std::collections::HashMap<&str, &Swatch> = std::collections::HashMap::new(); + let mut lib_by_name: HashMap<&str, &Swatch> = HashMap::new(); for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) { lib_by_name.entry(w.name.as_str()).or_insert(w); } @@ -1137,15 +1151,15 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // alone, as adding that swatch finds it under its own name. Paints are compared with their // colors linked as `links` says ([`relinked`]). let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot; - let numbered = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap<String, String>| { + let numbered = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| { let c = copies.get(w.name.as_str())?; let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint); let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w)); found.map(|x| x.name.clone()) }; - let unlinked = std::collections::HashMap::new(); + let unlinked = HashMap::new(); // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. - let there = |w: &Swatch, paint: &Paint, links: &std::collections::HashMap<String, String>| match (&w.paint, &patterns) { + let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } @@ -1169,7 +1183,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // The library's global and spot colors that the picked tints and gradients link to, with the // name each has in the document: library name → document name. Each is looked up for itself, // whether or not this call picks it, once. - let mut base_names: std::collections::HashMap<String, String> = std::collections::HashMap::new(); + let mut base_names: HashMap<String, String> = HashMap::new(); let mut looked_up: HashSet<&str> = HashSet::new(); for (_, w) in &picked { for base in linked_names(&w.paint) { @@ -1203,7 +1217,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let (Some(w), Some(x)) = (lib_by_name.get(l), by_name.get(n)) else { return false }; (x.global || x.spot) && same_kind(x, w) }; - let mut links: std::collections::HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); + let mut links: HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); links.extend(base_names); let added: Vec<(String, String)> = if fresh.is_empty() { vec![] @@ -1233,27 +1247,56 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // is named by importing the pattern into a copy first. let brings = if pending.is_empty() { Default::default() } else { patternlib::brought_names(src, pattern) }; let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n); + // A global or spot color the pattern brought, or took from the document under + // a numbered name: library name → document name. A color this call picks is + // added under its own name instead of the one the pattern took. + let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| { + let mut out: HashMap<String, String> = HashMap::new(); + for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { + if d.swatch(to).is_some_and(|x| x.global || x.spot) { + out.entry(from.clone()).or_insert_with(|| to.clone()); + } + } + out + }; + // The names learned from the copy, which the import into the document confirms. + let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); let (_, colors, took) = patternlib::import(&mut probe, src, pattern)?; - for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { - if probe.swatch(to).is_some_and(|x| x.global || x.spot) { - links.entry(from.clone()).or_insert_with(|| to.clone()); + for (from, to) in colors_of(&probe, &colors, &took) { + if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { + e.insert(to); + learned.push(from); } } } - settle(d, &mut pending, &links); + let settled = settle(d, &mut pending, &links); let had = taken_names(d); let (target, colors, took) = patternlib::import(d, src, pattern)?; - // A global or spot color the pattern brought, or took from the document under - // a numbered name, is the one the library's tints of it link to, unless the - // document already has one for it. A color this call picks is added under - // its own name instead of the one the pattern took. - for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { - if d.swatch(to).is_some_and(|x| x.global || x.spot) { - links.entry(from.clone()).or_insert_with(|| to.clone()); + // Those colors are the ones the library's tints of them link to, unless the + // document already has one for them. A name the copy gave that the import + // into the document did not give is replaced, and the tints linked to it are + // linked again. + let mut found = colors_of(d, &colors, &took); + let mut changed = false; + for from in learned { + let real = found.remove(&from); + if real.as_ref() != links.get(&from) { + changed = true; + match real { + Some(to) => links.insert(from, to), + None => links.remove(&from), + }; } } + for (from, to) in found { + links.entry(from).or_insert(to); + } + if changed { + relink_in(d, &settled, &links); + pending.extend(settled.into_iter().filter(|(_, w)| !all_linked(&w.paint, &links))); + } brought.extend(colors); if let Some(name) = library_pattern_swatch(d, w, &target).filter(|n| had.contains(n)) { reused.push((w.name.clone(), name)); @@ -1339,14 +1382,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } out.push((w.name.clone(), name)); } - let later: std::collections::HashMap<String, Paint> = pending.into_iter().map(|(name, w)| (name, relinked(&w.paint, &links))).collect(); - if !later.is_empty() { - for x in d.swatches_iter_mut() { - if let Some(paint) = later.get(&x.name) { - x.paint = paint.clone(); - } - } - } + relink_in(d, &pending, &links); Ok((out, reused, brought)) })?; existing.extend(reused); diff --git a/docs/mcp.md b/docs/mcp.md index af535e4ff7..6eda2bc435 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5805,8 +5805,9 @@ color the pattern's art links to keeps the library's color: when the document gi in under a numbered name ("Ink 2") and the pattern links to that. A library color whose name the document gives another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name -is used as it is. A library tint or gradient links to its colors under the names those colors have in the document, -whether a color is picked before or after it, was added earlier or came with a pattern's art. `added` lists the colors +is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the +document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added +earlier or came with a pattern's art. `added` lists the colors the pattern's art brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`<file>` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3965f265bf..388bc655d1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). A global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name, and adding it again uses that numbered copy; a library tint links to it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name, and adding it again uses that numbered copy; a library tint or gradient links to it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 0d272049445a08835527e63b364d553ba4b10b2b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 06:11:57 -0800 Subject: [PATCH 108/126] PSD import: keep clips and merges around adjustments that aren't applied - An adjustment layer's mask is checked against the memory allowed beside the canvases held while it is read (the merged canvas, the base's shape and the copies kept for pass-through groups). - A clipped adjustment layer whose mask is too large to read is left out without unclipping the layers clipped above it to the same base. - An adjustment layer in a pass-through group whose mask is too large to read is left out without stopping the merge of the layer above the group; its own merge with the layers below it still isn't made. - A layer whose stored pixels are all transparent draws nothing, so an adjustment layer above it in a pass-through group stays kept to change what is below the group. - A layer merged in a pass-through group for its blend mode or its knockout takes the adjustment layers kept below it with it, so an adjustment layer above that group in an outer pass-through group merges with it instead of being dropped. --- crates/engine/src/cmd/fileio/psdlayers.rs | 136 ++++++++++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 101 +++++++++++++ docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 4 files changed, 227 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 5fc6916c5e..dae505e247 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -45,11 +45,14 @@ //! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher //! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, //! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One -//! with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 +//! with nothing visible below it in its group that draws (a layer that stores no pixels, other than +//! a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 //! opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) //! changes nothing; in a pass-through group it changes //! what is below the group when the group is merged, and otherwise isn't applied. One that layers -//! are clipped to, and one clipped to another adjustment layer, isn't applied. +//! are clipped to, and one clipped to another adjustment layer, isn't applied. One whose layer mask +//! needs more memory than allowed beside the canvases it would change isn't applied, and a clip, or +//! a merge for another layer, that it is part of goes on without it. //! //! Other adjustment layers, Invert, Threshold and Posterize data that can't be read (a level out of //! range, too short, or a second adjustment block on the layer), fill layers that store no pixels and @@ -969,6 +972,12 @@ struct Builder<'a, F> { blank_log: Vec<usize>, /// How many times a merge was counted as not made because it needed more memory than allowed. squeezed: usize, + /// The adjustment layer whose own merge with the layers below it is being made: a layer mask of + /// its too large to read stops that merge, where one of another adjustment layer drawn in it + /// leaves that one out. + adjusting: Option<usize>, + /// Whether each record's stored transparency is 0 everywhere, once [`Self::clear`] has read it. + clear: Vec<Cell<Option<bool>>>, } impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { @@ -1098,8 +1107,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } /// Does record `i`'s layer mask, switched on, fit the memory allowed for reading it with - /// [`Self::mask`]? `true` when it has none, and when its size is damaged (reading it says so). - fn mask_fits(&self, i: usize) -> Result<bool, String> { + /// [`Self::mask`] beside `live` bytes of canvases held while it is read, and the copies of what + /// is below the pass-through groups being merged? `true` when it has none, and when its size is + /// damaged (reading it says so). + fn mask_fits(&self, i: usize, live: u64) -> Result<bool, String> { let rec = self.record(i)?; let Some(m) = rec.mask.filter(|m| !m.disabled) else { return Ok(true) }; if !rec.channels.iter().any(|(c, _)| *c == -2) { @@ -1110,7 +1121,42 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { if w > max_side || rows > max_side { return Ok(true); } - Ok(self.fits((row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64)).is_ok()) + let bytes = (row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64); + Ok(bytes.saturating_add(live) <= self.room()) + } + + /// Does record `i` store pixels that are all fully transparent, so that it paints nothing? + /// Its transparency is read once. `false` when it stores none, or has no transparency, or its + /// transparency can't be read within the memory allowed or is damaged (drawing it says so). + fn clear(&self, i: usize) -> Result<bool, String> { + if let Some(clear) = self.clear.get(i).and_then(Cell::get) { + return Ok(clear); + } + let rec = self.record(i)?; + let (w, rows) = rec.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let alpha = rec.channels.iter().find(|(c, _)| *c == -1).map(|(_, data)| data); + let clear = match alpha { + Some(data) if !rec.draws_nothing() && !rec.color_over_canvas() && w <= max_side && rows <= max_side => { + let (depth, row) = (self.h.depth, row_bytes(w, self.h.depth)); + let bytes = (row as u64).saturating_mul(rows as u64); + if bytes > self.room() { + false + } else { + self.spend(bytes)?; + match layer_channel(data, rows, row, self.h.psb, depth) { + Ok(plane) => (0..rows) + .all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))), + Err(_) => false, + } + } + } + _ => false, + }; + if let Some(c) = self.clear.get(i) { + c.set(Some(clear)); + } + Ok(clear) } /// Multiply `c`'s transparency by record `i`'s layer mask. @@ -1229,9 +1275,12 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } // A clipped adjustment layer changes the merged canvas in place, through its layer mask. let adjust = self.adjustment(body)?; - // Its layer mask too large to read needs more memory than allowed. - if adjust.is_some() && !base_adjustment && !self.mask_fits(i)? { - return Ok(false); + // Its layer mask too large to read needs more memory than allowed: it isn't applied, and the + // layers clipped above it still clip to the base. + if adjust.is_some() && !base_adjustment && !self.mask_fits(i, 0)? { + self.squeezed += 1; + self.unadjust(i); + return Ok(true); } let layer = match adjust { Some(_) => Canvas::default(), @@ -1282,6 +1331,16 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { self.unadjust(i); return Ok(true); } + // The mask is read beside the merged canvas and the base's shape. + let shape = match &u.clip { + Some(Clip::Shape(s)) => 4 * s.len() as u64, + _ => 0, + }; + if !self.mask_fits(i, (16 * c.px.len() as u64).saturating_add(shape))? { + self.squeezed += 1; + self.unadjust(i); + return Ok(true); + } let mask = self.mask(i, false)?; adjust_onto(c, a, blend, opacity, mask.as_ref(), i); u.name.push_str(" + "); @@ -1497,6 +1556,12 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { continue; } let (clips, drawn) = self.base_draws(items, k)?; + // One in a mode VectorCraft lacks (an adjustment layer aside), or with a shallow knockout + // that cuts what is below it, is merged with the layers below it in the group, which + // takes the ones kept so far with them (see `merged`). + if (matches!(r.blend, Blend::Other(_)) && (children.is_some() || r.adjust().is_none())) || self.cuts(items, k, clips, drawn && draws)? { + records.clear(); + } // One that layers are clipped to isn't kept, and a pass-through group they are clipped to // is drawn alone (see `clip`). One at 0 opacity changes nothing (see `adjust_below`). let keeps = !clips && r.opacity * r.fill > 0.0 && (!draws || !records.is_empty()); @@ -1517,6 +1582,33 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Ok((records, draws)) } + /// Does item `k` of `items`, a pass-through group's layers, take a shallow knockout that is merged + /// with the layers below it (see [`Self::knocks`])? Only one that `clips` nothing, is in the + /// Normal mode over visible layers in the Normal mode back to the last one merged for its mode, + /// and where it and something below it draw (`draws`). + fn cuts(&self, items: &[Item], k: usize, clips: bool, draws: bool) -> Result<bool, String> { + let record = |item: &Item| match item { + Item::Layer(i) | Item::Group(i, _) => self.record(*i), + }; + let Some(r) = items.get(k).map(record).transpose()? else { return Ok(false) }; + let normal = Blend::Mode(BlendMode::Normal); + if r.knockout != 1 || clips || !draws || r.blend != normal { + return Ok(false); + } + for below in items.get(..k).unwrap_or_default().iter().rev() { + let b = record(below)?; + if b.hidden || b.clipped { + continue; + } + match b.blend { + Blend::Other(_) if matches!(below, Item::Group(..)) || b.adjust().is_none() => break, + blend if blend != normal => return Ok(false), + _ => {} + } + } + Ok(true) + } + /// Does anything in `items` draw: a visible layer or group that isn't clipped and draws (see /// [`Self::base_draws`])? fn draws(&self, items: &[Item]) -> Result<bool, String> { @@ -1567,7 +1659,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Ok(match item { Item::Layer(i) => { let r = self.record(*i)?; - (r, !r.draws_nothing()) + (r, !r.draws_nothing() && !self.clear(*i)?) } Item::Group(g, children) => (self.record(*g)?, self.draws(children)?), }) @@ -1732,9 +1824,9 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { let mut below = false; for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { below |= match &b.body { - // An adjustment layer, a layer that draws nothing, or a group of such layers, has - // nothing to change. - Body::Layer(i) => !self.record(*i)?.draws_nothing(), + // An adjustment layer, a layer that draws nothing or whose pixels are all + // transparent, or a group of such layers, has nothing to change. + Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, Body::Group(_, items) => self.draws(items)?, // Clipped layers merged with a base that has no pixels have none either. Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), @@ -1751,7 +1843,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } let saved = self.saved(); let outer = self.try_from_here(); - let made = self.merge_into(out, &u)?; + let adjusting = self.adjusting.replace(u.record); + let made = self.merge_into(out, &u); + self.adjusting = adjusting; + let made = made?; self.tried(outer, made)?; if !made { self.restore(saved)?; @@ -2018,8 +2113,17 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { if let Some(a) = self.adjustment(&u.body)? { if let Some(c) = acc.as_mut() { let mask = match u.mask_of { - // A layer mask too large to read needs more memory than allowed. - Some(i) if !self.mask_fits(i)? => return Ok(false), + // A layer mask too large to read beside the canvas needs more memory than + // allowed: the adjustment isn't applied, and the rest of the merge goes on. + Some(i) if !self.mask_fits(i, 16 * c.px.len() as u64)? => { + // The adjustment's own merge isn't made then. + if self.adjusting == Some(u.record) { + return Ok(false); + } + self.squeezed += 1; + self.unadjust(u.record); + return Ok(true); + } Some(i) => self.mask(i, false)?, None => None, }; @@ -2454,6 +2558,8 @@ pub(super) fn import( laid_blank: vec![false; records.len()], blank_log: vec![], squeezed: 0, + adjusting: None, + clear: vec![Cell::new(None); records.len()], }; let layers = b.list(&items, Level::Top)?; // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 8ebc3a9f24..cda458d2aa 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1707,6 +1707,107 @@ fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() { } } +/// An adjustment layer's mask is read beside the canvases it changes: a 100 × 1 mask fits 256 bytes +/// alone, but not beside a 6 × 1 canvas, so the layer isn't applied. With the memory for both, it is. +#[test] +fn an_adjustment_mask_counts_the_canvas_it_changes() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 1, 100], 255, 0, vec![255; 100])), ..adjustment("Invert", b"nvrt", &[]) }; + for clipped in [false, true] { + let f = file(6, 1, &[layer("Under", [0, 0, 1, 6], [10, 20, 30, 255]), masked(clipped)], 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 256, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under"], "{clipped}: {warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}"); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Invert"], "{clipped}: {warnings:?}"); + assert!(warnings.is_empty(), "{clipped}: {warnings:?}"); + } +} + +/// An adjustment layer whose mask is too large to read is left out without stopping the clip or the +/// merge around it: a layer clipped above it still clips to the base, and a layer in a mode +/// VectorCraft lacks above a pass-through group holding it still merges in its mode. +#[test] +fn an_adjustment_mask_too_large_leaves_the_clip_and_merge_around_it() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![255; 10_000])), ..adjustment("Invert", b"nvrt", &[]) }; + let layers = [layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), masked(true), L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }]; + let (doc, warnings) = psdlayers::import(&file(2, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Base + Photo"], "{warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + // Gray 100 under Linear Dodge's gray 20 gives gray 120. + let layers = [ + layer("Under", [0, 0, 1, 1], [100, 100, 100, 255]), + group_end(), + masked(false), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [20, 20, 20, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(1, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::<Vec<_>>(), ["Under + Folder + Dodge"], "{warnings:?}"); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(warnings, ["1 adjustment layer was not applied", merged]); + let Some([c]) = doc.layers[0].children().map(Vec::as_slice) else { panic!("the merged layer holds one image") }; + let NodeKind::Image(img) = &c.kind else { panic!("the merged layer holds an image") }; + let px = craft_image_codecs::decode(&doc.images[&img.key].bytes).unwrap().to_rgba8(); + assert_eq!(px, [120, 120, 120, 255]); +} + +/// A layer merged in a pass-through group for its mode or its knockout takes the adjustment layers +/// kept below it with it: an adjustment layer above that group in an outer pass-through group then +/// merges with it, and the gray 100 posterizes to 85. +#[test] +fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() { + let tops = [ + ("Linear Dodge", vec![L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]) }]), + ("knockout", vec![layer("Photo", [0, 0, 1, 1], [50, 50, 50, 255]), knockout(layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]), 1, 255)]), + ]; + for (what, top) in tops { + let layers = [ + &[group_end(), group_end(), adjustment("Invert", b"nvrt", &[])][..], + &top, + &[group("Inner", b"pass"), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass")], + ] + .concat(); + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{what}: {r}"); + assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{what}: {r}"); + } +} + +/// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a +/// pass-through group, directly or in a pass-through group inside it, still changes what is below +/// the group. +#[test] +fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() { + let clear = || layer("Clear", [0, 0, 1, 1], [50, 50, 50, 0]); + let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let direct = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + clear(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{r}"); + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + clear(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); +} + /// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. #[test] fn damaged_adjustment_layers_never_panic() { diff --git a/docs/mcp.md b/docs/mcp.md index 2194a45351..04ce0fe200 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10917,9 +10917,11 @@ The rest are VectorCraft's own rules: nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer - that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such + that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all + transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not - applied. + applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, + and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer) or whose merge, its layer mask included, needs more memory than allowed, fill layers that store no pixels and whose fill isn't diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b42ce17573..0046922018 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2324,7 +2324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 7f97df87d4f29e75aef1b9c86f1a44a56ef6c91e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 07:54:43 -0800 Subject: [PATCH 109/126] Swatch libraries: library tints link only to a color of their own kind swatch.library.add linked a library tint to the wrong color in two cases. When the document had a process color with the same name and paint as the tint's global color, the global color counted as already present and the tint linked to the process color. When a tint was added without its global color and the document had another swatch of that color's name, the tint linked to that swatch. - A library color counts as already in the document only when the document's color of that name is the same kind: process, global or spot. A global color whose name the document gives a process color now comes in under a numbered name, and its tints link to that copy. - A global or spot color that an added tint or gradient links to, and that the document does not have, now comes in with the tint or gradient. It keeps its own name when that name is free and gets a number otherwise. added lists it after the picked swatches. - A library tint is not the document's tint of the same name and paint when the document's swatch of the base's name is another color or kind. - A tint that a pattern brought is used for a picked library tint only when the color it links to is the library color's kind. --- crates/engine/src/cmd/swatchlib.rs | 50 ++++++++-- crates/engine/src/tests/swatchlib.rs | 143 +++++++++++++++++++++++---- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 4 files changed, 173 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index c120f45038..a2fa4bb0bb 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1151,20 +1151,31 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // alone, as adding that swatch finds it under its own name. Paints are compared with their // colors linked as `links` says ([`relinked`]). let same_kind = |x: &Swatch, w: &Swatch| x.global == w.global && x.spot == w.spot; + // A color is the same swatch only as the same kind: a library global color is not the + // document's process color of the same name and paint, which a tint cannot link to. + let same_color_kind = |x: &Swatch, w: &Swatch| w.paint.color().is_none() || same_kind(x, w); let numbered = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| { let c = copies.get(w.name.as_str())?; - let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint); + let own = |x: &Swatch| lib_by_name.get(x.name.as_str()).is_some_and(|l| relinked(&l.paint, links) == x.paint && same_color_kind(x, l)); let found = c.iter().find(|x| !own(x) && x.paint == *paint && same_kind(x, w)); found.map(|x| x.name.clone()) }; let unlinked = HashMap::new(); + // Whether a library global or spot color that paint `p` links to has no place in `links` + // while the document gives its name another swatch, which such a link would find instead. + let misplaced = |p: &Paint, links: &HashMap<String, String>| { + linked_names(p) + .into_iter() + .any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot)) + }; // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| match (&w.paint, &patterns) { (Paint::Pattern { pattern, .. }, Some(src)) => { patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) } + _ if misplaced(&w.paint, links) => None, _ => match by_name.get(w.name.as_str()) { - Some(x) if x.paint == *paint => Some(w.name.clone()), + Some(x) if x.paint == *paint && same_color_kind(x, w) => Some(w.name.clone()), Some(_) => numbered(w, paint, links), None if group_names.contains(w.name.as_str()) => numbered(w, paint, links), None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), @@ -1324,14 +1335,21 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // A color a pattern added earlier in this call brought with its art is that // swatch when it shows the library swatch's color: it moves to the library // swatch's place, when its colors link where the library swatch's do: to the - // names `links` gives them, and not elsewhere for a color this call has yet to - // add. + // names `links` gives them, not elsewhere for a color this call has yet to add, + // and otherwise to a color of the library color's paint and process, global or spot kind, + // or under the same name when the library has no such swatch (Registration). let fits = |x: &Paint| { let (ours, theirs) = (linked_names(&w.paint), linked_names(x)); ours.len() == theirs.len() && ours.iter().zip(&theirs).all(|(l, t)| match links.get(*l) { Some(to) => to == t, - None => !picked_names.contains(l), + None => { + !picked_names.contains(l) + && match lib_by_name.get(*l) { + Some(b) => d.swatch(t).is_some_and(|x| x.paint == b.paint && same_kind(x, b)), + None => l == t, + } + } }) }; let same = |to: &str| { @@ -1382,6 +1400,26 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } out.push((w.name.clone(), name)); } + // A library global or spot color that a tint or gradient added here links to, which the + // document does not have and nothing in this call brought, comes in with it, as pasting + // art painted with the tint brings its color. It is listed with the colors patterns + // brought. + let mut wanted: Vec<&str> = vec![]; + let mut seen: HashSet<&str> = HashSet::new(); + for (_, w) in &pending { + for n in linked_names(&w.paint) { + if n != REGISTRATION && !links.contains_key(n) && seen.insert(n) { + wanted.push(n); + } + } + } + for n in wanted { + let Some(b) = lib_by_name.get(n).filter(|b| b.global || b.spot) else { continue }; + let name = free_copy_in(&mut taken, &b.name, |x| lib_by_name.contains_key(x)); + d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() }); + links.insert(n.to_string(), name.clone()); + brought.push((n.to_string(), name)); + } relink_in(d, &pending, &links); Ok((out, reused, brought)) })?; diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 875d9b5e28..9315eadb06 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -603,7 +603,15 @@ fn apply_paints_with_the_picked_color_not_one_a_pattern_brought() { run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"})); assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"], "{r}"); - assert_eq!(r["applied"], "Ink", "{r}"); + // The picked global color is not the process one: it comes in numbered, and the pattern's art + // takes it. + assert_eq!(r["applied"], "Ink 2", "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + // A picked color the document already has is applied, not the pattern added after it. + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Tiles"], "apply": "fill"})); + assert_eq!((&r["existing"], &r["applied"]), (&json!(["Ink"]), &json!("Ink")), "{r}"); } /// A numbered copy that another swatch of the same name hides (the document finds the first of a @@ -886,10 +894,11 @@ fn a_library_spot_tint_links_to_the_spot_color_not_a_process_one() { } } -/// A numbered copy that the library's own swatch of that name is (the same paint, whatever its -/// kind) is not also taken for the library color it is numbered after. +/// The library's process color of a numbered name is not the document's global color of that name +/// and paint, so that global color is the numbered copy of the library's global color it is named +/// after. #[test] -fn a_numbered_copy_the_library_has_by_paint_is_not_shared() { +fn a_numbered_process_color_of_the_library_is_not_the_documents_global_copy() { let mut s = session(); run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff"})); @@ -899,7 +908,7 @@ fn a_numbered_copy_the_library_has_by_paint_is_not_shared() { run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink 2"]})); - assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}"); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 2 2"]), &json!(["Ink 2"])), "{r}"); } /// A library tint added with a pattern whose art took the document's numbered copy of the tint's @@ -948,21 +957,115 @@ fn a_numbered_tint_the_library_has_is_not_shared() { assert_eq!(r["added"].as_array().map(Vec::len), Some(1), "{r}"); } -/// Adding a library color the document has as a process color of the same paint, with its tint, -/// again adds no other copy of the tint. +/// The document's swatch `name` is a global color showing `hex`. +fn is_global(s: &Session, name: &str, hex: &str) -> bool { + doc(s).swatch(name).is_some_and(|w| w.global && w.paint.color().is_some_and(|c| c.to_hex() == hex)) +} + +/// A library inks library (global `Ink` #0000ff and its tint `Ink half`) loaded into `s`, which is +/// then left in a new document whose own `Ink` is the same blue as a process color → the id. +fn tinted_ink_library_and_a_process_ink(s: &mut Session) -> Value { + let id = tinted_ink_library_and_a_red_ink(s); + run(s, "swatch.delete", json!({"names": ["Ink"]})); + run(s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + id +} + +/// A library global color is not the document's process color of the same name and paint: it +/// comes in numbered, its tint links to it, and adding the two again adds nothing. #[test] fn a_library_tint_of_a_color_the_document_has_as_process_is_added_once() { let mut s = session(); - run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let id = tinted_ink_library_and_a_process_ink(&mut s); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "{r}"); + let before = (named_after(&s, "Ink"), named_after(&s, "Ink half")); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); + assert_eq!(again["added"], json!([]), "{again}"); + assert_eq!((named_after(&s, "Ink"), named_after(&s, "Ink half")), before, "{r} then {again}"); +} + +/// A library tint added without its global color, in a document whose swatch of the color's name +/// is another color or a process color, brings its color along and links to it, not to the +/// document's swatch; adding the tint again adds nothing. +#[test] +fn a_library_tint_added_alone_brings_its_color_beside_a_namesake() { + for process in [false, true] { + let mut s = session(); + let id = if process { tinted_ink_library_and_a_process_ink(&mut s) } else { tinted_ink_library_and_a_red_ink(&mut s) }; + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(base != "Ink" && is_global(&s, &base, "#0000ff"), "process {process}: {r}"); + assert_eq!(r["added"], json!(["Ink half", base]), "process {process}: {r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "process {process}: {again}"); + } +} + +/// A library tint of a spot color is not the document's tint of the same name and paint whose +/// color is a global process color: adding it alone brings the spot color and a tint of it. +#[test] +fn a_library_spot_tint_is_not_the_documents_tint_of_a_process_namesake() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); run(&mut s, "file.new", json!({"width": 100, "height": 100})); - run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); - let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); - let before = named_after(&s, "Ink half"); - let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink", "Ink half"]})); - assert_eq!(named_after(&s, "Ink half"), before, "{r} then {again}"); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + let tint = r["added"][0].as_str().unwrap_or_default().to_string(); + let base = tint_base(&s, &tint).unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!([tint])), "{again}"); +} + +/// A tint of a process namesake that a pattern's art brings is not taken for a picked library +/// tint of a spot color. +#[test] +fn a_library_spot_tint_is_not_a_process_tint_a_pattern_brought() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink half", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let tints: Vec<String> = doc(&s).swatches_iter().filter(|w| w.name.starts_with("Ink half")).map(|w| w.name.clone()).collect(); + if !tints.is_empty() { + run(&mut s, "swatch.delete", json!({"names": tints})); + } + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + let picked = r["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink half"))).unwrap_or_default(); + let base = tint_base(&s, picked).unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}"); +} + +/// A library tint added without its global color to a document that has no swatch of the color's +/// name brings the color along under its own name. +#[test] +fn a_library_tint_added_alone_brings_its_missing_color() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "swatch.delete", json!({"names": ["Ink"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}"); + assert!(is_global(&s, "Ink", "#0000ff"), "{r}"); } /// A library tint added with a pattern the document already has (pasted with Merge, so it brings @@ -1002,8 +1105,8 @@ fn a_library_tint_with_a_pattern_the_document_has_is_added_once() { } } -/// A library gradient whose stops link to a color and to the Registration swatch, picked before a -/// pattern whose art brings the color under a numbered name, is not added a second time. +/// A library gradient whose stops link to a color and to the Registration swatch, picked before or +/// after a pattern whose art brings the color under a numbered name, is not added a second time. #[test] fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() { let mut s = session(); @@ -1018,10 +1121,12 @@ fn a_gradient_with_a_registration_stop_before_its_pattern_is_not_copied() { run(&mut s, "object.pattern.done", json!({})); let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); - run(&mut s, "file.new", json!({"width": 100, "height": 100})); - run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); - let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Fade", "Squares"]})); - assert_eq!(named_after(&s, "Fade"), ["Fade"], "{r}"); + for names in [json!(["Fade", "Squares"]), json!(["Squares", "Fade"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + assert_eq!(named_after(&s, "Fade"), ["Fade"], "{names}: {r}"); + } } /// A library tint follows its color when the call picks the color, even when a pattern added diff --git a/docs/mcp.md b/docs/mcp.md index 6eda2bc435..0a31452419 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5807,8 +5807,10 @@ another color is the document's numbered copy of the same color when it has one, again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added -earlier or came with a pattern's art. `added` lists the colors -the pattern's art brings too. A document with +earlier or came with a pattern's art. A library global color is not the document's process color of the same name and +paint: it comes in numbered. A global or spot color that a library tint or gradient links to and the document lacks +comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. `added` +lists the colors the pattern's art, a tint or a gradient brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`<file>` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 388bc655d1..8a406b82b8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name, and adding it again uses that numbered copy; a library tint or gradient links to it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 9b6519382c7e1e1098bbbe9d57580943556a314f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 09:12:19 -0800 Subject: [PATCH 110/126] PSD import: layers their masks hide draw nothing A layer or group whose layer mask, switched on, hides all of it now counts as drawing nothing when the import decides what an adjustment layer changes. A layer with stored pixels is hidden when its mask is 0 over all of them. A group, an adjustment layer and a layer that stores no pixels are hidden only when the mask is 0 everywhere, the value outside it included. - An adjustment layer above such a layer or group in a pass-through group is kept to change what is below the group, instead of merging with pixels that never show. - A shallow knockout hidden by its mask merges nothing, so the adjustment layers kept below it in a pass-through group stay in the group's kept set: an adjustment layer above that group in an outer pass-through group is kept after them, and both change what is below. - A clipping base hidden by its mask draws nothing, its clipped layers included. Each mask is read once for this, only when it can hide all of the layer, and the read is not counted against the import's memory allowance, since the mask is read and counted again where it is drawn. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/psdlayers.rs | 68 +++++++++++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 52 ++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 116 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index dae505e247..d6719d45ea 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -978,6 +978,8 @@ struct Builder<'a, F> { adjusting: Option<usize>, /// Whether each record's stored transparency is 0 everywhere, once [`Self::clear`] has read it. clear: Vec<Cell<Option<bool>>>, + /// Whether each record's layer mask hides all of it, once [`Self::masked_out`] has read it. + masked_out: Vec<Cell<Option<bool>>>, } impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { @@ -1159,6 +1161,47 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Ok(clear) } + /// Does record `i` have a layer mask, switched on, that hides all of it? For a layer with stored + /// pixels, other than an adjustment layer, the mask is 0 over all of them; for a group, an + /// adjustment layer and a layer that stores no pixels, which can change pixels anywhere below + /// them, it is 0 everywhere, the value outside it included. A mask is read only when it can hide + /// all of it, once. `false` when it has none, or it can't be read within the memory allowed or + /// is damaged (drawing it says so). `group` says the record opens a group. + fn masked_out(&self, i: usize, group: bool) -> Result<bool, String> { + if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { + return Ok(out); + } + let rec = self.record(i)?; + // Where it draws: a layer's stored pixels. + let area = (!group && !rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then_some(rec.bounds); + let inside = + |b: Bounds, x: i64, y: i64| (i64::from(b.left)..i64::from(b.right)).contains(&x) && (i64::from(b.top)..i64::from(b.bottom)).contains(&y); + // With a value outside it other than 0, it hides all of it only when it covers all of `area`. + let can_hide = rec.mask.is_some_and(|m| { + let outside = if m.inverted { 255 - m.default } else { m.default }; + outside == 0 + || area.is_some_and(|a| m.bounds.left <= a.left && m.bounds.top <= a.top && a.right <= m.bounds.right && a.bottom <= m.bounds.bottom) + }); + let out = can_hide && self.has_mask(Some(i))? && self.mask_fits(i, 0)? && { + // This read isn't counted against the import's allowance: the mask is read again, and + // counted, where the layer is drawn or its opacity mask is made. + let spent = self.spent.get(); + let read = self.mask(i, false); + self.spent.set(spent); + match read { + // Its values outside `area` hide nothing of it. + Ok(Some((left, top, m, _))) => { + m.enumerate_pixels().all(|(x, y, p)| p.0[0] == 0 || area.is_some_and(|a| !inside(a, left + i64::from(x), top + i64::from(y)))) + } + _ => false, + } + }; + if let Some(c) = self.masked_out.get(i) { + c.set(Some(out)); + } + Ok(out) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1627,11 +1670,15 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { /// For item `k` of `items`, visible and not clipped: whether visible layers are clipped to it, /// and whether it draws, above 0 opacity: by its own pixels (a group's, those of its layers) /// above 0 fill, or by those of the layers clipped to it that draw, which show in its pixels at - /// any fill, or over the canvas when it is a layer that covers it without drawing. + /// any fill, or over the canvas when it is a layer that covers it without drawing and that its + /// layer mask doesn't hide all of. fn base_draws(&self, items: &[Item], k: usize) -> Result<(bool, bool), String> { let Some(item) = items.get(k) else { return Ok((false, false)) }; let (r, own) = self.pixels(item)?; - let covers = matches!(item, Item::Layer(_)) && r.covers_without_drawing(); + let covers = match item { + Item::Layer(i) => r.covers_without_drawing() && !self.masked_out(*i, false)?, + Item::Group(..) => false, + }; let (mut clips, mut clips_draw) = (false, false); for above in items.get(k + 1..).unwrap_or_default() { let c = match above { @@ -1654,14 +1701,14 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } /// `item`'s record, and whether it has pixels of its own: a layer that draws, or a group with - /// something in it that draws (see [`Self::draws`]). + /// something in it that draws (see [`Self::draws`]), that its layer mask doesn't hide all of. fn pixels(&self, item: &Item) -> Result<(&Record<'_>, bool), String> { Ok(match item { Item::Layer(i) => { let r = self.record(*i)?; - (r, !r.draws_nothing() && !self.clear(*i)?) + (r, !r.draws_nothing() && !self.clear(*i)? && !self.masked_out(*i, false)?) } - Item::Group(g, children) => (self.record(*g)?, self.draws(children)?), + Item::Group(g, children) => (self.record(*g)?, self.draws(children)? && !self.masked_out(*g, true)?), }) } @@ -1823,7 +1870,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } let mut below = false; for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { - below |= match &b.body { + let draws = match &b.body { // An adjustment layer, a layer that draws nothing or whose pixels are all // transparent, or a group of such layers, has nothing to change. Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, @@ -1831,6 +1878,14 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { // Clipped layers merged with a base that has no pixels have none either. Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), }; + // One whose layer mask hides all of it has nothing to change either. A base merged with + // the layers clipped to it isn't checked: its canvas may reach past the base's own pixels. + let hidden = |m: usize| match &b.body { + Body::Layer(_) => self.masked_out(m, false), + Body::Group(..) => self.masked_out(m, true), + Body::Merged(_) => Ok(false), + }; + below = below || (draws && !b.mask_of.map(hidden).transpose()?.unwrap_or(false)); } // Kept below it in the group, or in a pass-through group below it there. let pending = !self.pending(out, level)?.is_empty(); @@ -2560,6 +2615,7 @@ pub(super) fn import( squeezed: 0, adjusting: None, clear: vec![Cell::new(None); records.len()], + masked_out: vec![Cell::new(None); records.len()], }; let layers = b.list(&items, Level::Top)?; // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index cda458d2aa..bc66cb717c 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1808,6 +1808,58 @@ fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); } +/// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in +/// a pass-through group still changes what is below the group, and a shallow knockout hidden that +/// way merges nothing, so the adjustment layers below it stay kept. +#[test] +fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { + let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; + let under = || layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]); + let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 2], [0, 0, 0, 255]) }; + let photo = || layer("Photo", [0, 0, 1, 2], [100, 100, 100, 255]); + let inverted = [[245, 235, 225, 255], [245, 235, 225, 255]]; + let masked_layer = [under(), group_end(), black(photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + // A mask over all of the layer's pixels hides it whatever its value outside them. + let white_outside = L { mask: Some(([0, 0, 1, 2], 255, 0, vec![0, 0])), ..photo() }; + let covered_layer = [under(), group_end(), white_outside, adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + let masked_group = [ + under(), + group_end(), + group_end(), + photo(), + black(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let knockout_cut = knockout(black(layer("Cut", [0, 0, 1, 1], [0, 0, 255, 255])), 1, 255); + let masked_knockout = [ + under(), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + knockout_cut, + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + let cases = [ + ("layer", &masked_layer[..], inverted), + ("covered layer", &covered_layer[..], inverted), + ("group", &masked_group[..], inverted), + ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ]; + let rows = |layers: &[L]| { + let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); + row_of(&s, &s.doc().unwrap().doc.layers[0]) + }; + let got: Vec<_> = cases.iter().map(|(what, layers, _)| (*what, rows(layers))).collect(); + let want: Vec<_> = cases.iter().map(|(what, _, want)| (*what, want.to_vec())).collect(); + assert_eq!(got, want); +} + /// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. #[test] fn damaged_adjustment_layers_never_panic() { diff --git a/docs/mcp.md b/docs/mcp.md index 04ce0fe200..d1e8f49dd7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10919,7 +10919,7 @@ The rest are VectorCraft's own rules: transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such - layers) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0046922018..ef92436720 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2324,7 +2324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 79dd33e2283d8c3ee507671c4939b1055e88ff3b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 09:30:26 -0800 Subject: [PATCH 111/126] Swatch libraries: a tint whose color was deleted brings it back A library tint or gradient counts as already in the document only when each color it links to is there. When the document's tint of that name links to a color the document no longer has (deleted without unlinking), the color comes back under its own name and is listed in `added`. A picked pattern the document already holds keeps the copy of a color its art takes (a numbered copy the library also names), and the picked tints and gradients of that color link to it, so adding the pattern and the tint again adds nothing. Without such a pattern, a numbered copy the library also names stands for that library swatch alone. docs/mcp.md also states that a pattern pasted with Merge for some colors and Add for others is added again as a copy. --- crates/engine/src/cmd/swatchlib.rs | 108 ++++++++++++++++++++++++--- crates/engine/src/tests/swatchlib.rs | 74 ++++++++++++++++++ docs/mcp.md | 9 ++- 3 files changed, 178 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index a2fa4bb0bb..48413d99a8 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1168,20 +1168,64 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { .into_iter() .any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot)) }; - // `paint` is `w`'s paint with the colors it links to as `links` has them in the document. - let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| match (&w.paint, &patterns) { - (Paint::Pattern { pattern, .. }, Some(src)) => { - patternlib::present_pattern(d, src, pattern).and_then(|target| library_pattern_swatch(d, w, &target)) + let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors + // linked to swatches of the document → the library's global and spot colors to bring back. + // `x` shows `w`'s paint with each color linked to: the name `links` gives it; its own name when + // that is the document's color of the library color's paint and kind; or, for a library color + // the document has under no name, that color's own name, which then comes in under it. + // Registration and colors the library does not have keep their names. + let fit = |x: &Swatch, w: &Swatch, links: &HashMap<String, String>| -> Option<Vec<String>> { + let (ours, theirs) = (linked_names(&w.paint), linked_names(&x.paint)); + if ours.len() != theirs.len() { + return None; } - _ if misplaced(&w.paint, links) => None, - _ => match by_name.get(w.name.as_str()) { - Some(x) if x.paint == *paint && same_color_kind(x, w) => Some(w.name.clone()), + let map: HashMap<String, String> = ours.iter().zip(&theirs).map(|(l, t)| (l.to_string(), t.to_string())).collect(); + if relinked(&w.paint, &map) != x.paint { + return None; + } + let mut restore = vec![]; + for (&l, &t) in ours.iter().zip(&theirs) { + let ok = match (links.get(l), lib_by_name.get(l).filter(|b| b.global || b.spot)) { + (Some(to), _) => to == t, + (None, None) => l == t, + (None, Some(b)) => match by_name.get(t) { + Some(y) => l == t && y.paint == b.paint && same_kind(y, b), + None if l == t && !group_names.contains(t) => { + if !picked_names.contains(l) { + restore.push(l.to_string()); + } + true + } + None => false, + }, + }; + if !ok { + return None; + } + } + Some(restore) + }; + // `paint` is `w`'s paint with the colors it links to as `links` has them in the document → the + // name of the document's swatch, and the library colors to bring back for it ([`fit`]). + let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| -> Option<(String, Vec<String>)> { + if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { + let target = patternlib::present_pattern(d, src, pattern)?; + return library_pattern_swatch(d, w, &target).map(|n| (n, vec![])); + } + if let Some(restore) = by_name.get(w.name.as_str()).filter(|x| same_color_kind(x, w)).and_then(|x| fit(x, w, links)) { + return Some((w.name.clone(), restore)); + } + if misplaced(&w.paint, links) { + return None; + } + let found = match by_name.get(w.name.as_str()) { Some(_) => numbered(w, paint, links), None if group_names.contains(w.name.as_str()) => numbered(w, paint, links), None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), - }, + }; + found.map(|n| (n, vec![])) }; - let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); // The global or spot color of the document that library color `b` is: its own name, or the // numbered copy of it that adding `b` would find. While no color or color group has its name, // a numbered copy is looked for only when this call does not add `b` under its own name. @@ -1206,14 +1250,47 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } } } + // A color that the art of a picked pattern the document holds takes under another name (a + // numbered copy that the library also names) is the one the picked tints and gradients link + // to, as when the pattern came in, unless this call adds the color itself. The colors the art + // takes are those of an import into a copy of the document, which adds nothing. + if let Some(src) = &patterns + && looked_up.iter().any(|n| !base_names.contains_key(*n)) + { + for (_, w) in &picked { + let Paint::Pattern { pattern, .. } = &w.paint else { continue }; + if patternlib::present_pattern(d, src, pattern).is_none() { + continue; + } + let mut probe: vectorcraft_doc::Document = (**d).clone(); + let Ok((_, _, took)) = patternlib::import(&mut probe, src, pattern) else { continue }; + for (from, to) in took { + let fits = |b: &&Swatch| by_name.get(to.as_str()).is_some_and(|x| (x.global || x.spot) && x.paint == b.paint && same_kind(x, b)); + if looked_up.contains(from.as_str()) && !picked_names.contains(from.as_str()) && lib_by_name.get(from.as_str()).is_some_and(fits) { + base_names.entry(from).or_insert(to); + } + } + } + } // Library name → the name of the document's swatch. let mut existing: Vec<(String, String)> = vec![]; let mut fresh = vec![]; + // The library colors that the document's tints and gradients found here link to by name while + // the document has no swatch of that name (one deleted without unlinking them): they come back + // under their own names. + let mut restore: Vec<String> = vec![]; for &(group, w) in &picked { // A tint or gradient is compared with its colors linked to the names they have here. let paint = relinked(&w.paint, &base_names); match there(w, &paint, &base_names) { - Some(name) => existing.push((w.name.clone(), name)), + Some((name, back)) => { + existing.push((w.name.clone(), name)); + for n in back { + if !restore.contains(&n) { + restore.push(n); + } + } + } None => fresh.push((group, w)), } } @@ -1230,7 +1307,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { }; let mut links: HashMap<String, String> = existing.iter().filter(|(l, n)| base_of(l, n)).cloned().collect(); links.extend(base_names); - let added: Vec<(String, String)> = if fresh.is_empty() { + let added: Vec<(String, String)> = if fresh.is_empty() && restore.is_empty() { vec![] } else { let (added, reused, brought) = s.edit("Add to Swatches", |d, _| { @@ -1245,6 +1322,15 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // The swatches the patterns imported in this call brought with their art: (library // name, document name). let mut brought: Vec<(String, String)> = vec![]; + // The colors to bring back come first, under their own names, which no swatch or color + // group of the document has; the tints and gradients added here link to them too. + for n in &restore { + let Some(b) = lib_by_name.get(n.as_str()) else { continue }; + let name = free_in(&mut taken, &b.name); + d.swatches.push(Swatch { name: name.clone(), ..(*b).clone() }); + links.insert(n.clone(), name.clone()); + brought.push((n.clone(), name)); + } // The swatches added here with a link `links` did not name yet: (document name, library // swatch). let mut pending: Vec<(String, &Swatch)> = vec![]; diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 9315eadb06..8e24403d60 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -831,6 +831,80 @@ fn a_numbered_copy_the_library_also_names_is_not_shared() { assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink 3"]), &json!(["Ink 2"])), "{r}"); } +/// A tint of the document whose global color was deleted without unlinking it is the library's +/// tint only with that color: adding the tint brings the color back under its name, listed as +/// added, and the tint links to it again. +#[test] +fn a_library_tint_whose_color_the_document_deleted_brings_the_color_back() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false})); + assert!(doc(&s).swatch("Ink").is_none()); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half"])), "{r}"); + assert!(is_global(&s, "Ink", "#0000ff"), "{r}"); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink"), "{r}"); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}"); +} + +/// A library tint added with a pattern whose art took a numbered copy that the library also names +/// is found again on the next add: the tint links to the copy the art took, and adding the pattern +/// and the tint again adds nothing. +#[test] +fn a_library_tint_linked_to_the_copy_a_pattern_took_is_found_again() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(is_global(&s, &base, "#0000ff"), "{r}"); + let swatches = doc(&s).swatches_iter().count(); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); + assert_eq!(again["added"], json!([]), "{again}"); + assert_eq!(doc(&s).swatches_iter().count(), swatches, "{again}"); + assert_eq!(named_after(&s, "Ink half"), ["Ink half"], "{again}"); + assert_eq!(tint_base(&s, "Ink half"), Some(base), "{again}"); +} + +/// Without a pattern whose art takes it, a numbered copy that the library also names stands for +/// that library swatch alone: the document's tint linked to it is not the library's tint of the +/// color the copy is numbered after. +#[test] +fn a_tint_linked_to_a_copy_the_library_names_is_not_another_colors_tint() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink 2", "tint": 50})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!(r["existing"], json!([]), "{r}"); + let added = r["added"][0].as_str().unwrap_or_default().to_string(); + let base = tint_base(&s, &added).unwrap_or_default(); + assert!(base != "Ink 2" && is_global(&s, &base, "#0000ff"), "{r}"); +} + /// A numbered copy of a color's name that the library also has as a swatch of another color is /// still the copy of the color: adding the color after a pattern brought it under that name adds /// no other copy. diff --git a/docs/mcp.md b/docs/mcp.md index 0a31452419..0de5ad1692 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5809,8 +5809,13 @@ is used as it is. A library tint or gradient whose global or spot color comes in document as such a numbered copy, links to that copy, whether the color is picked before or after it, was added earlier or came with a pattern's art. A library global color is not the document's process color of the same name and paint: it comes in numbered. A global or spot color that a library tint or gradient links to and the document lacks -comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. `added` -lists the colors the pattern's art, a tint or a gradient brings too. A document with +comes in with the tint or gradient, under a numbered name when the document gives its name another swatch. The +document's tint or gradient of the library one's name is that swatch when it links to the copy of the color that the +art of a pattern picked with it takes; a numbered copy that the library also names stands for that library swatch +otherwise. When the document's tint or gradient links to a color the document no longer has (deleted without +unlinking), that color comes back under its own name. A pattern is found again when it was pasted with Add or Merge for all of its colors; one pasted +with Merge for some colors and Add for others is added again as a copy. `added` lists the colors the pattern's art, a +tint or a gradient brings too. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with "`<file>` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. From a71de2dd7a14fdc6e98669f23875f95a86a11d46 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 10:16:36 -0800 Subject: [PATCH 112/126] Swatch libraries: a deleted color a found tint links to keeps its name A numbered copy of a library tint found in the document now brings back the deleted global or spot color it links to, as a tint of the library tint's own name does. A deleted color that the call also picks is added before the other new swatches, so a pattern added earlier in the call cannot give its name to another color and leave the found tint linked to the wrong one. A picked pattern the document already has is probed once: the probe gives both its name in the document and the colors its art takes, instead of a presence check, a second import into a copy and a third presence check. --- crates/engine/src/cmd/patternlib.rs | 25 +++++++++---- crates/engine/src/cmd/swatchlib.rs | 53 ++++++++++++++++++---------- crates/engine/src/tests/swatchlib.rs | 53 ++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index e8cffa24aa..88ec82e145 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -145,11 +145,12 @@ pub(crate) fn imported_name(imported: &Imported, name: &str) -> String { } /// The pattern of `d` that [`import`] of pattern `name` of library `lib` would use without adding -/// anything to `d` → its name in `d`. A pattern whose art uses no other resource is compared as -/// [`existing_pattern`] does. One whose art uses other resources, such as a pattern it is painted -/// with, is imported into a copy of `d` as [`probe_import`] does, so that those resources are -/// compared too. -pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<String> { +/// anything to `d` → its name in `d`, and the swatches of `d` that the art takes under another +/// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is +/// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it +/// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those +/// resources are compared too. +pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> { let gathered = gather(lib, name); let only_pattern = gathered.patterns.len() == 1 && gathered.symbols.is_empty() @@ -161,14 +162,24 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio && gathered.images.is_empty() && gathered.graph_designs.is_empty(); if only_pattern { - return existing_pattern(d, lib, name); + return existing_pattern(d, lib, name).map(|target| (target, vec![])); } // Without a pattern to reuse, the document is not copied. if !has_candidate(d, lib, name) { return None; } let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?; - (imported.added == 0).then(|| imported_name(&imported, name)) + if imported.added != 0 { + return None; + } + let took = imported + .renamed + .iter() + .filter(|r| r["kind"] == "swatch") + .filter_map(|r| Some((r["from"].as_str()?.to_string(), r["to"].as_str()?.to_string()))) + .filter(|(_, to)| d.swatches_iter().any(|w| w.name == *to)) + .collect(); + Some((imported_name(&imported, name), took)) } /// Whether `d` has a pattern that importing pattern `name` of `lib` can reuse: one under that name diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 48413d99a8..d0fbd1e0e0 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1169,8 +1169,18 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { .any(|n| !links.contains_key(n) && by_name.contains_key(n) && lib_by_name.get(n).is_some_and(|b| b.global || b.spot)) }; let picked_names: HashSet<&str> = picked.iter().map(|(_, w)| w.name.as_str()).collect(); + // The picked patterns the document already has, each probed once: library pattern name → its + // name in the document and the colors of the document its art takes under other names. + let mut present: HashMap<&str, Option<(String, patternlib::SwatchNames)>> = HashMap::new(); + if let Some(src) = &patterns { + for (_, w) in &picked { + let Paint::Pattern { pattern, .. } = &w.paint else { continue }; + present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern)); + } + } // Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors - // linked to swatches of the document → the library's global and spot colors to bring back. + // linked to swatches of the document → the library's global and spot colors to bring back, + // those this call picks included. // `x` shows `w`'s paint with each color linked to: the name `links` gives it; its own name when // that is the document's color of the library color's paint and kind; or, for a library color // the document has under no name, that color's own name, which then comes in under it. @@ -1192,9 +1202,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { (None, Some(b)) => match by_name.get(t) { Some(y) => l == t && y.paint == b.paint && same_kind(y, b), None if l == t && !group_names.contains(t) => { - if !picked_names.contains(l) { - restore.push(l.to_string()); - } + restore.push(l.to_string()); true } None => false, @@ -1209,9 +1217,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // `paint` is `w`'s paint with the colors it links to as `links` has them in the document → the // name of the document's swatch, and the library colors to bring back for it ([`fit`]). let there = |w: &Swatch, paint: &Paint, links: &HashMap<String, String>| -> Option<(String, Vec<String>)> { - if let (Paint::Pattern { pattern, .. }, Some(src)) = (&w.paint, &patterns) { - let target = patternlib::present_pattern(d, src, pattern)?; - return library_pattern_swatch(d, w, &target).map(|n| (n, vec![])); + if let (Paint::Pattern { pattern, .. }, Some(_)) = (&w.paint, &patterns) { + let (target, _) = present.get(pattern.as_str())?.as_ref()?; + return library_pattern_swatch(d, w, target).map(|n| (n, vec![])); } if let Some(restore) = by_name.get(w.name.as_str()).filter(|x| same_color_kind(x, w)).and_then(|x| fit(x, w, links)) { return Some((w.name.clone(), restore)); @@ -1224,7 +1232,12 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { None if group_names.contains(w.name.as_str()) => numbered(w, paint, links), None => (w.name == REGISTRATION && d.swatch(&w.name).is_some_and(|x| x.paint == *paint)).then(|| w.name.clone()), }; - found.map(|n| (n, vec![])) + // A numbered copy brings back the colors it links to that the document deleted, as a + // swatch of `w`'s own name does. + found.map(|n| { + let back = by_name.get(n.as_str()).and_then(|x| fit(x, w, links)).unwrap_or_default(); + (n, back) + }) }; // The global or spot color of the document that library color `b` is: its own name, or the // numbered copy of it that adding `b` would find. While no color or color group has its name, @@ -1254,17 +1267,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // numbered copy that the library also names) is the one the picked tints and gradients link // to, as when the pattern came in, unless this call adds the color itself. The colors the art // takes are those of an import into a copy of the document, which adds nothing. - if let Some(src) = &patterns - && looked_up.iter().any(|n| !base_names.contains_key(*n)) - { + if looked_up.iter().any(|n| !base_names.contains_key(*n)) { for (_, w) in &picked { let Paint::Pattern { pattern, .. } = &w.paint else { continue }; - if patternlib::present_pattern(d, src, pattern).is_none() { - continue; - } - let mut probe: vectorcraft_doc::Document = (**d).clone(); - let Ok((_, _, took)) = patternlib::import(&mut probe, src, pattern) else { continue }; - for (from, to) in took { + let Some(Some((_, took))) = present.get(pattern.as_str()) else { continue }; + for (from, to) in took.iter().cloned() { let fits = |b: &&Swatch| by_name.get(to.as_str()).is_some_and(|x| (x.global || x.spot) && x.paint == b.paint && same_kind(x, b)); if looked_up.contains(from.as_str()) && !picked_names.contains(from.as_str()) && lib_by_name.get(from.as_str()).is_some_and(fits) { base_names.entry(from).or_insert(to); @@ -1279,6 +1286,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { // the document has no swatch of that name (one deleted without unlinking them): they come back // under their own names. let mut restore: Vec<String> = vec![]; + // Those that this call picks: they are added first, so that they keep their names, which the + // art of a pattern added before them could otherwise take. + let mut reserved: HashSet<String> = HashSet::new(); for &(group, w) in &picked { // A tint or gradient is compared with its colors linked to the names they have here. let paint = relinked(&w.paint, &base_names); @@ -1286,7 +1296,9 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { Some((name, back)) => { existing.push((w.name.clone(), name)); for n in back { - if !restore.contains(&n) { + if picked_names.contains(n.as_str()) { + reserved.insert(n); + } else if !restore.contains(&n) { restore.push(n); } } @@ -1294,6 +1306,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { None => fresh.push((group, w)), } } + if !reserved.is_empty() { + let (first, rest): (Vec<_>, Vec<_>) = fresh.into_iter().partition(|(_, w)| reserved.contains(&w.name)); + fresh = first; + fresh.extend(rest); + } let undo_before = s.doc()?.history.undo.len(); // Library name → the name it got in the document. The colors the patterns brought that no // library swatch of this call stands for are added too; they are listed after the others and diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 8e24403d60..fc450ebc95 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -852,6 +852,55 @@ fn a_library_tint_whose_color_the_document_deleted_brings_the_color_back() { assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Ink half"])), "{again}"); } +/// A numbered tint of the document whose global color was deleted without unlinking it is the +/// library's tint only with that color: adding the tint brings the color back under its name. +#[test] +fn a_numbered_tint_whose_color_the_document_deleted_brings_the_color_back() { + let mut s = session(); + let id = tinted_ink_library_and_a_red_ink(&mut s); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Ink half 2", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.delete", json!({"names": ["Ink"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!(["Ink"]), &json!(["Ink half 2"])), "{r}"); + assert!(is_global(&s, "Ink", "#0000ff"), "{r}"); + assert_eq!(tint_base(&s, "Ink half 2").as_deref(), Some("Ink"), "{r}"); +} + +/// A deleted color that a document tint found here links to keeps its name when the call also +/// picks it, so a pattern added earlier in the call whose art brings another color of a taken +/// name does not take that name first. +#[test] +fn a_deleted_color_a_found_tint_links_to_keeps_its_name_beside_a_pattern() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#00ff00", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 half", "swatch": "Ink 2", "tint": 50})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink 2 half", "Ink 2"]})); + assert!(r["existing"].as_array().is_some_and(|a| a.contains(&json!("Ink 2 half"))), "{r}"); + assert_eq!(tint_base(&s, "Ink 2 half").as_deref(), Some("Ink 2"), "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint(); + let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") }; + let green = swatch.clone().unwrap_or_default(); + assert!(is_global(&s, &green, "#00ff00"), "{r}"); +} + /// A library tint added with a pattern whose art took a numbered copy that the library also names /// is found again on the next add: the tint links to the copy the art took, and adding the pattern /// and the tint again adds nothing. @@ -875,6 +924,10 @@ fn a_library_tint_linked_to_the_copy_a_pattern_took_is_found_again() { let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); let base = tint_base(&s, "Ink half").unwrap_or_default(); assert!(is_global(&s, &base, "#0000ff"), "{r}"); + // The pattern's art and the tint link to the same color. + let fill = doc(&s).pattern("Tiles").unwrap().art[0].appearance.fill_paint(); + let Paint::Solid { swatch, .. } = &fill else { panic!("the tile is filled with a color: {fill:?}") }; + assert_eq!(swatch.as_deref(), Some(base.as_str()), "{r}"); let swatches = doc(&s).swatches_iter().count(); let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink half"]})); assert_eq!(again["added"], json!([]), "{again}"); From 540711e1a5a82f7852c7b4a0629bd948061bf304 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 10:23:48 -0800 Subject: [PATCH 113/126] PSD import: masks that hide a layer's drawn pixels or a pass-through group hide all of it A layer's mask now hides all of it when it is 0 over every pixel that isn't fully transparent, so a shallow knockout whose mask and transparency leave nothing drawn no longer drops the adjustment layers kept below it. A pass-through group whose mask hides all of it no longer counts its layers as drawing, or its adjustment layers as kept, when deciding which adjustment layers above it change what is below the group. --- crates/engine/src/cmd/fileio/psdlayers.rs | 59 ++++++++++++++----- .../engine/src/cmd/fileio/tests_psdlayers.rs | 49 ++++++++++++++- 2 files changed, 93 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index d6719d45ea..59ead541d6 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -1162,11 +1162,13 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { } /// Does record `i` have a layer mask, switched on, that hides all of it? For a layer with stored - /// pixels, other than an adjustment layer, the mask is 0 over all of them; for a group, an - /// adjustment layer and a layer that stores no pixels, which can change pixels anywhere below - /// them, it is 0 everywhere, the value outside it included. A mask is read only when it can hide - /// all of it, once. `false` when it has none, or it can't be read within the memory allowed or - /// is damaged (drawing it says so). `group` says the record opens a group. + /// pixels, other than an adjustment layer, the mask is 0 over all of them that aren't fully + /// transparent (over all of them when their transparency can't be read within the memory + /// allowed); for a group, an adjustment layer and a layer that stores no pixels, which can + /// change pixels anywhere below them, it is 0 everywhere, the value outside it included. A mask + /// is read only when it can hide all of it, once. `false` when it has none, or it can't be read + /// within the memory allowed or is damaged (drawing it says so). `group` says the record opens + /// a group. fn masked_out(&self, i: usize, group: bool) -> Result<bool, String> { if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { return Ok(out); @@ -1183,16 +1185,42 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { || area.is_some_and(|a| m.bounds.left <= a.left && m.bounds.top <= a.top && a.right <= m.bounds.right && a.bottom <= m.bounds.bottom) }); let out = can_hide && self.has_mask(Some(i))? && self.mask_fits(i, 0)? && { - // This read isn't counted against the import's allowance: the mask is read again, and - // counted, where the layer is drawn or its opacity mask is made. + // Its transparency, when it stores one that can be read beside the mask. + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let (w, rows) = rec.bounds.size(); + let row = row_bytes(w, self.h.depth); + let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { + Some((_, data)) + if area.is_some() + && !rec.draws_nothing() + && !rec.color_over_canvas() + && w <= max_side + && rows <= max_side + && self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? => + { + layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + } + _ => None, + }; + // Is its pixel at `x`, `y`, inside `area`, fully transparent? + let transparent = |x: i64, y: i64| { + alpha.as_ref().is_some_and(|plane| { + let (dx, dy) = ((x - i64::from(rec.bounds.left)) as usize, (y - i64::from(rec.bounds.top)) as usize); + plane.get(dy * row..(dy + 1) * row).is_some_and(|r| byte(sample(r, dx, self.h.depth, false)) == 0) + }) + }; + // These reads aren't counted against the import's allowance: the mask and the + // transparency are read again, and counted, where the layer is drawn or its opacity + // mask is made. let spent = self.spent.get(); let read = self.mask(i, false); self.spent.set(spent); match read { - // Its values outside `area` hide nothing of it. - Ok(Some((left, top, m, _))) => { - m.enumerate_pixels().all(|(x, y, p)| p.0[0] == 0 || area.is_some_and(|a| !inside(a, left + i64::from(x), top + i64::from(y)))) - } + // Its values outside `area`, and over its fully transparent pixels, hide nothing of it. + Ok(Some((left, top, m, _))) => m.enumerate_pixels().all(|(x, y, p)| { + let (x, y) = (left + i64::from(x), top + i64::from(y)); + p.0[0] == 0 || area.is_some_and(|a| !inside(a, x, y)) || transparent(x, y) + }), _ => false, } }; @@ -1564,7 +1592,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to /// change what is below the group), those kept in the visible pass-through groups of `out` - /// included. + /// included, except groups whose layer mask hides all of them. fn pending(&self, out: &[Unit<'_>], level: Level) -> Result<Vec<usize>, String> { let mut records = vec![]; if level != Level::Pass { @@ -1574,7 +1602,9 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { if self.adjustment(&u.body)?.is_some() { records.push(u.record); - } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) { + } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + && !u.mask_of.map(|g| self.masked_out(g, true)).transpose()?.unwrap_or(false) + { records.extend(self.leading(items)?.0); } } @@ -1614,7 +1644,8 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { records.push(i); } } - Some(children) if r.blend == Blend::Pass && keeps => { + // A pass-through group whose layer mask hides all of it draws and changes nothing. + Some(children) if r.blend == Blend::Pass && keeps && !self.masked_out(i, true)? => { let (inner, inner_draws) = self.leading(children)?; records.extend(inner); draws |= inner_draws; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index bc66cb717c..4f1777c323 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -18,6 +18,8 @@ struct L { rect: [i32; 4], /// Red, green, blue and alpha, the same for every pixel. rgba: [u8; 4], + /// The alpha of each pixel, in place of `rgba`'s, stored raw. + alpha: Option<Vec<u8>>, blend: &'static [u8; 4], opacity: u8, clipped: bool, @@ -40,6 +42,7 @@ fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L { name, rect, rgba, + alpha: None, blend: b"norm", opacity: 255, clipped: false, @@ -151,6 +154,12 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> { .filter(|_| !l.bare) .map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip))) .collect(); + if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) { + *d = vec![0, 0]; + for &p in pixels { + d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + } + } let mut mask = vec![]; if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { let mut d = vec![0, 0]; @@ -1810,7 +1819,9 @@ fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() /// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in /// a pass-through group still changes what is below the group, and a shallow knockout hidden that -/// way merges nothing, so the adjustment layers below it stay kept. +/// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it +/// when it hides each pixel that isn't fully transparent. The layers in a pass-through group hidden +/// that way don't count as drawing below an adjustment layer above the group. #[test] fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; @@ -1845,11 +1856,47 @@ fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_gr group("Folder", b"pass"), dodge(), ]; + // A knockout whose mask hides each pixel it doesn't leave transparent. + let half = L { alpha: Some(vec![255, 0]), mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 255])), ..layer("Cut", [0, 0, 1, 2], [0, 0, 255, 255]) }; + let mut transparent_knockout = masked_knockout.clone(); + transparent_knockout[5] = knockout(half, 1, 255); + // A pass-through group its mask hides, below Invert in a pass-through group, with a layer drawn + // above that group, under Posterize. + let masked_pass = [ + under(), + group_end(), + group_end(), + group_end(), + photo(), + black(group("Hidden", b"pass")), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + // Invert in a pass-through group its mask hides keeps nothing above that group: Posterize + // merges with the layer below it, as with no such group. + let masked_invert = [ + under(), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + black(group("Hidden", b"pass")), + layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; let cases = [ ("layer", &masked_layer[..], inverted), ("covered layer", &covered_layer[..], inverted), ("group", &masked_group[..], inverted), ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ("pass-through group", &masked_pass[..], [[0, 0, 255, 255], [255, 255, 255, 255]]), + ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 255, 255], [10, 20, 30, 255]]), ]; let rows = |layers: &[L]| { let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); From 869105e1287418b1ff28ad80fc66a85b617aeda5 Mon Sep 17 00:00:00 2001 From: Terra854 <bentinner@yahoo.com.sg> Date: Sun, 22 Nov 2026 02:28:30 +0800 Subject: [PATCH 114/126] Images: read BMP density through craft-image-codecs (#9028) --- crates/doc/src/ppi.rs | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/ppi.rs b/crates/doc/src/ppi.rs index 5c3bd24b53..3477935a06 100644 --- a/crates/doc/src/ppi.rs +++ b/crates/doc/src/ppi.rs @@ -159,12 +159,8 @@ fn webp(b: &[u8]) -> Option<(f64, f64)> { } fn bmp(b: &[u8]) -> Option<(f64, f64)> { - // BITMAPINFOHEADER (40 bytes or longer) at 14: pixels per metre at +24 and +28. - if le32(b, 14)? < 40 { - return None; - } - let ppm = |at| le32(b, at).filter(|v| (1..=i32::MAX as u32).contains(v)).map(per_metre); - Some((ppm(38)?, ppm(42)?)) + let (x, y) = craft_image_codecs::bmp_probe::pixels_per_meter(b)?; + Some((per_metre(x.unsigned_abs()), per_metre(y.unsigned_abs()))) } /// Pixels per metre for a resolution in pixels per inch (the unit `pHYs` stores). @@ -241,6 +237,35 @@ mod tests { assert_eq!(crc32(&[b"IEND"]), 0xAE42_6082); } + #[test] + fn bmp_resolution_keeps_fractional_axes_and_rounds_near_whole_ppi() { + let bmp = bmp_resolution_header(108, 6001, 11811); + let (horizontal, vertical) = resolution(&bmp).expect("recorded physical resolution"); + assert!((horizontal - 152.4254).abs() < 1e-9); + assert_eq!(vertical, 300.0); + } + + #[test] + fn bmp_resolution_requires_complete_positive_density_in_range() { + let bmp = bmp_resolution_header(40, 3937008, 6001); + assert_eq!(resolution(&bmp).map(|(x, _)| x), Some(100_000.0)); + for len in 0..bmp.len() { + assert_eq!(resolution(&bmp[..len]), None, "only {len} header bytes"); + } + for (dib_size, x, y) in [(12, 11811, 11811), (40, -1, 11811), (40, 11811, 0), (40, 1, 11811), (40, 11811, 3937009)] { + assert_eq!(resolution(&bmp_resolution_header(dib_size, x, y)), None, "DIB {dib_size}, density {x} by {y}"); + } + } + + fn bmp_resolution_header(dib_size: u32, x: i32, y: i32) -> [u8; 46] { + let mut header = [0; 46]; + header[..2].copy_from_slice(b"BM"); + header[14..18].copy_from_slice(&dib_size.to_le_bytes()); + header[38..42].copy_from_slice(&x.to_le_bytes()); + header[42..46].copy_from_slice(&y.to_le_bytes()); + header + } + /// RIFF chunk `ty` holding `data`, padded to an even length. fn riff_chunk(ty: &[u8; 4], len: u32, data: &[u8]) -> Vec<u8> { let mut out = [ty.as_slice(), &len.to_le_bytes(), data].concat(); From 3b7c10acc4fab5bfa037193479f1f02e83a9a33c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 10:56:48 -0800 Subject: [PATCH 115/126] PSD import: an adjustment layer in a nested group over drawn layers merges applied A pass-through group's adjustment layers count as kept to change what is below the outer pass-through group only when nothing below that group in the outer one draws, as for adjustment layers directly in the outer group. Before, a layer merged above them for its blend mode merged them applied but the import counted them as not applied. docs/mcp.md now says when a layer's mask hides all of it. --- crates/engine/src/cmd/fileio/psdlayers.rs | 53 ++++++++++++------- .../engine/src/cmd/fileio/tests_psdlayers.rs | 21 ++++++++ docs/mcp.md | 3 +- 3 files changed, 56 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 59ead541d6..75c303cc36 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -1592,9 +1592,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to /// change what is below the group), those kept in the visible pass-through groups of `out` - /// included, except groups whose layer mask hides all of them. + /// included: from the first one with nothing that draws below it in `out`, as [`Self::leading`] + /// keeps them. A group whose layer mask hides all of it keeps none. fn pending(&self, out: &[Unit<'_>], level: Level) -> Result<Vec<usize>, String> { - let mut records = vec![]; + let (mut records, mut draws) = (vec![], false); if level != Level::Pass { return Ok(records); } @@ -1602,15 +1603,41 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { if self.adjustment(&u.body)?.is_some() { records.push(u.record); - } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + continue; + } + if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + && (!draws || !records.is_empty()) && !u.mask_of.map(|g| self.masked_out(g, true)).transpose()?.unwrap_or(false) { - records.extend(self.leading(items)?.0); + let (inner, inner_draws) = self.leading(items)?; + records.extend(inner); + draws |= inner_draws; + continue; } + draws = draws || self.unit_draws(u)?; } Ok(records) } + /// Does unit `u` draw? An adjustment layer, a layer that draws nothing or whose pixels are all + /// transparent, a group of such layers, and a unit whose layer mask hides all of it, don't. + fn unit_draws(&self, u: &Unit<'_>) -> Result<bool, String> { + let draws = match &u.body { + Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, + Body::Group(_, items) => self.draws(items)?, + // Clipped layers merged with a base that has no pixels have none either. + Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), + }; + // A base merged with the layers clipped to it isn't checked: its canvas may reach past the + // base's own pixels. + let hidden = |m: usize| match &u.body { + Body::Layer(_) => self.masked_out(m, false), + Body::Group(..) => self.masked_out(m, true), + Body::Merged(_) => Ok(false), + }; + Ok(draws && !u.mask_of.map(hidden).transpose()?.unwrap_or(false)) + } + /// The adjustment layers the import applies that a pass-through group with the layers `items` /// keeps to change what is below it: from the first one with nothing that draws below it in the /// group (hidden and clipped layers, other adjustment layers, layers and groups at 0 opacity, and @@ -1899,24 +1926,10 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { if u.opacity <= 0.0 { return Ok(()); } + // A unit that draws nothing has nothing to change. let mut below = false; for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { - let draws = match &b.body { - // An adjustment layer, a layer that draws nothing or whose pixels are all - // transparent, or a group of such layers, has nothing to change. - Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, - Body::Group(_, items) => self.draws(items)?, - // Clipped layers merged with a base that has no pixels have none either. - Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), - }; - // One whose layer mask hides all of it has nothing to change either. A base merged with - // the layers clipped to it isn't checked: its canvas may reach past the base's own pixels. - let hidden = |m: usize| match &b.body { - Body::Layer(_) => self.masked_out(m, false), - Body::Group(..) => self.masked_out(m, true), - Body::Merged(_) => Ok(false), - }; - below = below || (draws && !b.mask_of.map(hidden).transpose()?.unwrap_or(false)); + below = below || self.unit_draws(b)?; } // Kept below it in the group, or in a pass-through group below it there. let pending = !self.pending(out, level)?.is_empty(); diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 4f1777c323..56322787da 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1785,6 +1785,27 @@ fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() { } } +/// An adjustment layer in a pass-through group, over a layer drawn below that group in an outer +/// pass-through group, isn't kept to change what is below the outer group: a layer merged above +/// them for its mode merges it applied, and the import doesn't count it as not applied. The gray +/// 100 inverts to 155. +#[test] +fn an_adjustment_layer_in_a_group_over_a_drawn_layer_merges_applied() { + let layers = [ + group_end(), + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Top")), [[155, 155, 155, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); +} + /// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a /// pass-through group, directly or in a pass-through group inside it, still changes what is below /// the group. diff --git a/docs/mcp.md b/docs/mcp.md index d1e8f49dd7..504eab27ae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10919,7 +10919,8 @@ The rest are VectorCraft's own rules: transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such - layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + layers, nor a layer or group whose layer mask hides all of it, for a layer a mask of 0 over each of its pixels that + isn't fully transparent) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to From f72c56711ab40746b9e858e9af5f32a6e02590fc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Sat, 21 Nov 2026 14:16:05 -0500 Subject: [PATCH 116/126] doc: share PNG pHYs chunk writing via craft-image-codecs (craft-libs#785) (#9033) --- Cargo.lock | 112 +++++++++++++++++++++++++++++++++--------- Cargo.toml | 2 +- crates/doc/src/ppi.rs | 28 ++--------- 3 files changed, 94 insertions(+), 48 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b8995c19ea..35e3fc469e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1032,6 +1032,14 @@ name = "craft-codepage" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +[[package]] +name = "craft-dds" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "rayon", +] + [[package]] name = "craft-dds" version = "0.1.0" @@ -1128,12 +1136,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" dependencies = [ - "craft-dds", - "craft-jpeg", - "craft-metadata", - "craft-tiff", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "crc32fast", "exr", "flate2", @@ -1152,6 +1160,41 @@ dependencies = [ "zune-jpegxl", ] +[[package]] +name = "craft-image-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +dependencies = [ + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "crc32fast", + "exr", + "flate2", + "half", + "hayro-jpeg2000", + "image", + "image-webp", + "jpeg-encoder", + "png 0.18.1", + "rayon", + "serde_json", + "thiserror 2.0.21", + "tiff", + "zune-core", + "zune-jpeg", + "zune-jpegxl", +] + +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-jpeg" version = "0.1.0" @@ -1181,6 +1224,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "brotli-decompressor 6.3.2", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-metadata" version = "0.1.0" @@ -1188,7 +1243,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db39 dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "quick-xml 0.41.0", "serde", ] @@ -1300,7 +1355,7 @@ name = "craft-svg" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "craft-xml", "data-url", "flate2", @@ -1316,6 +1371,15 @@ dependencies = [ "vectorcraft-pathops 0.18.0", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3#ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -6689,7 +6753,7 @@ name = "vectorcraft-affinity" version = "0.24.1" dependencies = [ "craft-affinity", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "crc32fast", "proptest", "vectorcraft-affinity", @@ -6719,7 +6783,7 @@ name = "vectorcraft-cad" version = "0.24.1" dependencies = [ "craft-dxf", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-plotter", "image", "kurbo 0.13.1", @@ -6774,7 +6838,7 @@ name = "vectorcraft-doc" version = "0.24.1" dependencies = [ "chrono", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-stream-codecs", "flate2", "image", @@ -6794,7 +6858,7 @@ dependencies = [ name = "vectorcraft-effects" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-svg", "image", "kurbo 0.13.1", @@ -6819,7 +6883,7 @@ dependencies = [ "chrono", "craft-cdr", "craft-docpath", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-jxl", "craft-proof", "craft-stream-codecs", @@ -6877,7 +6941,7 @@ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-pdf", "craft-ps", "craft-stream-codecs", @@ -6957,7 +7021,7 @@ dependencies = [ name = "vectorcraft-mcp" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "image", "log", "proptest", @@ -6977,7 +7041,7 @@ dependencies = [ name = "vectorcraft-metafile" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-metafile", "image", "kurbo 0.13.1", @@ -7018,7 +7082,7 @@ version = "0.24.1" dependencies = [ "aes", "chrono", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-pdf", "craft-stream-codecs", "craft-xml", @@ -7053,7 +7117,7 @@ dependencies = [ name = "vectorcraft-plugins" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-vectorcraft-format", "log", "rustix 1.1.6", @@ -7075,10 +7139,10 @@ name = "vectorcraft-render" version = "0.24.1" dependencies = [ "craft-gif", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-psd", "craft-stream-codecs", - "craft-tiff", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "flate2", "image", "jpeg-encoder", @@ -7114,7 +7178,7 @@ name = "vectorcraft-svg" version = "0.24.1" dependencies = [ "craft-docpath", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-mime", "craft-svg", "data-url", @@ -7144,7 +7208,7 @@ dependencies = [ name = "vectorcraft-testkit" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "fax", "kurbo 0.13.1", "proptest", @@ -7195,7 +7259,7 @@ dependencies = [ name = "vectorcraft-tools" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "kurbo 0.13.1", "serde", "serde_json", @@ -7212,7 +7276,7 @@ dependencies = [ name = "vectorcraft-trace" version = "0.24.1" dependencies = [ - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "image", "kurbo 0.13.1", "serde", @@ -7227,7 +7291,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", - "craft-image-codecs", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-keymap", "craft-ui", "craft-update", diff --git a/Cargo.toml b/Cargo.toml index 9c933c3549..eb196e3294 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,7 +40,7 @@ craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ba25ccd233934d1b2f74e3c0f235168bf5f13ef3" } craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] } diff --git a/crates/doc/src/ppi.rs b/crates/doc/src/ppi.rs index 3477935a06..560c2d08ba 100644 --- a/crates/doc/src/ppi.rs +++ b/crates/doc/src/ppi.rs @@ -169,6 +169,7 @@ pub fn pixels_per_metre(ppi: f64) -> u32 { } /// PNG CRC-32 (the polynomial ZIP uses) of `parts` read one after another. +#[cfg(test)] fn crc32(parts: &[&[u8]]) -> u32 { let mut crc = !0u32; for &b in parts.iter().flat_map(|p| p.iter()) { @@ -182,33 +183,14 @@ fn crc32(parts: &[&[u8]]) -> u32 { /// A whole `pHYs` chunk (length, type, data, CRC) declaring `x` × `y` pixels per inch. pub fn phys_chunk(x: f64, y: f64) -> Vec<u8> { - let [x, y] = [x, y].map(|v| pixels_per_metre(v).to_be_bytes()); - // x, y, unit 1 = metre. - let data = [x.as_slice(), y.as_slice(), &[1]].concat(); - let mut out = Vec::with_capacity(21); - out.extend_from_slice(&9u32.to_be_bytes()); - out.extend_from_slice(b"pHYs"); - out.extend_from_slice(&data); - out.extend_from_slice(&crc32(&[b"pHYs", &data]).to_be_bytes()); - out + let ppm = (pixels_per_metre(x).max(1), pixels_per_metre(y).max(1)); + craft_image_codecs::raw_metadata::png_pixels_per_meter_chunk(ppm).map_or_else(|_| Vec::new(), |chunk| chunk.to_vec()) } /// `png` with a `pHYs` chunk declaring `ppi` right after the header (any existing one is replaced). pub fn with_png_resolution(png: &[u8], (x, y): (f64, f64)) -> Vec<u8> { - let Some(head) = be32(png, 8).and_then(|len| slice(png, 0, 20usize.checked_add(len as usize)?)) else { return png.to_vec() }; - let chunk = phys_chunk(x, y); - let mut out = Vec::with_capacity(png.len() + chunk.len()); - out.extend_from_slice(head); - out.extend_from_slice(&chunk); - let mut at = head.len(); - while let Some(chunk) = be32(png, at).and_then(|len| slice(png, at, 12usize.checked_add(len as usize)?)) { - if chunk.get(4..8) != Some(b"pHYs") { - out.extend_from_slice(chunk); - } - at += chunk.len(); - } - out.extend_from_slice(png.get(at..).unwrap_or_default()); - out + let resolution = (pixels_per_metre(x), pixels_per_metre(y)); + craft_image_codecs::raw_metadata::with_png_pixels_per_meter(png, resolution, png.len().saturating_add(21)).unwrap_or_else(|_| png.to_vec()) } #[cfg(test)] From 81c7578cf01626292cd481f9d1ba7659c1c71732 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 08:02:16 -0800 Subject: [PATCH 117/126] Pen: Quick Pen shows a protractor around an arc's center and snaps to its ticks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from where the arc starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when the tick lies within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps its arc size, so its end does not snap. Shift does not constrain Quick Pen points, so it does not change the snapping. The protractor, its 15° step and the snapping are VectorCraft's own behavior. The Smart Guides targets now also report whether a point landed on one of them (`Targets::snap_hit`), so a target whose label or line is hidden still takes precedence over a tick. Adds tests for the arc's circle, the tick snapping by drag and by click and its precedence, and the protractor during a drag and while hovering. Also adds tests of existing Quick Pen behavior: a point snapping to a Smart Guide, and the distance label shown while hovering. --- crates/engine/src/tests/quickpen.rs | 205 +++++++++++++++++++++++++++- crates/tools/src/guides/snap.rs | 8 ++ crates/tools/src/guides/targets.rs | 26 ++-- crates/tools/src/quickpen.rs | 168 +++++++++++++++++++++-- crates/tools/src/quickpen/tests.rs | 90 +++++++++++- docs/mcp.md | 9 ++ docs/target-app-parity.md | 1 + 7 files changed, 483 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index f14be809b4..c6174aa19f 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point, SubPath}; -use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; +use vectorcraft_tools::{Mods, Overlay, PointerEvent, PointerKind, ToolKey}; use crate::tooling::ViewInfo; use crate::*; @@ -43,13 +43,20 @@ fn pt(x: f64, y: f64) -> Point { } fn press(s: &mut Session, pts: &[(f64, f64)]) { - let v = view(); - s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap(); + press_in(s, pts, view()); +} + +fn press_in(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo) { + press_with(s, pts, v, Mods::default()); +} + +fn press_with(s: &mut Session, pts: &[(f64, f64)], v: ViewInfo, m: Mods) { + s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m), v).unwrap(); for &(x, y) in &pts[1..] { - s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y).with_mods(m), v).unwrap(); } let l = pts[pts.len() - 1]; - s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m), v).unwrap(); } fn click(s: &mut Session, x: f64, y: f64) { @@ -505,6 +512,194 @@ fn a_click_on_an_open_end_continues_the_path() { assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]); } +/// With Smart Guides on, a click near another path's anchor puts the point on that anchor; with +/// them off, the point stays where the click was. +#[test] +fn a_point_snaps_to_a_smart_guide() { + for (guides, want) in [(true, pt(300.0, 300.0)), (false, pt(302.0, 301.0))] { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 500, "y2": 450})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + let v = ViewInfo { smart_guides: guides, ..Default::default() }; + press_in(&mut s, &[(100.0, 100.0)], v); + press_in(&mut s, &[(302.0, 301.0)], v); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert!(drawn.1.subpaths[0].anchors.last().unwrap().p.distance(want) < 1e-9, "{guides}"); + } +} + +/// A point 100 pt from (200, 100) and 30.5° below the +x direction a path from (100, 100) ends in: +/// a continuous arc to it sweeps 61°. +fn arc_end_61() -> Point { + let half = 30.5f64.to_radians(); + pt(200.0 + 100.0 * half.cos(), 100.0 + 100.0 * half.sin()) +} + +/// The protractor's 60° tick for the arc to [`arc_end_61`]: on the same circle, a 60° sweep. +fn tick_60() -> Point { + let r = 50.0 / 30.5f64.to_radians().sin(); + pt(200.0 + r * 30f64.to_radians().cos(), 100.0 + r * 30f64.to_radians().sin()) +} + +/// A path from (100, 100) to (200, 100) drawn with Quick Pen, the action then a continuous arc. +fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { + quick_pen(s); + press_in(s, &[(100.0, 100.0)], v); + press_in(s, &[(200.0, 100.0)], v); + key(s, ToolKey::AltTap); +} + +/// The last point of the path the tool drew (any other path is a two-point line). +fn drawn_end(s: &Session) -> Point { + let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); + drawn.1.subpaths[0].anchors.last().unwrap().p +} + +/// A continuous arc dragged to end 61° round goes onto the protractor's 60° tick with Smart Guides +/// on, also with Shift held, which does not constrain Quick Pen points; with them off it ends at +/// the pointer. A Smart Guide in reach (another path's anchor) wins over the tick, also with its +/// label hidden, and so do Snap to Grid and Snap to Pixel. +#[test] +fn a_continuous_arc_end_snaps_to_the_protractor() { + let at = arc_end_61(); + let anchor = pt(at.x + 0.2, at.y + 0.15); + let fresh = session(); + let g = &fresh.doc().unwrap().doc.grid; + let step = g.spacing / g.subdivisions.max(1) as f64; + let on_grid = pt((at.x / step).round() * step, (at.y / step).round() * step); + let on_pixel = pt(at.x.round(), at.y.round()); + let shift = Mods { shift: true, ..Default::default() }; + // (Smart Guides, the other path, Snap to Grid, Snap to Pixel, Anchor/Path Labels, mods, where + // the end goes, the pointer) + let cases = [ + (true, false, false, false, true, Mods::default(), tick_60(), at), + (true, false, false, false, true, shift, tick_60(), at), + (false, false, false, false, true, Mods::default(), at, at), + (true, true, false, false, true, Mods::default(), anchor, at), + (true, false, true, false, true, Mods::default(), on_grid, on_grid), + (true, false, false, true, true, Mods::default(), on_pixel, on_pixel), + // Exactly on the anchor, which shows no guide with the labels off. + (true, true, false, false, false, Mods::default(), anchor, anchor), + ]; + for (guides, other, grid, pixel, labels, m, want, pointer) in cases { + let mut s = session(); + s.prefs.anchor_path_labels = labels; + if other { + s.execute("shape.line", &json!({"x1": anchor.x, "y1": anchor.y, "x2": 600, "y2": anchor.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + let v = ViewInfo { smart_guides: guides, snap_to_grid: grid, snap_to_pixel: pixel, ..Default::default() }; + continuous_arc_after_a_line(&mut s, v); + press_with(&mut s, &[(280.0, 140.0), (pointer.x, pointer.y)], v, m); + let end = drawn_end(&s); + assert!(end.distance(want) < 1e-6, "{guides} {other} {grid} {pixel} {labels} {m:?}: {end:?}"); + } +} + +/// With Smart Guides on, a click without a drag puts a continuous arc's end on the protractor's +/// tick; after Alt switches to a sharp-corner arc, a click at the same place puts the end at the +/// pointer. +#[test] +fn a_click_puts_a_continuous_arc_end_on_a_tick() { + let at = arc_end_61(); + let v = ViewInfo::default(); + for (taps, want) in [(0, tick_60()), (1, at)] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + press_in(&mut s, &[(at.x, at.y)], v); + let end = drawn_end(&s); + assert!(end.distance(want) < 1e-6, "{taps}: {end:?}"); + } +} + +/// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt +/// switches the action, the same hover puts it beside the pointer. +#[test] +fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() { + let at = arc_end_61(); + let tick = tick_60(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + let label = |s: &mut Session| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + let off = label(&mut s).unwrap() - tick; + assert!(off.x > 0.0 && (off.x - off.y).abs() < 1e-9, "the label sits diagonally off the tick: {off:?}"); + for _ in 0..2 { + key(&mut s, ToolKey::AltTap); + assert!((label(&mut s).unwrap() - off).distance(at) < 1e-9, "{:?}", s.tool_options()["action"]); + } +} + +/// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none. +#[test] +fn an_arc_drag_shows_the_protractor() { + let mut s = session(); + quick_pen(&mut s); + let protractors = |s: &mut Session| s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); + for (action, shown) in [("line", 0), ("continuousArc", 1), ("sharpArc", 1)] { + key(&mut s, ToolKey::Escape); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 150.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 180.0), view()).unwrap(); + assert_eq!(protractors(&mut s), shown, "{action}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + } +} + +/// While hovering, the piece the next click adds shows its protractor beside the rubber band, and +/// neither shows with the Pen tool's rubber band preference off; a line has no protractor. (Smart +/// Guides are off, so no guide paths show.) +#[test] +fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() { + for (rubber_band, action, paths) in [(true, "continuousArc", 2), (true, "line", 1), (false, "continuousArc", 0)] { + let mut s = session(); + s.prefs.pen_rubber_band = rubber_band; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + let shown = s.overlays(view()).iter().filter(|o| matches!(o, Overlay::Path { .. })).count(); + assert_eq!(shown, paths, "{rubber_band} {action}"); + } +} + +/// With Measurement Labels on, hovering after the path's last point shows the distance label +/// beside the pointer; with them off, no label shows. +#[test] +fn hovering_shows_the_distance_label() { + for labels in [true, false] { + let mut s = session(); + s.prefs.measurement_labels = labels; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 200.0), view()).unwrap(); + let o = s.overlays(view()); + let label = o.iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }); + assert_eq!(label.is_some(), labels); + if let Some(p) = label { + assert!(p.x > 300.0 && p.y > 200.0, "beside the pointer: {p:?}"); + } + } +} + /// `path.quickPen` makes a new path with the current paint, or a black stroke without any. #[test] fn path_quick_pen_makes_a_stroked_path() { diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index de09341bc7..948f5668b9 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -493,6 +493,14 @@ impl DrawSnap { t.nearest_point(p, tol).is_some_and(|(a, _)| at(a)) || t.crossing(p, tol).is_some_and(at) } + /// Whether a point at `p` leaving `from` lands on one of the targets the last hover or press + /// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides + /// off, with no targets, and while pixels or the grid snap instead. + pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool { + let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false }; + cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2 + } + /// The guides of the last snap. pub fn guides(&self) -> &[Overlay] { &self.guides diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 94344aab2c..5f30ce3a7c 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -778,27 +778,35 @@ impl Targets { /// that way into line with the nearest target; else, before lining up, it lands on a /// construction guide through it, where a target's line crosses the guide if one does nearby. pub fn snap_from(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec<Overlay>) { + let (q, guides, _) = self.snap_hit(p, from, tol); + (q, guides) + } + + /// [`Self::snap_from`], and whether `p` landed on a target (an anchor or center, a crossing, + /// a segment, a construction guide or a target's line), whether or not its guides show. A + /// point Shift kept to its angle without lining up with a target landed on none. + pub(crate) fn snap_hit(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec<Overlay>, bool) { if let Some(f) = from && let Some(q) = f.constrained(p) { return match self.slide(f.at, q - f.at, q, tol, true) { - Some((q, target)) => (q, self.lined_up(q, target)), - None => (q, vec![]), + Some((q, target)) => (q, self.lined_up(q, target), true), + None => (q, vec![], false), }; } if let Some((q, k)) = self.nearest_point(p, tol) { - return (q, self.label(q, k.label()).into_iter().collect()); + return (q, self.label(q, k.label()).into_iter().collect(), true); } if let Some(q) = self.crossing(p, tol) { - return (q, self.label(q, "intersect").into_iter().collect()); + return (q, self.label(q, "intersect").into_iter().collect(), true); } if let Some(f) = from.filter(|f| f.contact) && let Some((q, perpendicular, dir)) = self.touching(f.at, p, tol) { - return (q, self.touch_guides(f.at, q, perpendicular, dir, tol)); + return (q, self.touch_guides(f.at, q, perpendicular, dir, tol), true); } if let Some(q) = self.on_segment(p, tol) { - return (q, self.label(q, Kind::Edge.label()).into_iter().collect()); + return (q, self.label(q, Kind::Edge.label()).into_iter().collect(), true); } // A construction guide through the point it leaves, else a dragged segment's extension: // it lands on the guide, sliding into line with a target crossing it nearby. @@ -809,8 +817,8 @@ impl Targets { { let construction = |q: Point| Overlay::Line { a: at, b: q, color: self.style.color, dashed: false }; return match self.slide(at, dir, q, tol, false) { - Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect()), - None => (q, vec![construction(q)]), + Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect(), true), + None => (q, vec![construction(q)], true), }; } let mut out = p; @@ -840,7 +848,7 @@ impl Targets { if aligned { ov.extend(self.label(out, "align")); } - (out, ov) + (out, ov, aligned) } /// Where a line from `at` through a point near `p` touches a target segment: square to it diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 6368ba160b..d542af832c 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -12,18 +12,27 @@ //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. +//! +//! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a +//! protractor around the arc's center: a tick across its circle every 15° from where the arc +//! starts, a longer one every 90°, and one where it ends. The piece the next click adds shows its +//! protractor only while the Pen tool's rubber band preference shows that piece. With Smart Guides +//! on, the end of a continuous arc goes onto the nearest tick of that protractor when the tick lies +//! within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither +//! the grid nor pixels snap drawn points. A sharp-corner arc sweeps its arc size, so its end is not +//! snapped to a tick. Shift does not constrain Quick Pen points, so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave}; use crate::pen::{continue_from, open_end_at}; -use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The tool's id. pub const ID: &str = "quickPen"; @@ -36,6 +45,10 @@ pub const TURN_STEP: f64 = 15.0; /// The smallest and largest arc size (degrees). pub const MIN_TURN: f64 = 1.0; pub const MAX_TURN: f64 = 359.0; +/// Degrees between the protractor's ticks, and the steps a continuous arc's sweep snaps to. +pub const TICK_STEP: f64 = 15.0; +/// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. +const TICK_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight @@ -190,6 +203,80 @@ pub fn append(sp: &mut SubPath, piece: &Piece) -> bool { true } +/// The circle an arc piece lies on: its center and radius, the point the arc starts from, and the +/// arc's signed sweep (radians; positive bulges to the left of the direction drawn). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ArcCircle { + pub center: Point, + pub radius: f64, + pub start: Point, + pub sweep: f64, +} + +/// The circle of the arc `piece` adds at the end of `sp`, as [`append`] draws it. None for a line, +/// a piece that ends where `sp` does, and a circle whose center or radius is past the document's +/// coordinate limit. +pub fn arc_circle(sp: &SubPath, piece: &Piece) -> Option<ArcCircle> { + let a = sp.anchors.last()?.p; + let c = piece.to - a; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return None; + } + let s = turn_of(sp, piece, a, piece.to)?; + let half = s.abs() / 2.0; + let radius = l / (2.0 * half.sin()); + // The center lies on the chord's perpendicular bisector, on the side away from the bulge for + // less than a half circle and on the bulge's side for more. + let center = a + c / 2.0 + rot(c / l, FRAC_PI_2) * (radius * half.cos() * s.signum()); + (radius <= MAX_COORD && center.x.abs() <= MAX_COORD && center.y.abs() <= MAX_COORD).then_some(ArcCircle { center, radius, start: a, sweep: s }) +} + +/// The protractor tick nearest the end of a continuous arc ending at `piece.to`: the point on the +/// arc's circle ([`arc_circle`]) where the sweep is a whole number of [`TICK_STEP`]s. None for +/// other pieces, an arc without a circle, a sweep that rounds to nothing or to a whole circle, and +/// a tick past the document's coordinate limit. +pub fn tick_end(sp: &SubPath, piece: &Piece) -> Option<Point> { + if piece.stroke != Stroke::ContinuousArc { + return None; + } + let arc = arc_circle(sp, piece)?; + let step = TICK_STEP.to_radians(); + let s = (arc.sweep / step).round() * step; + (s.abs() > step / 2.0 && s.abs() < 2.0 * PI - step / 2.0) + .then(|| arc.center + rot(arc.start - arc.center, s)) + .filter(|b| b.x.abs() <= MAX_COORD && b.y.abs() <= MAX_COORD) +} + +/// The protractor around `arc`'s center: a tick across its circle every [`TICK_STEP`] from where +/// the arc starts, twice as long every 90°, and one where the arc ends. +fn protractor(cx: &ToolContext, arc: &ArcCircle) -> BezPath { + let step = TICK_STEP.to_radians(); + let out = (arc.start - arc.center) / arc.radius; + let ticks = (arc.sweep.abs() / step + 1e-9).floor() as usize; + let mut bp = BezPath::new(); + let mut tick = |angle: f64, long: bool| { + let d = rot(out, angle); + let half = cx.tol(if long { 2.0 * TICK_PX } else { TICK_PX }); + bp.move_to(arc.center + d * (arc.radius - half)); + bp.line_to(arc.center + d * (arc.radius + half)); + }; + let per_right_angle = (90.0 / TICK_STEP).round() as usize; + for k in 0..=ticks { + tick(arc.sweep.signum() * k as f64 * step, k % per_right_angle == 0); + } + if arc.sweep.abs() - ticks as f64 * step > 1e-6 { + tick(arc.sweep, false); + } + bp +} + +/// The last two of the first `kept` points of `sp`: where the piece after them starts, and the +/// direction it arrives in. +fn tail(sp: &SubPath, kept: usize) -> Option<SubPath> { + Some(SubPath::new(sp.anchors.get_range(kept.saturating_sub(2)..kept)?, false)) +} + /// Closes `sp`: a last point that lies on the first joins it (the first point takes its incoming /// handle); otherwise a straight segment closes the path. Fewer than two points stay open. pub fn close(sp: &mut SubPath) { @@ -284,11 +371,15 @@ pub struct QuickPenTool { press: Option<Press>, hover: Option<Point>, snap: DrawSnap, + /// The pointer while it hovers, and whether it lies on a Smart Guide target ([`Self::landed`]); + /// `hover` is where Smart Guides put it. The protractor's tick is applied when the point is + /// used ([`Self::hover_end`]), for the action chosen then. A press clears it. + pointer: Option<(Point, bool)>, } impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default() } + Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default(), pointer: None } } } @@ -375,11 +466,16 @@ impl QuickPenTool { return vec![]; } // The snapping leaves from the point before the piece being dragged, as the press found it. - let from = self.drawing.as_ref().and_then(|dr| { - let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?; - sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact()) - }); + let before = self.before_piece(); + let from = before.as_ref().and_then(|sp| sp.anchors.last()).map(|a| Leave::segment(cx, a.p, false).without_contact()); let q = self.snap.drag(cx, p, from.as_ref()); + let q = match (&before, self.drawing.as_ref().and_then(|dr| dr.pieces.last())) { + (Some(sp), Some(piece)) => { + let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + self.on_tick(cx, sp, *piece, p, q, landed) + } + _ => q, + }; let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; if last.to == q { return vec![]; @@ -388,6 +484,40 @@ impl QuickPenTool { vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] } + /// `q`, where the last snap put the end of `piece` drawn after `sp` (the pointer being at `p`), + /// moved onto the protractor's nearest tick ([`tick_end`]) when Smart Guides are on, the tick + /// lies within the snapping tolerance of the pointer, and nothing else snapped the point: the + /// snap left it where the pointer is, the pointer is on no Smart Guide target (shown or not, + /// `landed`), and neither the grid nor pixels snap drawn points. + fn on_tick(&self, cx: &ToolContext, sp: &SubPath, piece: Piece, p: Point, q: Point, landed: bool) -> Point { + if landed || !cx.smart_guides || q != p || cx.snap_to_grid || cx.snaps_to_pixel(PixelOp::Drawing) { + return q; + } + tick_end(sp, &Piece { to: q, ..piece }).filter(|b| b.distance(q) <= cx.tol(cx.snapping_tolerance)).unwrap_or(q) + } + + /// Whether the pointer at `p`, which the last snap left in place at `q`, lies on a Smart Guide + /// target leaving `from`, shown or not ([`DrawSnap::lands_on_target`]). A point the snap moved + /// is not asked about, since a tick applies only to a point left in place. + fn landed(&self, cx: &ToolContext, p: Point, q: Point, from: Option<&Leave>) -> bool { + q == p && self.snap.lands_on_target(cx, p, from) + } + + /// Where the next click's piece after `sp` ends while the pointer hovers: the hover's snapped + /// point, on the protractor's tick when [`Self::on_tick`] puts it there. None before the + /// pointer moves after a press. + fn hover_end(&self, cx: &ToolContext, sp: &SubPath) -> Option<Point> { + let ((p, landed), q) = (self.pointer?, self.hover?); + Some(self.on_tick(cx, sp, self.piece_to(q), p, q, landed)) + } + + /// During a press that adds a piece: the points before that piece, as the press found them + /// (the last two, see [`tail`]). + fn before_piece(&self) -> Option<SubPath> { + let dr = self.drawing.as_ref()?; + tail(dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?, *dr.kept.last()?) + } + /// Draws the path again after its last piece changed: a preview while a press draws that /// piece, else a step of its own. fn redraw(&self) -> Vec<Action> { @@ -434,6 +564,8 @@ impl QuickPenTool { } let from = self.leave(cx).map(|l| l.1); let q = self.snap.press(cx, p, &[id], from.as_ref()); + let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + let q = self.on_tick(cx, sp, self.piece_to(q), p, q, landed); let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { dr.push(piece, kept); @@ -459,6 +591,7 @@ impl QuickPenTool { /// Ends the path being drawn; a press that added a piece is taken back. fn end(&mut self) -> Vec<Action> { self.drawing = None; + self.pointer = None; self.snap.clear(); match self.press.take() { Some(pr) if pr.begun => vec![Action::Cancel], @@ -498,13 +631,16 @@ impl Tool for QuickPenTool { match ev.kind { PointerKind::Move => { let (on, from) = self.leave(cx).unzip(); - self.hover = Some(self.snap.hover(cx, p, on.as_slice(), from.as_ref())); + let q = self.snap.hover(cx, p, on.as_slice(), from.as_ref()); + self.hover = Some(q); + self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()))); vec![] } PointerKind::Down => { if self.press.is_some() { return vec![]; } + self.pointer = None; self.press_down(cx, p) } PointerKind::Drag => { @@ -670,13 +806,27 @@ impl Tool for QuickPenTool { fn hover_ended(&mut self, _cx: &ToolContext) { self.hover = None; + self.pointer = None; } fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut o = self.snap.guides().to_vec(); let Some((id, sp)) = self.active(cx) else { return o }; + let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; + // The arc being drawn: the piece a press drags, or the piece the next click adds while the + // rubber band shows it. + let arc = match self.press { + Some(pr) if pr.begun => { + self.before_piece().zip(self.drawing.as_ref().and_then(|dr| dr.pieces.last())).and_then(|(sp, piece)| arc_circle(&sp, piece)) + } + Some(_) => None, + None => end.filter(|_| cx.pen_rubber_band).and_then(|h| arc_circle(sp, &self.piece_to(h))), + }; + if let Some(arc) = arc { + o.push(Overlay::Path { path: protractor(cx, &arc), color: FEEDBACK, width: 1.0, dashed: false }); + } if self.press.is_none() - && let Some(h) = self.hover + && let Some(h) = end.or(self.hover) { if cx.pen_rubber_band && let Some(path) = self.rubber_band(sp, h) diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index f5ab9986d1..5fb23565c5 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; -use vectorcraft_geom::{ParamCurve, PathData}; +use vectorcraft_geom::{ParamCurve, PathData, PathSeg}; fn pt(x: f64, y: f64) -> Point { Point::new(x, y) @@ -196,6 +196,94 @@ fn the_first_click_starts_a_path() { assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); } +/// The circle `arc_circle` gives is the one `append` draws the arc on, for sharp-corner arcs of +/// less and more than a half circle, flipped, and continuous arcs; a line has none. +#[test] +fn the_arc_circle_is_the_circle_the_arc_is_drawn_on() { + let line = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let cases = [ + (start(pt(0.0, 0.0)), Piece { turn: 90.0, ..piece(100.0, 0.0, Stroke::SharpArc) }), + (start(pt(0.0, 0.0)), Piece { turn: 270.0, flip: true, ..piece(100.0, 30.0, Stroke::SharpArc) }), + (line.clone(), piece(200.0, 100.0, Stroke::ContinuousArc)), + (line.clone(), piece(40.0, 60.0, Stroke::ContinuousArc)), + ]; + for (sp, pc) in cases { + let arc = arc_circle(&sp, &pc).unwrap(); + let from = sp.anchors.len() - 1; + let mut drawn = sp.clone(); + append(&mut drawn, &pc); + assert!(on_circle(&drawn, from, arc.center, arc.radius), "{pc:?} {arc:?}"); + assert_eq!(arc.start, sp.anchors.last().unwrap().p); + } + assert!(arc_circle(&line, &piece(200.0, 100.0, Stroke::Line)).is_none()); +} + +/// A continuous arc's end goes to the protractor tick nearest it: on the same circle, where the +/// sweep is a whole number of 15° steps, so an end that sweeps 61° goes to the drawn 60° tick. A +/// sharp-corner arc and a sweep that rounds to a whole circle have no tick to go to. +#[test] +fn a_continuous_arc_end_goes_to_the_nearest_tick() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let half = 30.5f64.to_radians(); + let to = pt(100.0 + 80.0 * half.cos(), 80.0 * half.sin()); + let pc = Piece { to, ..piece(0.0, 0.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 61.0).abs() < 1e-9, "{arc:?}"); + let b = tick_end(&sp, &pc).unwrap(); + let after = arc_circle(&sp, &Piece { to: b, ..pc }).unwrap(); + assert!((after.sweep.to_degrees() - 60.0).abs() < 1e-9, "{after:?}"); + assert!(after.center.distance(arc.center) < 1e-9 && (after.radius - arc.radius).abs() < 1e-9, "the same circle"); + let ticks = protractor(&cx, &arc); + let on_a_tick = ticks.segments().any(|seg| (seg.eval(1.0) - seg.eval(0.0)).cross(b - seg.eval(0.0)).abs() < 1e-6); + assert!(on_a_tick, "{b:?} lies across a drawn tick"); + assert!(tick_end(&sp, &Piece { stroke: Stroke::SharpArc, ..pc }).is_none()); + // Nearly straight behind: the sweep rounds to 360°. + assert!(tick_end(&sp, &Piece { to: pt(20.0, 0.5), ..pc }).is_none()); +} + +/// An end inside the document's coordinate limit whose tick lies past it has no tick to go to: a +/// 59° sweep whose 60° tick is 0.4 pt past the limit. +#[test] +fn a_tick_past_the_coordinate_limit_is_not_used() { + let x = vectorcraft_doc::MAX_COORD - 87.5; + let sp = build(&start(pt(x - 100.0, 0.0)), &[piece(x, 0.0, Stroke::Line)], false); + let half = 29.5f64.to_radians(); + let pc = Piece { to: pt(x + 100.0 * half.cos(), 100.0 * half.sin()), ..piece(0.0, 0.0, Stroke::ContinuousArc) }; + assert!(pc.to.x < vectorcraft_doc::MAX_COORD); + assert!(tick_end(&sp, &pc).is_none()); + let inside = Piece { to: pt(pc.to.x - 10.0, pc.to.y), ..pc }; + assert!(tick_end(&sp, &inside).is_some(), "a tick inside the limit is used"); +} + +/// The protractor has a tick every 15° of the sweep, each across the arc's circle, the first +/// through the arc's start; a sweep that is not a whole number of steps adds a tick at its end. +#[test] +fn the_protractor_ticks_lie_across_the_arc() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let sp = start(pt(0.0, 0.0)); + for (turn, ticks) in [(90.0, 7), (100.0, 8)] { + let pc = Piece { turn, ..piece(100.0, 0.0, Stroke::SharpArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + let segs: Vec<_> = protractor(&cx, &arc).segments().collect(); + assert_eq!(segs.len(), ticks, "{turn}"); + for seg in &segs { + let (a, b) = (seg.eval(0.0), seg.eval(1.0)); + assert!((a.midpoint(b).distance(arc.center) - arc.radius).abs() < 1e-9); + assert!((b - a).cross(arc.center - a).abs() < 1e-6, "points at the center"); + } + let through = |seg: &PathSeg, q: Point| (seg.eval(1.0) - seg.eval(0.0)).cross(q - seg.eval(0.0)).abs() < 1e-6; + assert!(through(segs.first().unwrap(), arc.start)); + assert!(through(segs.last().unwrap(), pc.to)); + } +} + /// The rubber band previews exactly the piece a click adds. #[test] fn the_rubber_band_is_the_next_piece() { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..65383caa1b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7328,6 +7328,15 @@ arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). +While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a protractor around the arc's +center: a tick across the arc's circle every 15° from where the arc starts, a longer tick every 90°, and one where the +arc ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows +that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same +circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the +point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end +does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The +protractor, its 15° step and the tick snapping are VectorCraft's own behavior. + Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, which can change the document, then returns false and changes nothing more when the Quick Pen tool is not active diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..581f72bb0f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,6 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From 365823add69ec4da79543861fd002d9f09977f77 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 11:52:13 -0800 Subject: [PATCH 118/126] PSD import: masks hide layers and groups by the pixels they draw A layer mask white outside its rectangle now hides a layer when the mask is 0 over every pixel the layer draws, even where the rectangle leaves fully transparent pixels out. A group's mask is checked the same way against the pixels of the group's layers, unless the group holds an adjustment layer or a fill that stores no pixels. A base merged with the layers clipped to it counts as drawing nothing when its mask hides the base. A check that was skipped for lack of memory is made again later instead of being kept. --- crates/engine/src/cmd/fileio/psdlayers.rs | 208 +++++++++++++----- .../engine/src/cmd/fileio/tests_psdlayers.rs | 68 +++++- 2 files changed, 208 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 75c303cc36..75aadb1c01 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -585,6 +585,15 @@ enum Item { Group(usize, Vec<Item>), } +/// The layers of the group of record `g`, looked for in `items` and the groups inside them. +fn find_group(items: &[Item], g: usize) -> Option<&[Item]> { + items.iter().find_map(|item| match item { + Item::Group(i, children) if *i == g => Some(children.as_slice()), + Item::Group(_, children) => find_group(children, g), + Item::Layer(_) => None, + }) +} + fn tree(records: &[Record<'_>]) -> Result<Vec<Item>, String> { let mut stack: Vec<Vec<Item>> = vec![vec![]]; for (i, rec) in records.iter().enumerate() { @@ -913,6 +922,8 @@ impl Notes { struct Builder<'a, F> { h: &'a Header<'a>, records: &'a [Record<'a>], + /// The records as layers and groups (see [`tree`]). + tree: &'a [Item], /// Hidden layers come in, hidden. hidden: bool, max_alloc: u64, @@ -1129,7 +1140,8 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { /// Does record `i` store pixels that are all fully transparent, so that it paints nothing? /// Its transparency is read once. `false` when it stores none, or has no transparency, or its - /// transparency can't be read within the memory allowed or is damaged (drawing it says so). + /// transparency can't be read within the memory allowed or is damaged (drawing it says so); one + /// that didn't fit the memory allowed is read again the next time. fn clear(&self, i: usize) -> Result<bool, String> { if let Some(clear) = self.clear.get(i).and_then(Cell::get) { return Ok(clear); @@ -1143,7 +1155,7 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { let (depth, row) = (self.h.depth, row_bytes(w, self.h.depth)); let bytes = (row as u64).saturating_mul(rows as u64); if bytes > self.room() { - false + return Ok(false); } else { self.spend(bytes)?; match layer_channel(data, rows, row, self.h.psb, depth) { @@ -1161,75 +1173,155 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { Ok(clear) } - /// Does record `i` have a layer mask, switched on, that hides all of it? For a layer with stored - /// pixels, other than an adjustment layer, the mask is 0 over all of them that aren't fully - /// transparent (over all of them when their transparency can't be read within the memory - /// allowed); for a group, an adjustment layer and a layer that stores no pixels, which can - /// change pixels anywhere below them, it is 0 everywhere, the value outside it included. A mask - /// is read only when it can hide all of it, once. `false` when it has none, or it can't be read - /// within the memory allowed or is damaged (drawing it says so). `group` says the record opens - /// a group. + /// Does record `i` have a layer mask, switched on, that hides all of it? The mask is 0 over every + /// pixel that isn't fully transparent of the layers whose stored pixels show where it draws: a + /// layer's own, and a group's those of its layers, in the groups inside it too (every pixel of a + /// layer whose transparency can't be read). For an adjustment layer, a layer that stores no + /// pixels and a group with one of those in it, which can change pixels anywhere below them, it + /// is 0 everywhere, the value outside it included. The mask is read once. `false` when it has + /// none, or it can't be read within the memory allowed or is damaged (drawing it says so); a + /// `false` that a read skipped for lack of memory decided is worked out again the next time. + /// `group` says the record opens a group. fn masked_out(&self, i: usize, group: bool) -> Result<bool, String> { if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { return Ok(out); } let rec = self.record(i)?; - // Where it draws: a layer's stored pixels. - let area = (!group && !rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then_some(rec.bounds); - let inside = - |b: Bounds, x: i64, y: i64| (i64::from(b.left)..i64::from(b.right)).contains(&x) && (i64::from(b.top)..i64::from(b.bottom)).contains(&y); - // With a value outside it other than 0, it hides all of it only when it covers all of `area`. - let can_hide = rec.mask.is_some_and(|m| { - let outside = if m.inverted { 255 - m.default } else { m.default }; - outside == 0 - || area.is_some_and(|a| m.bounds.left <= a.left && m.bounds.top <= a.top && a.right <= m.bounds.right && a.bottom <= m.bounds.bottom) - }); - let out = can_hide && self.has_mask(Some(i))? && self.mask_fits(i, 0)? && { - // Its transparency, when it stores one that can be read beside the mask. - let max_side = if self.h.psb { 300_000 } else { 30_000 }; - let (w, rows) = rec.bounds.size(); - let row = row_bytes(w, self.h.depth); - let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { - Some((_, data)) - if area.is_some() - && !rec.draws_nothing() - && !rec.color_over_canvas() - && w <= max_side - && rows <= max_side - && self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? => - { - layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + // The layers whose stored pixels show where it draws, when they all do. + let layers = if group { + match find_group(self.tree, i) { + Some(items) => { + let mut layers = vec![]; + self.painters(items, &mut layers)?.then_some(layers) } - _ => None, - }; - // Is its pixel at `x`, `y`, inside `area`, fully transparent? - let transparent = |x: i64, y: i64| { - alpha.as_ref().is_some_and(|plane| { - let (dx, dy) = ((x - i64::from(rec.bounds.left)) as usize, (y - i64::from(rec.bounds.top)) as usize); - plane.get(dy * row..(dy + 1) * row).is_some_and(|r| byte(sample(r, dx, self.h.depth, false)) == 0) - }) - }; - // These reads aren't counted against the import's allowance: the mask and the - // transparency are read again, and counted, where the layer is drawn or its opacity - // mask is made. + None => None, + } + } else { + (!rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then(|| vec![i]) + }; + let outside = rec.mask.map_or(0, |m| if m.inverted { 255 - m.default } else { m.default }); + // Whether a read skipped for lack of memory decided it. + let mut squeezed = false; + let out = if (layers.is_none() && outside != 0) || !self.has_mask(Some(i))? { + false + } else if !self.mask_fits(i, 0)? { + squeezed = true; + false + } else { + // Not counted against the import's allowance: the mask is read again, and counted, where + // the layer is drawn or its opacity mask is made. let spent = self.spent.get(); let read = self.mask(i, false); self.spent.set(spent); match read { - // Its values outside `area`, and over its fully transparent pixels, hide nothing of it. - Ok(Some((left, top, m, _))) => m.enumerate_pixels().all(|(x, y, p)| { - let (x, y) = (left + i64::from(x), top + i64::from(y)); - p.0[0] == 0 || area.is_some_and(|a| !inside(a, x, y)) || transparent(x, y) - }), - _ => false, + // 0 everywhere hides all of anything. + Ok(Some((_, _, m, 0))) if m.pixels().all(|p| p.0[0] == 0) => true, + Ok(Some(mask)) => match &layers { + Some(layers) => { + let mut hides = true; + for &l in layers { + if !self.hides(i, l, &mask, &mut squeezed)? { + hides = false; + break; + } + } + hides + } + None => false, + }, + Ok(None) => false, + Err(_) => { + squeezed = true; + false + } } }; - if let Some(c) = self.masked_out.get(i) { + if (out || !squeezed) + && let Some(c) = self.masked_out.get(i) + { c.set(Some(out)); } Ok(out) } + /// Push onto `out` the layers in `items` (in the groups inside them too) that store pixels. + /// `false` when one of them can change or draw pixels where it stores none: an adjustment layer, + /// or a fill that stores no pixels. + fn painters(&self, items: &[Item], out: &mut Vec<usize>) -> Result<bool, String> { + for item in items { + match item { + Item::Layer(l) => { + let r = self.record(*l)?; + if r.covers_without_drawing() || r.color_over_canvas() || matches!(r.content, Content::Adjustment(_)) { + return Ok(false); + } + if !r.stores_nothing() { + out.push(*l); + } + } + Item::Group(_, children) => { + if !self.painters(children, out)? { + return Ok(false); + } + } + } + } + Ok(true) + } + + /// Does `mask`, record `i`'s layer mask read with [`Self::mask`], hide every pixel of layer `l` + /// that isn't fully transparent? Every pixel counts when `l`'s transparency can't be read beside + /// the mask; `squeezed` is set when that is for lack of memory. + fn hides(&self, i: usize, l: usize, mask: &(i64, i64, image::GrayImage, u8), squeezed: &mut bool) -> Result<bool, String> { + let (left, top, m, outside) = mask; + let (left, top, outside) = (*left, *top, *outside); + let (right, bottom) = (left + i64::from(m.width()), top + i64::from(m.height())); + let rec = self.record(l)?; + let b = rec.bounds; + let (bl, bt, br, bb) = (i64::from(b.left), i64::from(b.top), i64::from(b.right), i64::from(b.bottom)); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let (w, rows) = b.size(); + // The sides are checked first: the row's size could overflow otherwise. + let fits = w <= max_side && rows <= max_side; + let row = if fits { row_bytes(w, self.h.depth) } else { 0 }; + // Its transparency, when it stores one that can be read beside the mask. Not counted against + // the import's allowance: it is read again, and counted, where the layer is drawn. + let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { + Some((_, data)) if fits && !rec.draws_nothing() && !rec.color_over_canvas() => { + if self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? { + layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + } else { + *squeezed = true; + None + } + } + _ => None, + }; + let within = left <= bl && top <= bt && br <= right && bb <= bottom; + if outside != 0 && !within && alpha.is_none() { + return Ok(false); + } + // Its pixels the mask's value outside it can show, or only those under the mask. + let (x0, y0, x1, y1) = if outside != 0 { (bl, bt, br, bb) } else { (bl.max(left), bt.max(top), br.min(right), bb.min(bottom)) }; + for y in y0..y1 { + let line = match &alpha { + Some(plane) => match plane.get((y - bt) as usize * row..((y - bt) as usize + 1) * row) { + Some(r) => Some(r), + None => return Ok(false), + }, + None => None, + }; + for x in x0..x1 { + let under = (left..right).contains(&x) && (top..bottom).contains(&y); + let v = if under { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { outside }; + if v != 0 && line.is_none_or(|r| byte(sample(r, (x - bl) as usize, self.h.depth, false)) != 0) { + return Ok(false); + } + } + } + Ok(true) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1628,12 +1720,13 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { // Clipped layers merged with a base that has no pixels have none either. Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), }; - // A base merged with the layers clipped to it isn't checked: its canvas may reach past the - // base's own pixels. + // A base merged with the layers clipped to it draws within its own pixels, or, when it covers + // the canvas without drawing, anywhere: its mask hides all of it as it hides the base (see + // `base_draws`). let hidden = |m: usize| match &u.body { Body::Layer(_) => self.masked_out(m, false), Body::Group(..) => self.masked_out(m, true), - Body::Merged(_) => Ok(false), + Body::Merged(_) => self.masked_out(m, matches!(self.record(m)?.divider, 1 | 2)), }; Ok(draws && !u.mask_of.map(hidden).transpose()?.unwrap_or(false)) } @@ -2627,6 +2720,7 @@ pub(super) fn import( let mut b = Builder { h: &h, records: &records, + tree: &items, hidden, max_alloc, held: 0, diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 56322787da..46a8f5eb9f 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -99,10 +99,15 @@ fn predict(row: &[u8], depth: u16) -> Vec<u8> { } } -/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped -/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. +/// One sample of `v` at `depth` (in 32 bits, `v` / 255 as a float). +fn sample_of(v: u8, depth: u16) -> Vec<u8> { + if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] } +} + +/// A channel of `n` samples of `v` (see [`sample_of`]) at `depth`, raw, zipped (with prediction +/// when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option<bool>) -> Vec<u8> { - let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }; + let sample = sample_of(v, depth); let row: Vec<u8> = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect(); if let Some(predicted) = zip { let rows = n.checked_div(width).unwrap_or(0); @@ -157,14 +162,14 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec<u8> { if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) { *d = vec![0, 0]; for &p in pixels { - d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + d.extend(sample_of(p, depth)); } } let mut mask = vec![]; if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { let mut d = vec![0, 0]; for &p in pixels { - d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + d.extend(sample_of(p, depth)); } channels.push((-2, d)); for v in [mt, ml, mb, mr] { @@ -1841,8 +1846,10 @@ fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() /// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in /// a pass-through group still changes what is below the group, and a shallow knockout hidden that /// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it -/// when it hides each pixel that isn't fully transparent. The layers in a pass-through group hidden -/// that way don't count as drawing below an adjustment layer above the group. +/// when it hides each of its pixels that isn't fully transparent, and a group's when it hides each +/// such pixel of the group's layers, whatever the mask's value elsewhere; a layer hidden that way +/// hides the layers clipped to it too. The layers in a pass-through group hidden that way don't +/// count as drawing below an adjustment layer above the group. #[test] fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; @@ -1892,7 +1899,7 @@ fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_gr black(group("Hidden", b"pass")), adjustment("Invert", b"nvrt", &[]), group("Inner", b"pass"), - layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass"), dodge(), @@ -1905,19 +1912,58 @@ fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_gr group_end(), adjustment("Invert", b"nvrt", &[]), black(group("Hidden", b"pass")), - layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass"), dodge(), ]; + // A mask over only the pixels that aren't fully transparent, white outside it. + let corner = |l: L| L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..l }; + let half_photo = || L { alpha: Some(vec![255, 0]), ..photo() }; + let corner_layer = [under(), group_end(), corner(half_photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + let corner_group = [ + under(), + group_end(), + group_end(), + half_photo(), + corner(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + // The same mask over a group with a pixel drawn outside it: the group draws there. + let drawn_group = [ + under(), + group_end(), + group_end(), + photo(), + corner(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + // A layer its mask hides, with a layer clipped to it. + let clipped_base = [ + under(), + group_end(), + black(photo()), + L { clipped: true, ..layer("Red", [0, 0, 1, 2], [200, 0, 0, 255]) }, + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; let cases = [ ("layer", &masked_layer[..], inverted), ("covered layer", &covered_layer[..], inverted), ("group", &masked_group[..], inverted), ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), ("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), - ("pass-through group", &masked_pass[..], [[0, 0, 255, 255], [255, 255, 255, 255]]), - ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 255, 255], [10, 20, 30, 255]]), + ("pass-through group", &masked_pass[..], [[0, 0, 85, 255], [255, 255, 255, 255]]), + ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 85, 255], [10, 20, 30, 255]]), + ("layer covered where it draws", &corner_layer[..], inverted), + ("group covered where it draws", &corner_group[..], inverted), + ("group drawn outside its mask", &drawn_group[..], [[10, 20, 30, 255], [155, 155, 155, 255]]), + ("clipped base", &clipped_base[..], inverted), ]; let rows = |layers: &[L]| { let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); From 69dc6f3097cf2766f79f67d3254dd951a6324df2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Sat, 21 Nov 2026 15:24:11 -0500 Subject: [PATCH 119/126] eps: delegate AI editing-data lexer to craft_eps::ai_lex (craft-libs#790) (#9037) --- Cargo.lock | 6 +- Cargo.toml | 2 +- crates/eps/src/import/ai/lex.rs | 561 +------------------------------- 3 files changed, 6 insertions(+), 563 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 35e3fc469e..d294edfdf1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1068,12 +1068,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" +source = "git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e#068e079c7be4b100a8a6b305b31ac881e069727e" [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec" [[package]] name = "craft-font-catalog" @@ -6940,7 +6940,7 @@ dependencies = [ name = "vectorcraft-eps" version = "0.24.1" dependencies = [ - "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=068e079c7be4b100a8a6b305b31ac881e069727e)", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-pdf", "craft-ps", diff --git a/Cargo.toml b/Cargo.toml index eb196e3294..9bc0f9ecb0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,7 +33,7 @@ craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7 craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] } craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e" } # DXF tags, reader and writer (craft-libs#778, #926, #927). craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index a43166ccc9..5da1e6f7be 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -1,562 +1,5 @@ //! The scanner of the editing data: PostScript-like tokens, read line by line. //! -//! - A line starting with `%_` holds tokens like any other line (they are marked [`Token::hidden`]: -//! readers of the printed format skip them as comments). -//! - Any other line starting with `%` is a [`Tok::Comment`] (the section markers). -//! - `%_` later in a line starts tokens too, hidden (a pseudo-comment operator after its -//! operands, as a gradient stop's `… 50 100 %_Bs`: AI7 spec §1.4.3); any other `%` later in a -//! line starts a comment that is skipped, but for a line of hex digits after `%_` (a hidden -//! blend's record), a hidden [`Tok::Comment`]. -//! - The binary image data after `%%BeginData:` is one [`Tok::Data`]; the binary preview of a placed -//! file is one [`Tok::Preview`]. -//! - A document included whole (`%%BeginDocument:` … `%%EndDocument` lines, DSC 3.0 p. 68, nested -//! ones counted, the counted payloads of `%%BeginData:` and `%%BeginBinary:` inside skipped) is -//! one [`Tok::Document`]. +//! Backed by `craft_eps::ai_lex`. -use super::super::lex::{find, hex_decode}; - -/// A token. -#[derive(Clone, Debug, PartialEq)] -pub(super) enum Tok<'a> { - Num(f64), - /// A literal `(…)` string, escapes undone. - Str(Vec<u8>), - /// A hexadecimal `<…>` string. - Hex(Vec<u8>), - /// A literal `/name`. - Name(&'a [u8]), - /// An operator (any other word, `[` and `]` included). - Word(&'a [u8]), - /// A comment line, without its first `%`. - Comment(&'a [u8]), - /// An image's samples: what follows `XI` in a `%%BeginData:` section. - Data(&'a [u8]), - /// A placed file's preview: what is between `%AI26_BeginPlacedObjectPreview` and its end. - Preview(&'a [u8]), - /// A document included whole: what is between `%%BeginDocument:`'s line and the line of the - /// `%%EndDocument` that ends it, or `None` when none does (the rest of the data is skipped). - Document(Option<&'a [u8]>), -} - -#[derive(Clone, Debug, PartialEq)] -pub(super) struct Token<'a> { - pub tok: Tok<'a>, - /// Read from a `%_` line. - pub hidden: bool, -} - -/// A placed file's preview (binary): (begin, end) markers. -const PREVIEW: (&[u8], &[u8]) = (b"%AI26_BeginPlacedObjectPreview", b"%AI26_EndPlacedObjectPreview"); -/// A placed file's markers, which a hidden one has on `%_` lines. -const PLACE: [&[u8]; 2] = [b"%AI5_BeginPlace", b"%AI5_EndPlace"]; -/// A path's note comments, also read on `%_` lines. -const NOTES: [&[u8]; 3] = [b"%AI3_Note:", b"%%Note:", b"%AI5_NoteMore:"]; -/// The markers around a placed file's relative folder, which a hidden one has on `%_` lines too. -const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlacedRelativePath"]; -/// A document included whole: (begin, end) markers. -const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument"); - -/// The line of `src` before the one that starts at `at`, without its line end, when it ends within -/// [`OPERAND_LINE`] bytes of `at` and is no longer than that. -fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> { - let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?; - let end = before.iter().rposition(|b| !is_eol(*b))? + 1; - let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1; - before.get(start..end) -} - -/// The longest line of an image's `XI` operands looked at. -const OPERAND_LINE: usize = 1024; - -/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix] -/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when -/// the alpha count isn't 0, else none (or when the operands aren't of that shape). -fn alpha_bytes(line: &[u8]) -> usize { - let line = line.strip_prefix(b"%_").unwrap_or(line); - let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 }; - let nums: Vec<f64> = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect(); - match (nums.get(4), nums.get(5), nums.get(8)) { - // At most the pixels the reader reads an image with. - (Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize, - _ => 0, - } -} - -/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose -/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line -/// end, or the end of `w`, follows. -fn end_data(w: &[u8]) -> Option<usize> { - const MARK: &[u8] = b"%%EndData"; - let mut first = None; - let mut at = 0; - while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) { - let i = at + i; - let rest = w.get(i + MARK.len()..).unwrap_or_default(); - if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) { - let next = rest.strip_prefix(b"\r").unwrap_or(rest); - let next = next.strip_prefix(b"\n").unwrap_or(next); - let next = next.strip_prefix(b"%_").unwrap_or(next); - if next.starts_with(b"XH") { - return Some(i); - } - first = first.or(Some(i)); - } - at = i + 1; - } - first -} - -fn is_space(b: u8) -> bool { - matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') -} - -fn is_delim(b: u8) -> bool { - matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') -} - -fn is_eol(b: u8) -> bool { - matches!(b, b'\r' | b'\n') -} - -pub(super) struct Lexer<'a> { - src: &'a [u8], - pos: usize, - /// The current line started with `%_`. - hidden: bool, -} - -impl<'a> Lexer<'a> { - pub fn new(src: &'a [u8]) -> Self { - Self { src, pos: 0, hidden: false } - } - - fn peek(&self) -> Option<u8> { - self.src.get(self.pos).copied() - } - - /// The data from where the next token is looked for. - pub fn rest(&self) -> &'a [u8] { - self.src.get(self.pos..).unwrap_or_default() - } - - fn at_line_start(&self) -> bool { - self.pos == 0 || self.src.get(self.pos - 1).is_some_and(|b| is_eol(*b)) - } - - /// The rest of the current line (without its end), the position moved past it. - fn line(&mut self) -> &'a [u8] { - let rest = self.rest(); - let n = rest.iter().position(|b| is_eol(*b)).unwrap_or(rest.len()); - self.pos += n; - rest.get(..n).unwrap_or_default() - } - - /// [`Self::line`], the position moved past its end too (`\r`, `\n` or `\r\n`). - fn whole_line(&mut self) -> &'a [u8] { - let line = self.line(); - if self.peek() == Some(b'\r') { - self.pos += 1; - } - if self.peek() == Some(b'\n') { - self.pos += 1; - } - line - } - - /// Where the next token is looked for. - pub fn offset(&self) -> usize { - self.pos - } - - /// Look for the next token at `pos` again (the end of the data at most). - pub fn seek(&mut self, pos: usize) { - self.pos = pos.min(self.src.len()); - } - - /// The data from `from` to `to` (empty where that isn't in it). - pub fn slice(&self, from: usize, to: usize) -> &'a [u8] { - self.src.get(from..to).unwrap_or_default() - } - - /// Skip past the next `needle` (the end of data that isn't tokens) → what was skipped. - pub fn skip_past(&mut self, needle: &[u8]) -> &'a [u8] { - let rest = self.rest(); - let n = find(rest, needle).map_or(rest.len(), |i| i + needle.len()); - self.pos += n; - rest.get(..n).unwrap_or_default() - } - - /// The next token; `None` at the end. - pub fn next_token(&mut self) -> Option<Token<'a>> { - loop { - let b = self.peek()?; - if is_eol(b) { - self.pos += 1; - self.hidden = false; - continue; - } - if is_space(b) { - self.pos += 1; - continue; - } - if b == b'%' { - let start = self.at_line_start(); - // A pseudo-comment: `%_` at the line's start, or after operands. - if self.rest().starts_with(b"%_") && (start || self.rest().get(2).is_some_and(|b| b.is_ascii_alphabetic())) { - self.pos += 2; - self.hidden = true; - continue; - } - // Right after `%_` a section still starts (a hidden image's data, #1264). - let prefixed = self.hidden && self.pos >= 2 && self.src.get(self.pos - 2..self.pos) == Some(b"%_"); - let line = self.line(); - if (start || prefixed) - && let Some(t) = self.special(line) - { - return Some(Token { hidden: prefixed, ..t }); - } - if start { - return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: false }); - } - // So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. And a - // hidden path's note. - if prefixed && PLACE.iter().chain(&NOTES).chain(&RELATIVE).any(|m| line.starts_with(m)) { - return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); - } - // And a line of hex digits, as a hidden blend's record is written (`%_%4443…` - // after its `XP`), like the plain one on `%` lines. - let digits = line.get(1..).unwrap_or_default(); - if prefixed && !digits.trim_ascii_end().is_empty() && digits.trim_ascii_end().iter().all(u8::is_ascii_hexdigit) { - return Some(Token { tok: Tok::Comment(digits), hidden: true }); - } - // A comment later in a line. - continue; - } - let hidden = self.hidden; - self.pos += 1; - let tok = match b { - b'(' => Tok::Str(self.string()), - b'<' => { - let rest = self.rest(); - let end = rest.iter().position(|b| *b == b'>').unwrap_or(rest.len()); - self.pos += (end + 1).min(rest.len()); - // Malformed digits read as an empty string. - Tok::Hex(rest.get(..end).and_then(hex_decode).unwrap_or_default()) - } - b'[' | b']' | b'{' | b'}' | b')' | b'>' => Tok::Word(self.src.get(self.pos - 1..self.pos).unwrap_or_default()), - b'/' => Tok::Name(self.word()), - _ => { - self.pos -= 1; - let w = self.word(); - match number(w) { - Some(v) => Tok::Num(v), - None => Tok::Word(w), - } - } - }; - return Some(Token { tok, hidden }); - } - } - - /// The token a comment line stands for when it starts a section read differently: image data - /// (`%%BeginData:` followed by `XI`), a placed file's preview and skipped binary sections. - fn special(&mut self, line: &'a [u8]) -> Option<Token<'a>> { - if line.starts_with(PREVIEW.0) { - let from = self.pos; - let after = find(self.rest(), PREVIEW.1).map_or(self.src.len(), |i| self.pos + i); - self.pos = after; - self.line(); - return Some(Token { tok: Tok::Preview(self.slice(from, after)), hidden: false }); - } - if line.starts_with(DOCUMENT.0) { - return Some(Token { tok: Tok::Document(self.document()), hidden: false }); - } - let n = line.strip_prefix(b"%%BeginData:")?; - let n: usize = std::str::from_utf8(n).ok()?.split_whitespace().next()?.parse().ok()?; - // The count starts after the comment's line end character (a following `\n` counts). - let from = self.pos + 1; - let region = self.src.get(from..)?; - let mut skip = region.iter().take_while(|b| is_space(**b)).count(); - // A hidden object's section is on `%_` lines up to its samples: `%_XI`, then `%_%%EndData`. - let hidden = region.get(skip..)?.starts_with(b"%_XI"); - if hidden { - skip += 2; - } else if !region.get(skip..)?.starts_with(b"XI") { - return None; - } - let mut data = from + skip + 2; - match (self.src.get(data), self.src.get(data + 1)) { - (Some(b'\r'), Some(b'\n')) => data += 2, - (Some(b'\r' | b'\n'), _) => data += 1, - _ => {} - } - // The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one - // that a line end or the end of the data follows (samples can hold the marker's bytes). - let declared = from.saturating_add(n).min(self.src.len()).max(data); - // The alpha channel the line before gives the image (its `XI` operands) follows the counted - // samples: the marker is looked for after it. - let line_start = self.pos.saturating_sub(line.len()); - let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start }; - let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes); - let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data); - let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len()); - let end = match self.src.get(start..stop).and_then(end_data) { - Some(i) => start + i, - None => declared, - }; - self.pos = end; - let samples = self.src.get(data..end).unwrap_or_default(); - let samples = if hidden { samples.strip_suffix(b"%_").unwrap_or(samples) } else { samples }; - Some(Token { tok: Tok::Data(samples), hidden: false }) - } - - /// After a `%%BeginDocument:` line: the document up to the start of the `%%EndDocument` line - /// that ends it, the position moved past that line. A `%%BeginDocument:` line inside starts a - /// nested document, and the bytes a `%%BeginData:` or `%%BeginBinary:` line inside counts are - /// skipped (DSC 3.0 pp. 68 and 72): a marker in them ends nothing. `None` when no line ends it: - /// the position moves to the end of the data. - fn document(&mut self) -> Option<&'a [u8]> { - // The rest of the `%%BeginDocument:` line is its end; the line after the document starts - // tokens afresh (not hidden unless it starts with `%_`). - self.whole_line(); - self.hidden = false; - let from = self.pos; - let mut depth = 0usize; - while self.pos < self.src.len() { - let start = self.pos; - // A hidden object's document is on `%_` lines. - let line = self.whole_line(); - let line = line.strip_prefix(b"%_").unwrap_or(line); - if line.starts_with(DOCUMENT.1) { - if depth == 0 { - return Some(self.slice(from, start)); - } - depth -= 1; - } else if line.starts_with(DOCUMENT.0) { - depth = depth.saturating_add(1); - } else if let Some(n) = line.strip_prefix(b"%%BeginData:").or_else(|| line.strip_prefix(b"%%BeginBinary:")) { - self.skip_counted(n); - } - } - None - } - - /// Skip what a `%%BeginData:` or `%%BeginBinary:` comment counts (`n`, its text after the - /// colon): `count [type [Bytes|Lines]]`, bytes unless it says `Lines`. - fn skip_counted(&mut self, n: &[u8]) { - let mut words = std::str::from_utf8(n).unwrap_or_default().split_whitespace(); - let Some(count) = words.next().and_then(|c| c.parse::<usize>().ok()) else { return }; - if words.nth(1).is_some_and(|unit| unit.eq_ignore_ascii_case("lines")) { - for _ in 0..count { - if self.pos >= self.src.len() { - break; - } - self.whole_line(); - } - } else { - // The count starts after the comment's line end, which `document` has passed. - self.pos = self.pos.saturating_add(count).min(self.src.len()); - } - } - - /// A regular token's characters. - fn word(&mut self) -> &'a [u8] { - let start = self.pos; - while let Some(b) = self.peek() { - if is_space(b) || is_delim(b) { - break; - } - self.pos += 1; - } - self.src.get(start..self.pos).unwrap_or_default() - } - - /// A literal string after its `(` (an unterminated one ends with the data). - fn string(&mut self) -> Vec<u8> { - let mut out = vec![]; - let mut depth = 0usize; - while let Some(b) = self.peek() { - self.pos += 1; - match b { - b'(' => { - depth += 1; - out.push(b); - } - b')' if depth == 0 => break, - b')' => { - depth -= 1; - out.push(b); - } - b'\\' => { - let Some(e) = self.peek() else { break }; - self.pos += 1; - match e { - b'n' => out.push(b'\n'), - b'r' => out.push(b'\r'), - b't' => out.push(b'\t'), - b'b' => out.push(8), - b'f' => out.push(12), - b'\r' => { - if self.peek() == Some(b'\n') { - self.pos += 1; - } - } - b'\n' => {} - b'0'..=b'7' => { - let mut v = u32::from(e - b'0'); - for _ in 0..2 { - match self.peek() { - Some(d @ b'0'..=b'7') => { - v = v * 8 + u32::from(d - b'0'); - self.pos += 1; - } - _ => break, - } - } - out.push((v & 0xff) as u8); - } - other => out.push(other), - } - } - _ => out.push(b), - } - } - out - } -} - -/// A finite number token (`12`, `-3.5`, `.5`, `1e-3`), or `None`. -pub(super) fn number(w: &[u8]) -> Option<f64> { - let first = *w.first()?; - if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { - return None; - } - if w.iter().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) { - return None; - } - let v: f64 = std::str::from_utf8(w).ok()?.parse().ok()?; - v.is_finite().then_some(v) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn all(src: &[u8]) -> Vec<Token<'_>> { - let mut l = Lexer::new(src); - std::iter::from_fn(|| l.next_token()).collect() - } - - fn t(tok: Tok<'_>, hidden: bool) -> Token<'_> { - Token { tok, hidden } - } - - #[test] - fn hidden_lines_and_comments() { - let toks = all(b"%AI5_BeginLayer\r\n1 (a\\)b) Ln\r%_/X : ;\n0 %_BS\n<4142>\n"); - assert_eq!( - toks, - vec![ - t(Tok::Comment(b"AI5_BeginLayer"), false), - t(Tok::Num(1.0), false), - t(Tok::Str(b"a)b".to_vec()), false), - t(Tok::Word(b"Ln"), false), - t(Tok::Name(b"X"), true), - t(Tok::Word(b":"), true), - t(Tok::Word(b";"), true), - t(Tok::Num(0.0), false), - // A pseudo-comment operator after its operands. - t(Tok::Word(b"BS"), true), - t(Tok::Hex(b"AB".to_vec()), false), - ] - ); - } - - #[test] - fn a_percent_later_in_a_line_is_a_comment_unless_an_operator_follows_it() { - let toks = all(b"1 % a note (\n2 %_Bs\n3 %_ 4\n"); - let words: Vec<_> = toks.iter().map(|t| (t.tok.clone(), t.hidden)).collect(); - assert_eq!(words, [(Tok::Num(1.0), false), (Tok::Num(2.0), false), (Tok::Word(b"Bs"), true), (Tok::Num(3.0), false)]); - // A hidden line of hex digits (a hidden blend's record) is a comment; other text after - // `%_%` stays skipped. - let toks = all(b"%_%44434241\n%_% not hex\n%_%\n1\n"); - assert_eq!(toks, [t(Tok::Comment(b"44434241"), true), t(Tok::Num(1.0), false)]); - } - - #[test] - fn image_data_is_one_token() { - // The count starts after the comment's `\r`: `\nXI\n` and 3 samples; an alpha channel - // after them isn't counted. - let src = b"[1 0 0 1 0 0] XI\r\n%%BeginData: 7\r\nXI\n(%)A%%EndData\r\nXH\r\n"; - let toks = all(src); - assert!(toks.contains(&t(Tok::Data(b"(%)A"), false)), "{toks:?}"); - assert_eq!(toks.last(), Some(&t(Tok::Word(b"XH"), false))); - // #1264: on `%_` lines too, where the samples would otherwise be read as tokens. - let toks = all(b"%_[1 0 0 1 0 0] XI\r%_%%BeginData: 7\rXI\n(U)A%%EndData\r%_XH\ru\r"); - assert!(toks.contains(&t(Tok::Data(b"(U)A"), true)), "{toks:?}"); - assert_eq!(toks.last(), Some(&t(Tok::Word(b"u"), false)), "{toks:?}"); - // A section of hex lines is comments. - let toks = all(b"%%BeginData: 9 Hex Bytes\r\n%00FF\r\n%%EndData\r\n1\r\n"); - assert_eq!(toks.last(), Some(&t(Tok::Num(1.0), false))); - // On `%_` lines (an opacity mask's image, say) too: a `(` in the samples starts no string. - let toks = all(b"%_XI\r%_%%BeginData: 4\r%_XI\r(\x00\x00\x00%_%%EndData\r%_XH\r1\r"); - assert!(toks.contains(&t(Tok::Data(b"(\x00\x00\x00"), true)), "{toks:?}"); - assert_eq!(toks.last(), Some(&t(Tok::Num(1.0), false))); - } - - #[test] - fn binary_sections_are_one_token() { - let toks = all(b"%AI26_BeginPlacedObjectPreview\r\n2 1 (\x00\xff\r\n%AI26_EndPlacedObjectPreview\r\nN\r\n"); - assert_eq!(toks, vec![t(Tok::Preview(b"\r\n2 1 (\x00\xff\r\n"), false), t(Tok::Word(b"N"), false)]); - let toks = all(b"%%BeginDocument: a.eps\n(\x00 frobnicate\n%%EndDocument\nN\n"); - assert_eq!(toks, vec![t(Tok::Document(Some(b"(\x00 frobnicate\n")), false), t(Tok::Word(b"N"), false)]); - // One that doesn't end takes the rest. - assert_eq!(all(b"%AI26_BeginPlacedObjectPreview\r1 (").len(), 1); - } - - #[test] - fn an_included_document_ends_at_its_own_end_line() { - // A nested document, `%%EndDocument` later in a line and in counted data end nothing; `\r\n`, - // `\r` and `\n` lines alike. - let body = b"1 0 0 setrgbcolor\r\n%%BeginDocument: inner.eps\r(%%EndDocument) pop\r%%EndDocument\r\n\ - %%BeginData: 14 Binary Bytes\n%%EndDocument\n%%BeginBinary: 14\n%%EndDocument\n\ - %%BeginData: 1 Hex Lines\n%%EndDocument\n"; - let mut src = b"%%BeginDocument: outer.eps\r\n".to_vec(); - src.extend_from_slice(body); - src.extend_from_slice(b"%%EndDocument\r\n~\r\n"); - assert_eq!(all(&src), vec![t(Tok::Document(Some(body)), false), t(Tok::Word(b"~"), false)]); - // On a hidden object's `%_` lines. - let toks = all(b"%_%%BeginDocument: a.eps\r%_1 0 0 setrgbcolor\r%_%%EndDocument\r%_~\r"); - assert_eq!(toks, vec![t(Tok::Document(Some(b"%_1 0 0 setrgbcolor\r")), true), t(Tok::Word(b"~"), true)]); - // The line after it is hidden only when it starts with `%_`. - let toks = all(b"%_%%BeginDocument: a.eps\r%_%%EndDocument\rN\r"); - assert_eq!(toks, vec![t(Tok::Document(Some(b"")), true), t(Tok::Word(b"N"), false)]); - } - - #[test] - fn an_included_document_that_doesnt_end_takes_the_rest() { - for src in [&b"%%BeginDocument: a.eps\n%%BeginDocument: b.eps\n%%EndDocument\n~\n"[..], b"%%BeginDocument: a.eps\n%%BeginData: 99999999999\n"] - { - assert_eq!(all(src), vec![t(Tok::Document(None), false)]); - } - } - - #[test] - fn skip_past_data() { - let mut l = Lexer::new(b"/Binary : /ASCII85Decode ,\r\n%_(abc[%\r\n%x~>\r\n%_; 1"); - for _ in 0..4 { - l.next_token(); - } - assert_eq!(l.skip_past(b"~>"), b"\r\n%_(abc[%\r\n%x~>"); - assert_eq!(l.next_token().map(|t| t.tok), Some(Tok::Word(b";"))); - assert_eq!(l.next_token().map(|t| t.tok), Some(Tok::Num(1.0))); - } - - #[test] - fn hostile_input_ends() { - for src in [&b"(unterminated \\"[..], b"<12", b"%%BeginData: 99999999999\r\nXI", b"%%BeginData: 5\rXI\r", b"/", b"1e999 nan"] { - let toks = all(src); - assert!(toks.len() < 10); - } - } -} +pub(super) use craft_eps::ai_lex::{Lexer, Tok, Token, number}; From 91fd78e27a85884c36f6edcaeae5c464cb820802 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 12:33:10 -0800 Subject: [PATCH 120/126] PSD import: looking for drawn pixels takes nothing from the import's allowance Checking whether a layer's pixels are all fully transparent no longer counts its transparency against the memory allowed for the whole import. The layer is counted where it is drawn, so an import that fits no longer fails because the check counted the same pixels first. --- crates/engine/src/cmd/fileio/psdlayers.rs | 13 +++++++------ crates/engine/src/cmd/fileio/tests_psdlayers.rs | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 75aadb1c01..67958a550b 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -1156,13 +1156,14 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> { let bytes = (row as u64).saturating_mul(rows as u64); if bytes > self.room() { return Ok(false); - } else { - self.spend(bytes)?; - match layer_channel(data, rows, row, self.h.psb, depth) { - Ok(plane) => (0..rows) - .all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))), - Err(_) => false, + } + // Not counted against the import's allowance: the transparency is read again, and + // counted, where the layer is drawn. + match layer_channel(data, rows, row, self.h.psb, depth) { + Ok(plane) => { + (0..rows).all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))) } + Err(_) => false, } } _ => false, diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 46a8f5eb9f..09acabbfa0 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -2247,6 +2247,12 @@ fn damaged_layers_never_panic() { assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some()); let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err(); assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); + // Looking through those layers' transparency for pixels that draw, below an adjustment layer, + // takes nothing from the allowance. + let mut clear: Vec<L> = (0..16).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 0])).collect(); + clear.push(adjustment("Invert", b"nvrt", &[])); + let opened = psdlayers::import(&file(8, 8, &clear, 8, false, false), false, 512, cms); + assert!(opened.as_ref().is_ok_and(Option::is_some), "{:?}", opened.err()); } /// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers From fa3c5af490ad255d7fe45255688b19dc91c08de9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 12:37:12 -0800 Subject: [PATCH 121/126] Docs: when a group's mask, or a clipping base's, hides all of it on PSD import --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 504eab27ae..b79832226d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10920,7 +10920,9 @@ The rest are VectorCraft's own rules: that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it, for a layer a mask of 0 over each of its pixels that - isn't fully transparent) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + isn't fully transparent, for a group the same over its layers' pixels, or a mask of 0 everywhere when it holds an + adjustment layer or a fill that stores no pixels, and for a layer with layers clipped to it the same as for the + layer) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to From 88f5ece15be88c335994e730c73832daabaa685c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" <dylan@dylanmtaylor.com> Date: Sat, 21 Nov 2026 15:39:25 -0500 Subject: [PATCH 122/126] svg: cut over CSS transform, CSS string quoting, and symbol unit basis to craft-svg (#9035) * svg: cut over CSS transform, CSS string quoting, and symbol unit basis to craft-svg (#789) * build: repin craft-svg to merged craft-libs main (d20a8248) --- Cargo.lock | 47 +++++++++++++------ Cargo.toml | 2 +- crates/svg/src/css.rs | 25 +--------- crates/svg/src/import/css_transform.rs | 65 +------------------------- crates/svg/src/import/symbol_units.rs | 13 +----- 5 files changed, 38 insertions(+), 114 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d294edfdf1..6a602ed891 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1043,7 +1043,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ "rayon", ] @@ -1163,12 +1163,12 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ - "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", - "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-dds 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", "crc32fast", "exr", "flate2", @@ -1198,7 +1198,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ "thiserror 2.0.21", ] @@ -1239,11 +1239,11 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ "brotli-decompressor 6.3.2", "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", "quick-xml 0.41.0", "serde", ] @@ -1353,10 +1353,10 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" dependencies = [ - "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", - "craft-xml", + "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3)", "data-url", "flate2", "gif", @@ -1380,6 +1380,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1478,6 +1487,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d20a82481b1f7b1d32c818b19c620338af9755d3#d20a82481b1f7b1d32c818b19c620338af9755d3" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -6887,7 +6906,7 @@ dependencies = [ "craft-jxl", "craft-proof", "craft-stream-codecs", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "crc32fast", "encoding_rs", "flate2", @@ -7085,7 +7104,7 @@ dependencies = [ "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ba25ccd233934d1b2f74e3c0f235168bf5f13ef3)", "craft-pdf", "craft-stream-codecs", - "craft-xml", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)", "flate2", "getrandom 0.4.3", "image", diff --git a/Cargo.toml b/Cargo.toml index 9bc0f9ecb0..6056916d75 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,7 +30,7 @@ craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c96 # Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778). craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "9b28b56bc7207ef7ce806f37df72cb94c0ad5c37" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d20a82481b1f7b1d32c818b19c620338af9755d3", features = ["tree"] } craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "068e079c7be4b100a8a6b305b31ac881e069727e" } diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index 2bfa7c5e5c..76069d802a 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -26,28 +26,7 @@ pub(crate) fn declarations<'a>(props: impl IntoIterator<Item = &'a (&'static str /// A CSS string. pub(crate) fn css_string(s: &str) -> String { - quoted(s, '"') -} - -/// `s` as a CSS string in `quote`s. A backslash and the quote are escaped, and so are line breaks -/// and other control characters (a newline would end the string and let the rest be rules) and -/// `<` and `>` (which could end a `<style>` element), as hex escapes. -fn quoted(s: &str, quote: char) -> String { - let mut out = String::with_capacity(s.len() + 2); - out.push(quote); - for c in s.chars() { - match c { - '\\' => out.push_str("\\\\"), - c if c == quote => { - out.push('\\'); - out.push(c); - } - c if c.is_control() || matches!(c, '<' | '>') => out.push_str(&format!("\\{:x} ", u32::from(c))), - c => out.push(c), - } - } - out.push(quote); - out + craft_svg::simple_css::quote_css_string(s, '"') } pub(crate) fn blend_css(b: BlendMode) -> &'static str { @@ -133,7 +112,7 @@ pub(crate) fn font_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { // Only a plain identifier (no leading digit) can be written bare; anything else is quoted. let bare = st.font_family.chars().next().is_some_and(|c| !c.is_ascii_digit() && c != '-') && st.font_family.chars().all(|c| c.is_alphanumeric() || matches!(c, '-' | '_')); - let fam = if !bare { quoted(&st.font_family, '\'') } else { st.font_family.clone() }; + let fam = if !bare { craft_svg::simple_css::quote_css_string(&st.font_family, '\'') } else { st.font_family.clone() }; p.push(("font-family", format!("{fam}{}", generic_fallback(&st.font_family)))); p.push(("font-size", len(st.size * st.v_scale / 100.0))); let (weight, italic) = font_descriptor(st); diff --git a/crates/svg/src/import/css_transform.rs b/crates/svg/src/import/css_transform.rs index dc59b28426..9392cd4aac 100644 --- a/crates/svg/src/import/css_transform.rs +++ b/crates/svg/src/import/css_transform.rs @@ -8,7 +8,6 @@ //! functions SVG lacks (`translateX`, `scaleY`, `skew`…) spelled with SVG's. A value that can't be //! (percentages, `em`, 3D functions) is left as it is. -use std::f64::consts::PI; use std::ops::Range; use craft_svg::tree::usvg::roxmltree; @@ -16,69 +15,7 @@ use craft_svg::tree::usvg::roxmltree; use super::css::XNode; /// The CSS transform `value` in SVG syntax; `None` when it has nothing to rewrite or can't be. -pub(super) fn to_svg(value: &str) -> Option<String> { - let v = value.trim(); - if v.eq_ignore_ascii_case("none") { - return Some("matrix(1 0 0 1 0 0)".into()); - } - let mut out = Vec::new(); - let mut rest = v; - while !rest.trim_start().is_empty() { - rest = rest.trim_start(); - let open = rest.find('(')?; - let close = rest.find(')')?; - let name = rest.get(..open)?.trim().to_ascii_lowercase(); - let args: Vec<&str> = rest.get(open + 1..close)?.split(|c: char| c == ',' || c.is_whitespace()).filter(|a| !a.is_empty()).collect(); - let len = |i: usize| args.get(i).and_then(|a| length(a)); - let ang = |i: usize| args.get(i).and_then(|a| angle(a)); - let num = |i: usize| args.get(i).and_then(|a| a.parse::<f64>().ok()).filter(|n| n.is_finite()); - let f = match (name.as_str(), args.len()) { - ("matrix", 6) => format!("matrix({} {} {} {} {} {})", num(0)?, num(1)?, num(2)?, num(3)?, len(4)?, len(5)?), - ("translate", 1) => format!("translate({} 0)", len(0)?), - ("translate", 2) => format!("translate({} {})", len(0)?, len(1)?), - ("translatex", 1) => format!("translate({} 0)", len(0)?), - ("translatey", 1) => format!("translate(0 {})", len(0)?), - ("scale", 1) => format!("scale({})", num(0)?), - ("scale", 2) => format!("scale({} {})", num(0)?, num(1)?), - ("scalex", 1) => format!("scale({} 1)", num(0)?), - ("scaley", 1) => format!("scale(1 {})", num(0)?), - ("rotate", 1) => format!("rotate({})", ang(0)?), - ("skewx", 1) => format!("skewX({})", ang(0)?), - ("skewy", 1) => format!("skewY({})", ang(0)?), - ("skew", 1) => format!("skewX({})", ang(0)?), - ("skew", 2) => format!("matrix(1 {} {} 1 0 0)", ang(1)?.to_radians().tan(), ang(0)?.to_radians().tan()), - _ => return None, - }; - out.push(f); - rest = rest.get(close + 1..)?; - } - let svg = out.join(" "); - (!out.is_empty() && svg != v).then_some(svg) -} - -/// A length in user units: `px` or unitless. -fn length(a: &str) -> Option<f64> { - let n = a.strip_suffix("px").unwrap_or(a).parse::<f64>().ok()?; - n.is_finite().then_some(n) -} - -/// An angle in degrees. -fn angle(a: &str) -> Option<f64> { - let a = a.to_ascii_lowercase(); - let (n, k) = if let Some(n) = a.strip_suffix("deg") { - (n, 1.0) - } else if let Some(n) = a.strip_suffix("grad") { - (n, 0.9) - } else if let Some(n) = a.strip_suffix("rad") { - (n, 180.0 / PI) - } else if let Some(n) = a.strip_suffix("turn") { - (n, 360.0) - } else { - (a.as_str(), 1.0) - }; - let d = n.parse::<f64>().ok()? * k; - d.is_finite().then_some(d) -} +pub(super) use craft_svg::transform_compat::css_transform_to_svg as to_svg; /// Where CSS can be in `svg`: `style` attribute values and `<style>` contents. fn css_ranges(xml: &roxmltree::Document) -> Vec<Range<usize>> { diff --git a/crates/svg/src/import/symbol_units.rs b/crates/svg/src/import/symbol_units.rs index 78bb34ee19..b3e7b4fb27 100644 --- a/crates/svg/src/import/symbol_units.rs +++ b/crates/svg/src/import/symbol_units.rs @@ -16,17 +16,6 @@ const SHAPES: &[&str] = &["rect", "circle", "ellipse", "line", "image", "use", " /// The elements whose content has lengths of its own kind (or a viewport of its own). const SCOPES: &[&str] = &["symbol", "svg", "pattern", "mask", "clipPath", "marker"]; -/// What a percentage of attribute `name` is of, in a viewport of `w` × `h`: its width, its height, -/// or (a radius) its diagonal over √2. -fn basis(name: &str, w: f64, h: f64) -> Option<f64> { - match name { - "x" | "x1" | "x2" | "cx" | "width" | "rx" => Some(w), - "y" | "y1" | "y2" | "cy" | "height" | "ry" => Some(h), - "r" => Some(((w * w + h * h) / 2.0).sqrt()), - _ => None, - } -} - /// The percentage geometry of shapes in symbols with a `viewBox`, each as (value range, number). pub(super) fn rewrites(xml: &roxmltree::Document) -> Vec<(Range<usize>, String)> { let mut out = Vec::new(); @@ -44,7 +33,7 @@ pub(super) fn rewrites(xml: &roxmltree::Document) -> Vec<(Range<usize>, String)> } for a in n.attributes().filter(|a| a.namespace().is_none()) { let percent = a.value().trim().strip_suffix('%').and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()); - if let (Some(p), Some(of)) = (percent, basis(a.name(), vb.w, vb.h)) { + if let (Some(p), Some(of)) = (percent, craft_svg::doc_style::symbol_percent_basis(a.name(), vb.w, vb.h)) { out.push((a.range_value(), (p / 100.0 * of).to_string())); } } From a99702361a0f4ead3e830dbe6d5f0c21c52ad203 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 13:09:35 -0800 Subject: [PATCH 123/126] Pen: Quick Pen snaps no first continuous arc to a tick and hides a stale hover A continuous arc that starts a path has no direction to follow and sweeps the arc size, as a sharp-corner arc does. Moving its end onto a protractor tick put the end on a circle the drawn arc does not follow, so `tick_end` now gives no tick for it. The hover keeps the snap settings it was made with (`SnapSettings` in guides/snap.rs: the window, zoom, snapping options, tolerances, Alignment Guides and construction angles). After one of them changes under a still pointer, the hover's rubber band, protractor, distance label and Smart Guides are hidden until the pointer moves, also through a press, so the preview shows no point that a click would not place. A press also drops the hover, so after a click puts an arc's end on a tick no preview runs from that end back to the pointer. While the pointer hovers, the tool asks the canvas to hover it again when the view, the document or the selection changes (`wants_rehover`). --- crates/engine/src/tests/quickpen.rs | 89 +++++++++++++++++++++++++++++ crates/tools/src/guides.rs | 2 +- crates/tools/src/guides/snap.rs | 22 +++++++ crates/tools/src/quickpen.rs | 57 +++++++++++++----- crates/tools/src/quickpen/tests.rs | 15 +++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 7 files changed, 178 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index c6174aa19f..bcb90f5249 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -616,6 +616,23 @@ fn a_click_puts_a_continuous_arc_end_on_a_tick() { } } +/// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from +/// the placed end back to where the pointer was; the next move shows the preview again. +#[test] +fn a_click_on_a_tick_leaves_no_preview_back_to_the_pointer() { + let at = arc_end_61(); + let v = ViewInfo::default(); + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), v).unwrap(); + press_in(&mut s, &[(at.x, at.y)], v); + assert!(drawn_end(&s).distance(tick_60()) < 1e-6); + let label = |s: &mut Session| s.overlays(v).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(!label(&mut s), "no distance label back to the pointer"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 300.0), v).unwrap(); + assert!(label(&mut s)); +} + /// Hovering near a tick as a continuous arc puts the distance label beside the tick; after Alt /// switches the action, the same hover puts it beside the pointer. #[test] @@ -640,6 +657,78 @@ fn a_hover_snaps_to_a_tick_only_for_a_continuous_arc() { } } +/// A hover made with Smart Guides off shows nothing once they are turned on under the still +/// pointer, so it shows no tick that a click would not use (another path's anchor under the +/// pointer takes the click). The next move shows the hover again, its label beside the anchor; +/// once Smart Guides are turned off again, its guides are hidden with it, also after a click. +#[test] +fn a_hover_shows_nothing_after_smart_guides_change() { + let at = arc_end_61(); + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": at.x, "y1": at.y, "x2": 600, "y2": at.y})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, off); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), off).unwrap(); + let label = |s: &mut Session, v: ViewInfo| { + s.overlays(v).iter().find_map(|o| match o { + Overlay::Measure { p, .. } => Some(*p), + _ => None, + }) + }; + assert!(label(&mut s, off).is_some()); + assert_eq!(label(&mut s, on), None, "the hover from before the change shows nothing"); + s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); + let off_anchor = label(&mut s, on).unwrap() - at; + assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); + let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); + assert!(!only_points(&mut s, on)); + assert!(only_points(&mut s, off), "only the path's points show"); + // A click before the pointer moves does not bring the stale hover back. + press_in(&mut s, &[(400.0, 300.0)], off); + assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); +} + +/// While the pointer hovers, the tool asks the canvas to hover it again when the view, the document +/// or the selection changes under a still pointer, so the snapped point follows the art; a press +/// stops it until the next move. +#[test] +fn a_hover_is_hovered_again_when_the_art_changes() { + let mut s = session(); + continuous_arc_after_a_line(&mut s, view()); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Move, 280.0, 180.0), view()).unwrap(); + assert!(s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 180.0), view()).unwrap(); + assert!(!s.tool_wants_rehover()); +} + +/// A hover on the path's last point, which another path's anchor shares, shows that anchor's Smart +/// Guide; after Smart Guides are turned off, a click there adds nothing and the guide stays hidden +/// while the button is held and after it is let go. +#[test] +fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { + let off = ViewInfo { smart_guides: false, ..Default::default() }; + let on = ViewInfo::default(); + let mut s = session(); + s.execute("shape.line", &json!({"x1": 200, "y1": 100, "x2": 200, "y2": 400})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + continuous_arc_after_a_line(&mut s, on); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); + let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + assert!(only_points(&mut s, off)); + let steps = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 100.0), off).unwrap(); + assert!(only_points(&mut s, off), "the guide stays hidden while the button is held"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 100.0), off).unwrap(); + assert_eq!(undo_steps(&s), steps, "the click adds nothing"); + assert!(only_points(&mut s, off), "the guide stays hidden"); +} + /// While a press drags an arc, the tool shows its protractor; while it drags a line, it shows none. #[test] fn an_arc_drag_shows_the_protractor() { diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index e9f7bf7318..ccbf258512 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -25,10 +25,10 @@ mod snap; mod targets; pub(crate) use bitangent::TangentLine; -pub(crate) use snap::hold_on_path; pub use snap::{ DEFAULT_CONSTRUCTION_ANGLES, DrawSnap, HandleSnap, Leave, PointSnap, construction_angles, distance_guides, snap_draw, snap_pick, square, }; +pub(crate) use snap::{SnapSettings, hold_on_path}; use targets::Kind; pub use targets::Targets; #[cfg(test)] diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 948f5668b9..0a48b35001 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -376,6 +376,28 @@ impl SnapKey { } } +/// Every setting that can move a snapped drawn point besides the document: the window and the +/// zoom, the options and tolerances [`SnapKey`] holds except the guides' color and labels, and +/// the construction guides' angles a [`Leave::segment`] follows. A tool that keeps a hover's +/// snapped point compares two of these to see whether a click would still snap the same way. +#[derive(PartialEq)] +pub(crate) struct SnapSettings { + screen: Option<ScreenFrame>, + zoom: f64, + view: [bool; 7], + snap_to_glyph: Option<GlyphSnap>, + alignment_lines: bool, + tolerances: [f64; 2], + angles: &'static [f64], +} + +impl SnapSettings { + pub(crate) fn of(cx: &ToolContext) -> Self { + let SnapKey { screen, view, snap_to_glyph, style, tolerances, .. } = SnapKey::of(cx, &[]); + Self { screen, zoom: cx.zoom, view, snap_to_glyph, alignment_lines: style.lines, tolerances, angles: cx.construction_angles } + } +} + /// The part of the document the window shows (none headless: all of it). pub(super) fn visible(cx: &ToolContext) -> Option<Rect> { let s = cx.screen?; diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index d542af832c..1ff691f309 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -19,8 +19,12 @@ //! protractor only while the Pen tool's rubber band preference shows that piece. With Smart Guides //! on, the end of a continuous arc goes onto the nearest tick of that protractor when the tick lies //! within the snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither -//! the grid nor pixels snap drawn points. A sharp-corner arc sweeps its arc size, so its end is not -//! snapped to a tick. Shift does not constrain Quick Pen points, so it does not change the snapping. +//! the grid nor pixels snap drawn points. A sharp-corner arc, and a continuous arc that has no +//! direction to follow, sweep the arc size, so their ends are not snapped to a tick. After a snap +//! setting changes under a still pointer, the hover's preview, protractor, distance label and +//! Smart Guides are hidden until the pointer moves; when the view, the document or the selection +//! changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, +//! so it does not change the snapping. use std::f64::consts::{FRAC_PI_2, PI}; use std::sync::Arc; @@ -30,7 +34,7 @@ use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; -use crate::guides::{DrawSnap, Leave}; +use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -234,12 +238,14 @@ pub fn arc_circle(sp: &SubPath, piece: &Piece) -> Option<ArcCircle> { /// The protractor tick nearest the end of a continuous arc ending at `piece.to`: the point on the /// arc's circle ([`arc_circle`]) where the sweep is a whole number of [`TICK_STEP`]s. None for -/// other pieces, an arc without a circle, a sweep that rounds to nothing or to a whole circle, and -/// a tick past the document's coordinate limit. +/// other pieces, a continuous arc with no direction to follow (it sweeps the arc size, as a +/// sharp-corner arc does), an arc without a circle, a sweep that rounds to nothing or to a whole +/// circle, and a tick past the document's coordinate limit. pub fn tick_end(sp: &SubPath, piece: &Piece) -> Option<Point> { if piece.stroke != Stroke::ContinuousArc { return None; } + arrival(sp)?; let arc = arc_circle(sp, piece)?; let step = TICK_STEP.to_radians(); let s = (arc.sweep / step).round() * step; @@ -371,10 +377,11 @@ pub struct QuickPenTool { press: Option<Press>, hover: Option<Point>, snap: DrawSnap, - /// The pointer while it hovers, and whether it lies on a Smart Guide target ([`Self::landed`]); - /// `hover` is where Smart Guides put it. The protractor's tick is applied when the point is - /// used ([`Self::hover_end`]), for the action chosen then. A press clears it. - pointer: Option<(Point, bool)>, + /// The pointer while it hovers, whether it lies on a Smart Guide target ([`Self::landed`]), and + /// the snap settings then; `hover` is where Smart Guides put it. The protractor's tick is + /// applied when the point is used ([`Self::hover_end`]), for the action chosen then. A press + /// clears it. + pointer: Option<(Point, bool, SnapSettings)>, } impl Default for QuickPenTool { @@ -505,12 +512,22 @@ impl QuickPenTool { /// Where the next click's piece after `sp` ends while the pointer hovers: the hover's snapped /// point, on the protractor's tick when [`Self::on_tick`] puts it there. None before the - /// pointer moves after a press. + /// pointer moves after a press, and while the hover is stale ([`Self::hover_stale`]). fn hover_end(&self, cx: &ToolContext, sp: &SubPath) -> Option<Point> { - let ((p, landed), q) = (self.pointer?, self.hover?); + let (&(p, landed, _), q) = (self.pointer.as_ref()?, self.hover?); + if self.hover_stale(cx) { + return None; + } Some(self.on_tick(cx, sp, self.piece_to(q), p, q, landed)) } + /// Whether the snap settings changed since the pointer last moved: the hover's snapped point + /// and its tick may then not be where a click puts the point, so the hover shows nothing until + /// the pointer moves again. + fn hover_stale(&self, cx: &ToolContext) -> bool { + self.pointer.as_ref().is_some_and(|(_, _, at)| *at != SnapSettings::of(cx)) + } + /// During a press that adds a piece: the points before that piece, as the press found them /// (the last two, see [`tail`]). fn before_piece(&self) -> Option<SubPath> { @@ -633,13 +650,20 @@ impl Tool for QuickPenTool { let (on, from) = self.leave(cx).unzip(); let q = self.snap.hover(cx, p, on.as_slice(), from.as_ref()); self.hover = Some(q); - self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()))); + self.pointer = Some((p, on.is_some() && self.landed(cx, p, q, from.as_ref()), SnapSettings::of(cx))); vec![] } PointerKind::Down => { if self.press.is_some() { return vec![]; } + // The hover shows again when the pointer moves after the press: the point the press + // places can lie on a tick away from it. A stale hover's guides stay hidden, also + // when the press snaps nothing. + if self.hover_stale(cx) { + self.snap.clear(); + } + self.hover = None; self.pointer = None; self.press_down(cx, p) } @@ -809,8 +833,14 @@ impl Tool for QuickPenTool { self.pointer = None; } + /// A hover's snapped point and its tick depend on the art and the view under a still pointer. + fn wants_rehover(&self) -> bool { + self.pointer.is_some() + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { - let mut o = self.snap.guides().to_vec(); + // A stale hover's Smart Guides go with its preview. + let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; let Some((id, sp)) = self.active(cx) else { return o }; let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; // The arc being drawn: the piece a press drags, or the piece the next click adds while the @@ -826,6 +856,7 @@ impl Tool for QuickPenTool { o.push(Overlay::Path { path: protractor(cx, &arc), color: FEEDBACK, width: 1.0, dashed: false }); } if self.press.is_none() + && !self.hover_stale(cx) && let Some(h) = end.or(self.hover) { if cx.pen_rubber_band diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 5fb23565c5..1319948423 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -259,6 +259,21 @@ fn a_tick_past_the_coordinate_limit_is_not_used() { assert!(tick_end(&sp, &inside).is_some(), "a tick inside the limit is used"); } +/// A continuous arc that starts a path has no direction to follow and sweeps the arc size, so its +/// end has no tick to go to: with a 100° arc size, a tick at 105° would move the end off the arc +/// the click draws. +#[test] +fn a_continuous_arc_without_a_direction_has_no_tick() { + let sp = start(pt(0.0, 0.0)); + let pc = Piece { turn: 100.0, ..piece(100.0, 10.0, Stroke::ContinuousArc) }; + let arc = arc_circle(&sp, &pc).unwrap(); + assert!((arc.sweep.to_degrees() - 100.0).abs() < 1e-9, "{arc:?}"); + assert!(tick_end(&sp, &pc).is_none()); + // After a line, the same end has a tick. + let sp = build(&start(pt(-100.0, 0.0)), &[piece(0.0, 0.0, Stroke::Line)], false); + assert!(tick_end(&sp, &pc).is_some()); +} + /// The protractor has a tick every 15° of the sweep, each across the arc's circle, the first /// through the arc's start; a sweep that is not a whole number of steps adds a tick at its end. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 65383caa1b..c1577473f7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7333,8 +7333,12 @@ center: a tick across the arc's circle every 15° from where the arc starts, a l arc ends. The piece the next click adds shows its protractor only while Enable Rubber Band for the Pen tool shows that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the -point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc sweeps the arc size, so its end -does not snap to a tick. Shift does not constrain Quick Pen points, so it does not change the tick snapping. The +point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. After a snap +setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still +pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer +moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it +does not change the tick snapping. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 581f72bb0f..e67e8b291d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,7 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. -- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From ac28d0b6ba389fbc50101ecec51374002c4bcb80 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 14:41:30 -0800 Subject: [PATCH 124/126] Pen: Alt tapped during a Quick Pen press moves the end on or off the tick at once A press keeps the pointer and the snapped point for the end of the piece it adds. When Alt changes the action during the press, the end goes through the protractor's tick again for the new action, so a continuous arc that snapped to a tick and becomes a sharp-corner arc ends at the pointer, and a piece that becomes a continuous arc goes onto the tick, without waiting for the next drag. This also covers a press that has not dragged. --- crates/engine/src/tests/quickpen.rs | 28 +++++++++++++++++ crates/tools/src/quickpen.rs | 47 ++++++++++++++++++++--------- docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 4 files changed, 64 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index bcb90f5249..754dda7e42 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -616,6 +616,34 @@ fn a_click_puts_a_continuous_arc_end_on_a_tick() { } } +/// Alt tapped during a press moves the end of the piece for the new action at once, with no +/// further drag: a continuous arc's end on the 60° tick goes to the pointer once the piece is a +/// sharp-corner arc, after a drag and after a press that has not dragged, and a line's end at the +/// pointer goes onto the tick once the piece is a continuous arc. +#[test] +fn an_alt_tap_during_a_press_moves_the_end_for_the_new_action() { + let at = arc_end_61(); + let v = ViewInfo::default(); + // (drag first, Alt taps before the press, the end before Alt, the end after it) + for (drag, taps, before, after) in [(true, 0, tick_60(), at), (false, 0, tick_60(), at), (true, 2, at, tick_60())] { + let mut s = session(); + continuous_arc_after_a_line(&mut s, v); + for _ in 0..taps { + key(&mut s, ToolKey::AltTap); + } + let first = if drag { (280.0, 140.0) } else { (at.x, at.y) }; + s.pointer(&PointerEvent::new(PointerKind::Down, first.0, first.1), v).unwrap(); + if drag { + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x, at.y), v).unwrap(); + } + assert!(drawn_end(&s).distance(before) < 1e-6, "{drag} {taps}: {:?}", drawn_end(&s)); + s.tool_key(ToolKey::AltTap, Mods::default(), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} after Alt: {:?}", drawn_end(&s)); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y), v).unwrap(); + assert!(drawn_end(&s).distance(after) < 1e-6, "{drag} {taps} placed: {:?}", drawn_end(&s)); + } +} + /// After a click puts a continuous arc's end on a tick away from the pointer, no preview runs from /// the placed end back to where the pointer was; the next move shows the preview again. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 1ff691f309..7acef24638 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -362,12 +362,14 @@ impl Drawing { } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo -/// step (a piece it adds). +/// step (a piece it adds). `end` is the pointer for the end of the piece it adds and where the +/// snap put that end, before the protractor's tick. #[derive(Clone, Copy, Debug, PartialEq)] struct Press { at: Point, dragged: bool, begun: bool, + end: Option<(Point, Point)>, } pub struct QuickPenTool { @@ -476,12 +478,12 @@ impl QuickPenTool { let before = self.before_piece(); let from = before.as_ref().and_then(|sp| sp.anchors.last()).map(|a| Leave::segment(cx, a.p, false).without_contact()); let q = self.snap.drag(cx, p, from.as_ref()); - let q = match (&before, self.drawing.as_ref().and_then(|dr| dr.pieces.last())) { - (Some(sp), Some(piece)) => { - let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); - self.on_tick(cx, sp, *piece, p, q, landed) - } - _ => q, + if let Some(pr) = self.press.as_mut() { + pr.end = Some((p, q)); + } + let q = match self.drawing.as_ref().and_then(|dr| dr.pieces.last()) { + Some(piece) => self.press_end(cx, piece, p, q), + None => q, }; let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; if last.to == q { @@ -491,6 +493,15 @@ impl QuickPenTool { vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] } + /// Where `piece`, which a press draws, ends with the pointer at `p` that the snap put at `q`: + /// on the protractor's tick when [`Self::on_tick`] puts it there for the piece's action. + fn press_end(&self, cx: &ToolContext, piece: &Piece, p: Point, q: Point) -> Point { + let Some(sp) = self.before_piece() else { return q }; + let from = sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()); + let landed = piece.stroke == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); + self.on_tick(cx, &sp, *piece, p, q, landed) + } + /// `q`, where the last snap put the end of `piece` drawn after `sp` (the pointer being at `p`), /// moved onto the protractor's nearest tick ([`tick_end`]) when Smart Guides are on, the tick /// lies within the snapping tolerance of the pointer, and nothing else snapped the point: the @@ -580,15 +591,15 @@ impl QuickPenTool { return vec![]; } let from = self.leave(cx).map(|l| l.1); - let q = self.snap.press(cx, p, &[id], from.as_ref()); - let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, q, from.as_ref()); - let q = self.on_tick(cx, sp, self.piece_to(q), p, q, landed); + let snapped = self.snap.press(cx, p, &[id], from.as_ref()); + let landed = self.action == Stroke::ContinuousArc && self.landed(cx, p, snapped, from.as_ref()); + let q = self.on_tick(cx, sp, self.piece_to(snapped), p, snapped, landed); let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { dr.push(piece, kept); dr.before_press = shared_node(cx.doc, id).cloned(); } - self.press = Some(Press { at: p, dragged: false, begun: true }); + self.press = Some(Press { at: p, dragged: false, begun: true, end: Some((p, snapped)) }); return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) @@ -798,11 +809,17 @@ impl Tool for QuickPenTool { } ToolKey::AltTap => { self.action = self.action.next(); - // A drag under way draws its piece with the new action. + // A drag under way draws its piece with the new action. Its end goes through the + // protractor's tick again for that action: a continuous arc's end on a tick goes + // back to where the snap put the pointer for another action, and the other way. if self.press.is_some_and(|pr| pr.begun) && self.held(cx) { - let (action, turn) = (self.action, self.turn); - if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - (last.stroke, last.turn, last.flip) = (action, turn, false); + let (action, turn, end) = (self.action, self.turn, self.press.and_then(|pr| pr.end)); + let piece = self.drawing.as_ref().and_then(|dr| dr.pieces.last()).map(|&pc| { + let pc = Piece { stroke: action, turn, flip: false, ..pc }; + end.map_or(pc, |(p, q)| Piece { to: self.press_end(cx, &pc, p, q), ..pc }) + }); + if let (Some(piece), Some(last)) = (piece, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *last = piece; } return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } diff --git a/docs/mcp.md b/docs/mcp.md index c1577473f7..5d9ce83191 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7334,7 +7334,9 @@ arc ends. The piece the next click adds shows its protractor only while Enable R that piece. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick of its protractor, on the same circle, when that tick lies within the Smart Guides snapping tolerance of the pointer, no other Smart Guide snaps the point, and neither Snap to Grid nor Snap to Pixel snaps drawn points. A sharp-corner arc, and a continuous arc that -starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. After a snap +starts a path and so has no direction to follow, sweep the arc size, so their ends do not snap to a tick. Alt tapped +during a press moves the piece's end for the new action at once: off the tick when a continuous arc becomes a +sharp-corner arc, and onto it when the piece becomes a continuous arc. After a snap setting (Smart Guides, Snap to Point, Snap to Grid, Snap to Pixel or a snapping tolerance) changes under a still pointer, the hover's preview, its protractor, its distance label and its Smart Guides are hidden until the pointer moves. When the view, the document or the selection changes, the canvas hovers the still pointer again. Shift does not constrain Quick Pen points, so it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e67e8b291d..630781ba62 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -642,7 +642,7 @@ since 2026-10-01. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. -- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. +- **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. From ff26d5e4a36d603675e72653740abd15b83ce200 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 15:38:19 -0800 Subject: [PATCH 125/126] Swatch libraries: colors a pattern brings skip the library's other names A global or spot color that a library pattern's art brings under a numbered name no longer takes a name the library gives another swatch. Before, adding a pattern whose art uses "Ink" to a document with another "Ink" brought the color as "Ink 2" even when the library has its own "Ink 2"; adding that library swatch next then came in as "Ink 2 2". The brought color now takes the next free name the library does not use ("Ink 3"), and every paint linked to it follows the new name, so adding the library's "Ink 2" next adds it under its own name and adding both again adds nothing. A color the pattern's art brings or takes is the color a library tint or gradient links to only when it has the library color's paint and its process, global or spot kind, as for the other lookups in the same add. The test a_numbered_copy_named_like_another_library_color_is_found now makes the blue "Ink 2" itself, as an earlier version's pattern add left it, since a pattern add no longer gives that name. --- crates/engine/src/cmd/swatchlib.rs | 41 +++++++++++++-- crates/engine/src/tests/swatchlib.rs | 78 ++++++++++++++++++++++++---- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 106 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index d0fbd1e0e0..7a5dc06c18 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1023,6 +1023,30 @@ fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) name } +/// Rename each swatch of `d` that `colors` lists (library name, document name) under a numbered +/// name that `reserved` says the library gives another swatch, to a free numbered name of its own +/// ([`free_copy_in`]), and link every paint linked to it to the new name. A later add then finds +/// the library's swatch of that name under its own name. +fn rename_brought(d: &mut vectorcraft_doc::Document, colors: &mut patternlib::SwatchNames, reserved: impl Fn(&str) -> bool) { + let mut taken = taken_names(d); + for (from, to) in colors.iter_mut() { + if from == to || !reserved(to) { + continue; + } + let new = free_copy_in(&mut taken, from, &reserved); + let Some(w) = d.swatches_iter_mut().find(|w| w.name == *to) else { continue }; + w.name = new.clone(); + map_swatch_links(d, &mut |_, link, _| { + let hit = link.as_deref() == Some(to.as_str()); + if hit { + *link = Some(new.clone()); + } + hit + }); + *to = new; + } +} + /// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors /// under the names `links` gives them, for each whose colors `links` names now. Those leave /// `pending` and are returned. @@ -1363,11 +1387,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let waited = |n: &&str| !links.contains_key(*n) && brings.contains(*n); // A global or spot color the pattern brought, or took from the document under // a numbered name: library name → document name. A color this call picks is - // added under its own name instead of the one the pattern took. + // added under its own name instead of the one the pattern took. A library global + // or spot color is only a document color of its paint and kind, as for `base_of`. let colors_of = |d: &vectorcraft_doc::Document, colors: &[(String, String)], took: &[(String, String)]| { let mut out: HashMap<String, String> = HashMap::new(); for (from, to) in colors.iter().chain(took.iter().filter(|(from, _)| !picked_names.contains(from.as_str()))) { - if d.swatch(to).is_some_and(|x| x.global || x.spot) { + let library = lib_by_name.get(from.as_str()).filter(|b| b.global || b.spot); + let fits = |x: &Swatch| (x.global || x.spot) && library.is_none_or(|b| x.paint == b.paint && same_kind(x, b)); + if d.swatch(to).is_some_and(fits) { out.entry(from.clone()).or_insert_with(|| to.clone()); } } @@ -1377,7 +1404,8 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, colors, took) = patternlib::import(&mut probe, src, pattern)?; + let (_, mut colors, took) = patternlib::import(&mut probe, src, pattern)?; + rename_brought(&mut probe, &mut colors, |n| lib_by_name.contains_key(n)); for (from, to) in colors_of(&probe, &colors, &took) { if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { e.insert(to); @@ -1387,7 +1415,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors, took) = patternlib::import(d, src, pattern)?; + let (target, mut colors, took) = patternlib::import(d, src, pattern)?; + // A color the art brought under a numbered name the library gives another + // swatch takes a free one instead. + rename_brought(d, &mut colors, |n| lib_by_name.contains_key(n)); // Those colors are the ones the library's tints of them link to, unless the // document already has one for them. A name the copy gave that the import // into the document did not give is replaced, and the tints linked to it are diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index fc450ebc95..5a7615327a 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -959,25 +959,18 @@ fn a_tint_linked_to_a_copy_the_library_names_is_not_another_colors_tint() { } /// A numbered copy of a color's name that the library also has as a swatch of another color is -/// still the copy of the color: adding the color after a pattern brought it under that name adds -/// no other copy. +/// still the copy of the color: adding the color to a document that has such a copy (as a pattern +/// added by an earlier version left it) adds no other copy. #[test] fn a_numbered_copy_named_like_another_library_color_is_found() { let mut s = session(); run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); - let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); - run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); - run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); - run(&mut s, "select.set", json!({"ids": [dot]})); - run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); - run(&mut s, "object.pattern.done", json!({})); let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); - let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Inks.vectorcraft"}))["library"].clone(); run(&mut s, "file.new", json!({"width": 100, "height": 100})); run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); - run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); - assert_eq!(named_after(&s, "Ink"), ["Ink", "Ink 2"]); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink"]})); assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{r}"); } @@ -1183,6 +1176,69 @@ fn a_library_spot_tint_is_not_a_process_tint_a_pattern_brought() { assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{r}"); } +/// A library tint of a spot color added with a pattern whose art the document holds linked to its +/// process color of the spot color's name and paint (as pasting with Merge leaves it) links to a +/// spot color, not to that process color, in either pick order. +#[test] +fn a_library_spot_tint_is_not_linked_to_the_process_color_a_merged_pattern_takes() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + for names in [json!(["Ink half", "Tiles"]), json!(["Tiles", "Ink half"])] { + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + // The paste merged the spot color into the document's process color of its name. + assert_eq!(named_after(&s, "Ink"), ["Ink"], "{names}"); + assert!(doc(&s).swatch("Ink").is_some_and(|w| w.global && !w.spot), "{names}"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": names})); + let base = tint_base(&s, "Ink half").unwrap_or_default(); + assert!(doc(&s).swatch(&base).is_some_and(|w| w.spot), "{names}: {r}"); + } +} + +/// A color a library pattern's art brings under a numbered name does not take a name the library +/// gives another swatch: adding that swatch next adds it under its own name, and adding the two +/// again adds nothing. +#[test] +fn a_color_a_pattern_brings_skips_the_librarys_numbered_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let brought = + first["added"].as_array().and_then(|a| a.iter().filter_map(|n| n.as_str()).find(|n| n.starts_with("Ink"))).unwrap_or_default().to_string(); + assert!(brought != "Ink 2" && is_global(&s, &brought, "#0000ff"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{r}"); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]})); + assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", brought, "Ink 2"])), "{again}"); +} + /// A library tint added without its global color to a document that has no swatch of the color's /// name brings the color along under its own name. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 0de5ad1692..559dc0b3a0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5802,7 +5802,8 @@ From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes -in under a numbered name ("Ink 2") and the pattern links to that. A library color whose name the document gives +in under a numbered name ("Ink 2") and the pattern links to that. That numbered name skips the names the library +gives its other swatches. A library color whose name the document gives another color is the document's numbered copy of the same color when it has one, so adding the pattern and its color again adds nothing. A pattern the document already holds with its art linked to the document's own color of that name is used as it is. A library tint or gradient whose global or spot color comes in under a numbered name, or is in the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8a406b82b8..f2744f2bb6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2237,7 +2237,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`). In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning. `.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`). - Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). + Swatches › Open Swatch Library › Other Library… lists `.ai` and `.eps` files in its Swatch Libraries filter and loads another document's swatches ([importing swatches from another document](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=134)): its colors, tints, gradients and pattern swatches, in its order and color groups. Adding a pattern swatch from such a library brings the pattern with its tile and art as a pattern swatch, under the library swatch's name and in its color group. A document with no swatches, and a `.ai` or EPS whose swatches are only the default ones, are refused with a message (`cmd::fileio::tests_aiimport::a_swatch_library_in_a_ai_file_lists_and_adds_its_pattern_swatches`, `a_pattern_from_a_ai_library_keeps_a_color_the_library_lacks`, `swatch_library_documents_without_swatches_or_damaged_are_refused`, `cmd::fileio::tests::the_swatch_library_filter_lists_ai_and_eps_files`). As VectorCraft's own rule, a global or spot color whose name the document gives another color, added from a library on its own, with a tint or with a pattern's art, comes in under a numbered name that skips the names of the library's other swatches, and adding it again uses that numbered copy; a library tint or gradient links to it, and brings its color when the document lacks it. Use Library Item adds a library pattern's colors the same way (`tests::swatchlib::adding_a_library_pattern_and_its_color_again_reuses_the_numbered_color`, `a_library_tint_follows_its_color_to_its_numbered_name`, `a_library_tint_added_alone_brings_its_color_beside_a_namesake`, `a_library_tint_picked_before_its_color_follows_it_to_its_numbered_name`, `a_library_gradient_is_not_the_one_a_merged_pattern_brought`, `a_color_a_pattern_brings_skips_the_librarys_numbered_names`, `tests::library::a_pattern_item_keeps_its_global_color_when_the_document_has_that_name_in_another_color`). A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`). A `.ai` or EPS symbol library, whose editing data holds symbol definitions and their list but no layers, opens with those symbols in list order, each with its registration point. Other Library… in the Symbols panel's Symbol Libraries Menu imports the symbols of the file you pick ([Create or import symbol libraries](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html)) and lists such a library's symbols in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the symbols defined before its layers (`crates/eps/src/import/tests_native.rs`, `crates/eps/src/import/ai/tests.rs`, `cmd::fileio::tests_aiimport::a_symbol_library_in_a_ai_file_without_layers_loads_its_symbols`). In a large canvas `.ai` or EPS ([Large canvas FAQ](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html)), or a `.ai` whose page is in larger units, opened from its editing data, VectorCraft reads the symbol definitions in the same units as the layers. When the file opens at its full size, each symbol's art, strokes and effects are scaled with the layers, and each instance keeps its own scale and rotation and draws where and as large as before. A new instance comes in at the symbol's full size, the size of an instance at 100% in the file. A symbol library from such a file comes in at the same size, and opacity masks on the layers that don't move with their object are scaled with the layers too. Editing data that VectorCraft wrote keeps its symbols and those masks at their own size, as its `.ai` save writes them (`tests_native::a_large_canvas_eps_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_keeps_its_symbols_at_the_pages_size`, `a_large_canvas_ai_vectorcraft_wrote_keeps_its_symbols_at_their_own_size`, `a_symbol_library_in_larger_units_comes_in_at_the_pages_size`, `build::candidate_tests::scaling_the_symbols_keeps_their_instances_in_place`, `scaling_a_read_document_scales_unlinked_opacity_masks`). From 6404b0cebfed434ccae6d1da78efe4fea7b1e025 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Sat, 21 Nov 2026 17:31:08 -0800 Subject: [PATCH 126/126] Swatch libraries: hold the library's numbered names while a pattern comes in A color a library pattern's art brings now skips the library's numbered names while the pattern is imported, instead of being renamed after the import. The rename also rewrote every other paint in the document linked to the name the import first gave, such as art still linked to a deleted "Ink 2", so adding the pattern changed that art. Now the names are held with placeholder swatches during the import and removed afterwards, and links that were already in the document stay as they were. A pattern whose art brings both "Ink" and the library's "Ink 2" keeps the library's "Ink 2" under its own name when the document gives "Ink" another color, and the library's "Ink" takes the next free name. A library pattern with a numbered name, such as "Tiles 2", keeps that name when the document does not use it. --- crates/engine/src/cmd/patternlib.rs | 5 ++ crates/engine/src/cmd/swatchlib.rs | 75 ++++++++++++++++++---------- crates/engine/src/tests/swatchlib.rs | 74 +++++++++++++++++++++++++++ 3 files changed, 128 insertions(+), 26 deletions(-) diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 88ec82e145..64342b21dd 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -138,6 +138,11 @@ pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::Has gather(lib, name).swatches.into_iter().map(|w| w.name).collect() } +/// The names in `lib` of pattern `name` and of the patterns its art brings. +pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet<String> { + gather(lib, name).patterns.into_iter().map(|p| p.name).collect() +} + /// The name pattern `name` has in the document `imported` went into. pub(crate) fn imported_name(imported: &Imported, name: &str) -> String { let renamed = imported.renamed.iter().find(|r| r["kind"] == "pattern" && r["from"] == name).and_then(|r| r["to"].as_str()); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 7a5dc06c18..341a26a4b1 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -1023,28 +1023,55 @@ fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str) name } -/// Rename each swatch of `d` that `colors` lists (library name, document name) under a numbered -/// name that `reserved` says the library gives another swatch, to a free numbered name of its own -/// ([`free_copy_in`]), and link every paint linked to it to the new name. A later add then finds -/// the library's swatch of that name under its own name. -fn rename_brought(d: &mut vectorcraft_doc::Document, colors: &mut patternlib::SwatchNames, reserved: impl Fn(&str) -> bool) { - let mut taken = taken_names(d); - for (from, to) in colors.iter_mut() { - if from == to || !reserved(to) { - continue; - } - let new = free_copy_in(&mut taken, from, &reserved); - let Some(w) = d.swatches_iter_mut().find(|w| w.name == *to) else { continue }; - w.name = new.clone(); - map_swatch_links(d, &mut |_, link, _| { - let hit = link.as_deref() == Some(to.as_str()); - if hit { - *link = Some(new.clone()); +/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered +/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own +/// swatches of those names, so that a color the art brings under a numbered name does not take one +/// of them. While the import runs, a placeholder swatch holds each such name the art does not +/// bring, and a copy of the library's color holds each one the art brings, which the art then +/// takes. The placeholders are removed before it returns, and so is a copy the art did not take; +/// a copy the art took is listed with the colors the import brought. Names of the patterns the +/// import brings are not held. +fn import_holding( + d: &mut vectorcraft_doc::Document, + src: &vectorcraft_doc::Document, + pattern: &str, + names: &HashMap<&str, &Swatch>, +) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> { + let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())); + let taken = taken_names(d); + let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect(); + free.sort_unstable(); + let (mut held, mut copies): (Vec<Swatch>, Vec<Swatch>) = (vec![], vec![]); + if !free.is_empty() { + let brings = patternlib::brought_names(src, pattern); + let patterns = patternlib::brought_patterns(src, pattern); + for n in free.into_iter().filter(|n| !patterns.contains(*n)) { + if !brings.contains(n) { + held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false }); + } else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) { + copies.push((*w).clone()); } - hit - }); - *to = new; + } } + let start = d.swatches.len(); + d.swatches.extend(held.iter().chain(&copies).cloned()); + let imported = patternlib::import(d, src, pattern); + let used = |n: &str| { + imported + .as_ref() + .is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n)) + }; + let used: HashSet<String> = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect(); + let mut i = 0; + d.swatches.retain(|w| { + i += 1; + let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint); + !(i > start && ours && !used.contains(&w.name)) + }); + let (target, mut colors, mut took) = imported?; + took.retain(|(from, _)| !used.contains(from)); + colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n))); + Ok((target, colors, took)) } /// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors @@ -1404,8 +1431,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, mut colors, took) = patternlib::import(&mut probe, src, pattern)?; - rename_brought(&mut probe, &mut colors, |n| lib_by_name.contains_key(n)); + let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?; for (from, to) in colors_of(&probe, &colors, &took) { if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { e.insert(to); @@ -1415,10 +1441,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, mut colors, took) = patternlib::import(d, src, pattern)?; - // A color the art brought under a numbered name the library gives another - // swatch takes a free one instead. - rename_brought(d, &mut colors, |n| lib_by_name.contains_key(n)); + let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?; // Those colors are the ones the library's tints of them link to, unless the // document already has one for them. A name the copy gave that the import // into the document did not give is replaced, and the tints linked to it are diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 5a7615327a..5d94eecc69 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1239,6 +1239,80 @@ fn a_color_a_pattern_brings_skips_the_librarys_numbered_names() { assert_eq!((&again["added"], &again["existing"]), (&json!([]), &json!(["Tiles", brought, "Ink 2"])), "{again}"); } +/// A pattern whose art brings both a color and the library's numbered color of the same name keeps +/// the numbered color under its own name, and the other color takes the next free one. +#[test] +fn a_pattern_bringing_a_color_and_its_numbered_namesake_keeps_the_librarys_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone(); + let green = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]})); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [green]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, green]})); + run(&mut s, "select.set", json!({"ids": [blue, green]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{r}"); + assert!(named_after(&s, "Ink").iter().any(|n| n != "Ink" && n != "Ink 2" && is_global(&s, n, "#0000ff")), "{r}"); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles", "Ink", "Ink 2"]})); + assert_eq!(again["added"], json!([]), "{again}"); +} + +/// A library pattern with a numbered name comes in under that name when the document does not use +/// it. +#[test] +fn a_numbered_library_pattern_keeps_its_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert!(r["added"].as_array().is_some_and(|a| a.contains(&json!("Tiles 2"))), "{r}"); + assert!(doc(&s).pattern("Tiles 2").is_some(), "{r}"); +} + +/// A color a library pattern's art brings does not change art of the document that is still +/// linked to a deleted color of a numbered name the library uses. +#[test] +fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#ffff00", "global": true})); + let box_id = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [box_id]})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let fill = doc(&s).node(vectorcraft_doc::NodeId(box_id.as_u64().unwrap())).unwrap().appearance.fill_paint(); + let Paint::Solid { swatch, .. } = &fill else { panic!("the box is filled with a color: {fill:?}") }; + assert_eq!(swatch.as_deref(), Some("Ink 2"), "{r}"); + assert!(doc(&s).swatch("Ink 2").is_none(), "{r}"); +} + /// A library tint added without its global color to a document that has no swatch of the color's /// name brings the color along under its own name. #[test]