From 322ce1a0159ab9898bcd1c8d7180002b31404648 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:27:00 -0800 Subject: [PATCH 1/8] Smart Guides: tangent and perpendicular snaps find a touch point that falls exactly on a sample The touch points of a drawn line were found by sampling each target segment in 24 steps and bisecting where the sign changed. When the line was exactly square or tangent at one of the samples, the value there was exactly 0, neither interval changed sign, and no snap was offered: for example the foot of a perpendicular from a point above a segment's middle, or a circle's tangent point when it fell exactly on a sample. A sample whose value is exactly 0 now counts as a touch point when its neighbors are not 0, so a straight curve seen from its own line still gives none. The ends of the segment, a cusp and a start point on the curve itself are left out, as between samples. Part of #7846 --- crates/tools/src/guides/snap.rs | 16 ++++++++-- crates/tools/src/guides/tests.rs | 54 ++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index d7ee8ecdd8..8aef46f028 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -29,7 +29,9 @@ pub(super) fn seg_direction(seg: &PathSeg, t: f64) -> Vec2 { } /// The parameters in (0, 1) where the line from `at` to `seg` is square to it (`perpendicular`) -/// or grazes it, found by sampling the curve for a change of sign and bisecting. +/// or grazes it, found by sampling the curve for a change of sign and bisecting. A sample where +/// the line is exactly square or grazing, and its neighbors are not, is one of them too: no sign +/// changes on either side of it. pub(super) fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec { const STEPS: usize = 24; let f = |t: f64| { @@ -41,7 +43,17 @@ pub(super) fn touch_params(seg: &PathSeg, at: Point, perpendicular: bool) -> Vec for i in 1..=STEPS { let t = i as f64 / STEPS as f64; let cur = (t, f(t)); - if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 { + if cur.1 == 0.0 { + // Not at the end (t = 1), not where `at` lies on the curve or the direction is zero + // (a cusp), and not along a stretch that is zero throughout, such as a straight + // curve seen from its own line. The sign need not change: the tangent at an + // inflection touches zero without crossing it. + let isolated = |n: f64| n.is_finite() && n != 0.0; + let (v, d) = (seg.eval(t) - at, seg_direction(seg, t)); + if i < STEPS && isolated(prev.1) && isolated(f((i + 1) as f64 / STEPS as f64)) && v.hypot() * d.hypot() > 1e-12 { + out.push(t); + } + } else if prev.1.is_finite() && cur.1.is_finite() && prev.1 * cur.1 < 0.0 { let (mut lo, mut hi) = (prev, cur); for _ in 0..40 { let mid = 0.5 * (lo.0 + hi.0); diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 16b46f6fb9..e4c2600879 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -535,6 +535,60 @@ fn drawn_lines_land_perpendicular_to_segments_and_tangent_to_curves() { } } +/// A touch point that falls exactly on one of the samples `touch_params` takes (t = k / 24) is +/// found, once: the foot of the perpendicular from above a segment's middle, and the tangent +/// point of a line drawn from a free point to a circle (#7846). A line to an oval lands tangent +/// between samples, as before. +#[test] +fn touch_points_exactly_on_a_sample_are_found() { + use super::snap::touch_params; + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::kurbo::{CubicBez, Line, ParamCurve}; + use vectorcraft_geom::shapes; + // (50, 40) above the segment (0, 0) to (100, 0): the foot is (50, 0), at t = 0.5 = 12 / 24. + let flat = PathSeg::Line(Line::new((0.0, 0.0), (100.0, 0.0))); + assert_eq!(touch_params(&flat, Point::new(50.0, 40.0), true), [0.5]); + assert_eq!(touch_params(&flat, Point::new(30.0, 40.0), true).len(), 1, "between samples, as before"); + assert!(touch_params(&flat, Point::new(0.0, 40.0), true).is_empty(), "the ends stay out"); + assert!(touch_params(&flat, Point::new(100.0, 40.0), true).is_empty(), "the ends stay out"); + // From a point on the segment itself there is no line to be square. + assert!(touch_params(&flat, Point::new(50.0, 0.0), true).is_empty()); + // A straight cubic seen from its own line runs along that line everywhere: no touch point. + let straight = PathSeg::Cubic(CubicBez::new((0.0, 0.0), (30.0, 0.0), (70.0, 0.0), (100.0, 0.0))); + assert!(touch_params(&straight, Point::new(-50.0, 0.0), false).is_empty()); + // y = 400 (t - 0.5)^3 has its inflection at t = 0.5, and the tangent there (the x axis) + // touches zero without a change of sign; seen from (-100, 0) it is still found. + let wave = PathSeg::Cubic(CubicBez::new((0.0, -50.0), (100.0 / 3.0, 50.0), (200.0 / 3.0, -50.0), (100.0, 50.0))); + assert_eq!(touch_params(&wave, Point::new(-100.0, 0.0), false), [0.5]); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let id = d.alloc_id(); + let circle = shapes::ellipse(Rect::new(450.0, 450.0, 550.0, 550.0)); + // The middle of the lower right quarter, and a point on the circle's tangent there. + let quarter = PathSeg::Cubic(circle.subpaths[0].segment(2)); + let mid = quarter.eval(0.5); + let from = mid + Vec2::new(-64.0, 64.0); + assert!(((mid - Point::new(500.0, 500.0)).hypot() - 50.0).abs() < 0.1, "{mid:?}"); + assert_eq!(touch_params(&quarter, from, false), [0.5]); + d.insert(Some(l), 1, Node::path(id, circle, Appearance::default_art())).unwrap(); + // An oval (centre (500, 300), 100 by 50) seen from (300, 300): the tangent points are at + // x = 450, y = 300 -/+ 25 * sqrt(3), between samples. + let oval = d.alloc_id(); + d.insert(Some(l), 2, Node::path(oval, shapes::ellipse(Rect::new(400.0, 250.0, 600.0, 350.0)), Appearance::default_art())).unwrap(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let leave = Leave::segment(&c, from, false); + let (q, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, None)).snap_from(&c, mid + Vec2::new(1.5, 1.0), Some(&leave)); + assert_eq!(labels(&ov), ["tangent"]); + assert!((q - mid).hypot() < 1e-9, "{q:?} {mid:?}"); + assert_eq!(lines(&ov), vec![(from, q)]); + let start = Point::new(300.0, 300.0); + let leave = Leave::segment(&c, start, false); + let (q, ov) = PointSnap::new(&c, || Targets::for_drawing(&d, &[], None, None)).snap_from(&c, Point::new(452.0, 259.0), Some(&leave)); + assert_eq!(labels(&ov), ["tangent"]); + assert!((q - Point::new(450.0, 300.0 - 25.0 * 3f64.sqrt())).hypot() < 0.2, "{q:?}"); +} + /// A box dragged from a corner (Rectangle, Ellipse, ...) never snaps square to a segment, and /// a busy spot does not hide the contact: every segment in reach is tried. #[test] From ad1c0573c3d522058d25bc517ff7e47e3034088b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:17:56 -0800 Subject: [PATCH 2/8] Legacy .ai: write Perceptual gradients with the stops on their curve In a legacy .ai gradient definition, each color stop holds only its color, midpoint and ramp point, and VectorCraft's reader opens such a gradient as a Classic gradient. A Perceptual gradient was written with its own stops, so the file opened with different colors between them and no warning. The writer now treats a Perceptual gradient as it treats a gradient mixed around the hue wheel: the colors on its curve become stops of their own in process colors, at most 256, in a definition of their own, with a warning that names Perceptual gradients. --- crates/eps/src/legacy_ai.rs | 1 + crates/eps/src/legacy_ai/tests.rs | 75 ++++++++++++++++++++++++++++++ crates/eps/src/legacy_ai/writer.rs | 12 ++--- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 + 5 files changed, 86 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index 779385b82b..7c13e46d37 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -122,6 +122,7 @@ const DIAMOND: &str = "diamond gradients are written as four linear gradients cl const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (legacy .ai gradients only pad)"; const SPREAD_CAPPED: &str = "gradients that repeat or reflect are written with at most 256 stops; they pad past those"; const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; +const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)"; /// Wedges a conic gradient is written as: one a degree. const CONIC_WEDGES: usize = 360; const STROKES: &str = diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 12a11a78f4..36b51e7ec5 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -238,6 +238,81 @@ fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() { } } +/// The written definition of the gradient named `name` in `text`, and how many stops it holds. +fn definition<'a>(text: &'a str, name: &str) -> (&'a str, usize) { + let def = text.split(&format!("%AI5_BeginGradient: ({name})\n")).nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap(); + (def, def.matches(" %_Bs\n").count()) +} + +/// The format's gradients mix their stops' colors directly: a Perceptual gradient is written in +/// process colors with the colors on its curve as stops, no more than the reader reads, in a +/// definition of its own rather than its swatch's, with a warning, and opens with the colors it +/// had. A Classic gradient keeps its own stops and gives no warning. +#[test] +fn perceptual_gradients_are_written_with_the_stops_on_their_curve() { + use vectorcraft_color::{GradientMethod, Swatch}; + let mut doc = Document::new(200.0, 100.0); + for (name, color) in [("Night", Color::cmyk(1.0, 1.0, 0.0, 0.0)), ("Sun", Color::cmyk(0.0, 0.0, 1.0, 0.0))] { + doc.swatches.push(Swatch { name: name.into(), paint: Paint::solid(color), global: true, spot: true }); + } + let stop = |offset: f32, color: Color, swatch: &str| GradientStop { swatch: Some(swatch.into()), ..GradientStop::new(offset, color) }; + let stops = vec![stop(0.0, Color::cmyk(1.0, 1.0, 0.0, 0.0), "Night"), stop(1.0, Color::cmyk(0.0, 0.0, 1.0, 0.0), "Sun")]; + let mut g = GradientPaint::new(Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) }); + g.swatch = Some("Dusk".into()); + let want = g.gradient.clone(); + // The same stops mixed directly stray from the Perceptual curve, so a file holding only the + // two stops would not open with the colors it had. + let classic = Gradient { method: GradientMethod::Classic, ..want.clone() }; + assert!( + (0..=100).any(|k| { + let t = k as f32 / 100.0; + want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05) + }), + "the methods mix alike" + ); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings); + assert!(!out.warnings.iter().any(|w| w == HUE_STOPS), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert!(!text.contains("(Dusk)"), "the curve is not the swatch's gradient"); + assert!(!text.contains("(Night)") && !text.contains("(Sun)"), "the stops are process colors: {text}"); + let (_, written) = definition(&text, "Gradient"); + assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops"); + let read = crate::import(&out.bytes).unwrap().document; + let mut back = None; + read.walk(|n| { + if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) { + back = Some(g.gradient.clone()); + } + }); + let back = back.unwrap(); + assert!(back.method.is_classic()); + assert_eq!(back.stops.len(), written, "every stop written is read"); + assert!(back.stops.iter().all(|s| s.swatch.is_none()), "{:?}", back.stops); + for k in 0..=100 { + let t = k as f32 / 100.0; + let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb()); + assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "at {t}: {a:?} vs {b:?}"); + } + + // Classic: its own two stops, its spot colors and its swatch's name, without the warning. + let mut doc = Document::new(200.0, 100.0); + doc.swatches.push(Swatch { name: "Night".into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 0.0, 0.0)), global: true, spot: true }); + let mut g = GradientPaint::new(classic); + g.swatch = Some("Dusk".into()); + let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None); + let l = doc.layers[0].id; + doc.insert(Some(l), 0, n).unwrap(); + let out = write(&doc); + assert!(!out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings); + let text = String::from_utf8_lossy(&out.bytes).into_owned(); + assert_eq!(definition(&text, "Dusk").1, 2); + assert!(text.contains("%%DocumentCustomColors: (Night)"), "{text}"); +} + /// A radial gradient repeated out from a center far from the shape is written with its ramp points /// (percent) to five decimals, so its runs keep their places hundreds of runs out. #[test] diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index c8bce40227..426717ee6e 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -9,7 +9,7 @@ use super::{ ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; -use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, SPREAD, SPREAD_CAPPED}; +use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; #[cfg(test)] thread_local! { @@ -751,11 +751,11 @@ impl<'a> Writer<'a> { /// (its distance a fraction of the radius, at most 1, §3.5.5; `0 0 0 0 Bh` at the center, /// §3.5.6), `1 (name) x y angle length 1 0 0 1 0 0 Bg`. fn gradient(&mut self, g: &GradientPaint, bounds: Rect) -> String { - // A gradient mixed around the hue wheel (the format's gradients mix their stops' colors - // directly): the stops on its curve, no more than the reader reads, in a definition of - // its own. - if g.gradient.method.is_hue() { - self.warn(HUE_STOPS); + // A gradient mixed by the Perceptual method or around the hue wheel (the format's + // gradients mix their stops' colors directly): the stops on its curve, in process colors, + // no more than the reader reads, in a definition of its own. + if !g.gradient.method.is_classic() { + self.warn(if g.gradient.method.is_hue() { HUE_STOPS } else { PERCEPTUAL_STOPS }); let curve = g.gradient.as_classic_curve(); let gradient = if curve.is_spread() { curve } else { curve.fitted(crate::import::MAX_GRADIENT_STOPS).into_owned() }; let p = GradientPaint { gradient, swatch: None, ..g.clone() }; diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..f25b2c6d71 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1633,7 +1633,8 @@ its noise). PDF exports write it the same way, except for a linear, radial, coni stops whose other stops are all paper white or written in CMYK or gray, that is not a dithered fill and whose curve does not have too many stops (a diamond as four such shadings). An export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile. PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK -or gray inks as a DeviceN shading. +or gray inks as a DeviceN shading. A legacy `.ai` file gets the colors between a Perceptual gradient's stops as stops +of their own, in process colors (at most 256, with a warning). `hue-clockwise` and `hue-counterclockwise` (VectorCraft's own methods) mix a linear, radial, conic or diamond gradient's colors around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next. With `hue-clockwise` the hue angle falls (red, magenta, blue, cyan, green, yellow, red), which is clockwise on the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..f3ebae9768 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2304,6 +2304,8 @@ PDF export writes a Perceptual linear or radial gradient whose stops are tints o In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. +Legacy `.ai` export writes a Perceptual gradient as it writes a gradient mixed around the hue wheel: the colors on its curve become stops of their own, in process colors, at most 256, in a gradient definition of their own rather than the gradient swatch's, with a warning. In a legacy `.ai` gradient definition, each color stop holds only its color, midpoint and position (`colorSpec colorStyle midPoint rampPoint %_Bs`, [File Format Specification §3.5.2](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf#page=41)). VectorCraft's legacy `.ai` reader opens such a gradient as a Classic gradient and mixes the stop colors directly. Spot color stops lose their inks, as they do in EPS (VectorCraft's own rule). Test: `eps::legacy_ai::tests::perceptual_gradients_are_written_with_the_stops_on_their_curve`. + ## Artwork Cleanup add-on (2026-10-30) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Artwork Cleanup and its From 87b21ebe55848b55a8503fb371ee395b55042f17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:32:03 -0800 Subject: [PATCH 3/8] Selection: select.toggle and select.add with many ids go through the selection once A Shift-drag marquee sends every object it reaches as one select.toggle {ids}. Each id used to scan and rebuild the selected objects, so K ids against S selected objects took O(K*(S+K)). Selection::toggle_all and Selection::add_all now handle the ids in one pass with a map of each id's current slot, and the commands use them. The result is the same as toggling or adding each id in order: an id toggled twice is selected again at the end, and a removal clears that id's anchors, segments, key and key anchor. Select > Inverse looks each selectable object up in a set of the selected ones instead of scanning the selection for each. Selection::toggle_target, set_slices and set_guides use the same set lookups. crates/engine/examples/selection_bench.rs times the old per-id loops against the new ones in one process. With 50,000 objects, toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs (wall clock on a machine that was running other builds). --- crates/doc/src/selection.rs | 73 ++++++++-- crates/doc/src/selection/tests.rs | 142 +++++++++++++++++++ crates/engine/examples/selection_bench.rs | 95 +++++++++++++ crates/engine/src/cmd/select.rs | 17 +-- crates/engine/tests/it/selection_commands.rs | 14 ++ docs/target-app-parity.md | 1 + 6 files changed, 317 insertions(+), 25 deletions(-) create mode 100644 crates/engine/examples/selection_bench.rs diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index e97a4b0cc1..7fb533769d 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -183,23 +183,69 @@ impl Selection { self.key_anchor = None; } } + /// [`Self::add`] for each of `ids` in order, going through the selected objects once. + pub fn add_all(&mut self, ids: impl IntoIterator) { + self.each(ids, false); + } + /// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id + /// listed twice is removed and then added again at the end. + pub fn toggle_all(&mut self, ids: impl IntoIterator) { + self.each(ids, true); + } + /// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot + /// carries the number of the activation that made it; an id's slots are kept only when they + /// carry its current activation, so a removal drops every slot of the id at once. + fn each(&mut self, ids: impl IntoIterator, toggle: bool) { + use std::collections::hash_map::{Entry, HashMap}; + let mut ids = ids.into_iter().peekable(); + if ids.peek().is_none() { + return; + } + self.target = None; + self.slices.clear(); + self.symbol_part = None; + self.on_path_member = None; + let mut live: HashMap = self.objects.iter().map(|id| (*id, 0)).collect(); + let mut added: Vec<(NodeId, usize)> = Vec::new(); + let mut removed = false; + for id in ids { + match live.entry(id) { + Entry::Vacant(e) => { + let activation = added.len() + 1; + e.insert(activation); + added.push((id, activation)); + } + Entry::Occupied(e) if toggle => { + e.remove(); + removed = true; + self.anchors.remove(&id); + self.segments.remove(&id); + if self.key == Some(id) { + self.key = None; + } + if self.key_anchor.is_some_and(|(k, _)| k == id) { + self.key_anchor = None; + } + } + Entry::Occupied(_) => {} + } + } + if removed { + self.objects.retain(|id| live.get(id) == Some(&0)); + } + self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id)); + } /// Select slices `ids` (see [`Selection::slices`]) and nothing else. pub fn set_slices(&mut self, ids: impl IntoIterator) { self.clear(); - for id in ids { - if !self.slices.contains(&id) { - self.slices.push(id); - } - } + let mut seen = HashSet::new(); + self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id))); } /// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else. pub fn set_guides(&mut self, ids: impl IntoIterator) { self.clear(); - for i in ids { - if !self.guides.contains(&i) { - self.guides.push(i); - } - } + let mut seen = HashSet::new(); + self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id))); } /// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a /// Shift-click on a guide). @@ -426,10 +472,11 @@ impl Selection { }; let locks = doc.locked_artboards(); ids.retain(|i| !locks.holds_id(*i)); - if ids.iter().all(|i| self.contains(*i)) { - ids.iter().for_each(|i| self.remove(*i)); + let selected: HashSet = self.objects.iter().copied().collect(); + if ids.iter().all(|i| selected.contains(i)) { + self.remove_all(ids); } else { - ids.into_iter().for_each(|i| self.add(i)); + self.add_all(ids); } self.target = None; } diff --git a/crates/doc/src/selection/tests.rs b/crates/doc/src/selection/tests.rs index b6090f8993..d3d7e9657a 100644 --- a/crates/doc/src/selection/tests.rs +++ b/crates/doc/src/selection/tests.rs @@ -45,6 +45,148 @@ fn remove_all_does_what_removing_each_does() { assert_eq!(none, s); } +/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key, +/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member. +fn seeded() -> Selection { + let mut s = Selection { objects: [1, 2, 3, 4, 5, 3, 6].map(NodeId).to_vec(), ..Selection::default() }; + for i in [2, 3, 4, 5] { + s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)])); + s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)])); + } + s.key = Some(NodeId(4)); + s.key_anchor = Some((NodeId(5), (0, 1))); + s.target = Some(NodeId(3)); + s.slices = vec![NodeId(9)]; + s.guides = vec![NodeId(10)]; + s.key_guide = Some(NodeId(10)); + s.new_art = Arc::new(HashSet::from([NodeId(2)])); + s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] }); + s.on_path_member = Some(NodeId(11)); + s +} + +/// Id lists with repeats, ids not selected, removals followed by additions, and the empty list. +fn id_streams() -> Vec> { + let mut streams: Vec> = [ + vec![], + vec![4], + vec![7], + vec![3], + vec![4, 1, 4, 7], + vec![7, 8, 7, 7, 3, 3, 5], + vec![1, 2, 3, 4, 5, 6], + vec![6, 5, 4, 3, 2, 1, 1, 2, 3], + vec![8, 2, 8, 2, 9, 9, 9], + ] + .into_iter() + .map(|ids| ids.into_iter().map(NodeId).collect()) + .collect(); + // Deterministic pseudo-random lists over ids 1 to 12, half of them selected to start with. + let mut x: u64 = 0x9e37_79b9_7f4a_7c15; + for len in [5, 17, 40, 120] { + let ids = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + NodeId(x % 12 + 1) + }) + .collect(); + streams.push(ids); + } + streams +} + +#[test] +fn add_all_does_what_adding_each_does() { + for ids in id_streams() { + let mut one_by_one = seeded(); + for id in &ids { + one_by_one.add(*id); + } + let mut all = seeded(); + all.add_all(ids.iter().copied()); + assert_eq!(all, one_by_one, "add_all({ids:?})"); + } +} + +#[test] +fn toggle_all_does_what_toggling_each_does() { + for ids in id_streams() { + let mut one_by_one = seeded(); + for id in &ids { + one_by_one.toggle(*id); + } + let mut all = seeded(); + all.toggle_all(ids.iter().copied()); + assert_eq!(all, one_by_one, "toggle_all({ids:?})"); + } + // An id toggled twice is selected again, at the end, without the anchors it had. + let mut s = seeded(); + s.toggle_all([NodeId(2), NodeId(2)]); + assert_eq!(s.objects, [1, 3, 4, 5, 3, 6, 2].map(NodeId)); + assert!(!s.anchors.contains_key(&NodeId(2)) && !s.segments.contains_key(&NodeId(2))); + // A removed key and key anchor stay cleared. + let mut s = seeded(); + s.toggle_all([NodeId(4), NodeId(5), NodeId(4), NodeId(5)]); + assert_eq!((s.key, s.key_anchor), (None, None)); +} + +#[test] +fn set_slices_and_set_guides_keep_the_first_of_each_id() { + let mut s = seeded(); + s.set_slices([3, 1, 3, 2, 1].map(NodeId)); + assert_eq!(s.slices, [3, 1, 2].map(NodeId)); + assert!(s.objects.is_empty() && s.guides.is_empty()); + s.set_guides([5, 5, 4, 6, 4].map(NodeId)); + assert_eq!(s.guides, [5, 4, 6].map(NodeId)); + assert!(s.slices.is_empty()); +} + +/// Shift-clicking a target circle does what removing or adding each of its art one by one does, +/// for a layer with art, an empty layer and an object. +#[test] +fn toggle_target_does_what_toggling_its_art_one_by_one_does() { + let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let art: Vec = (0..4).map(|_| d.alloc_id()).collect(); + for id in &art { + d.insert(Some(l), usize::MAX, Node::path(*id, rect(), crate::Appearance::default_art())).unwrap(); + } + let empty = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(empty, "Empty", crate::LayerColor::Preset(2))).unwrap(); + let one_by_one = |s: &Selection, id: NodeId| { + let mut s = s.clone(); + let ids = match d.node(id) { + Some(n) if n.is_layer() => n.layer_art(true), + _ => vec![id], + }; + if ids.iter().all(|i| s.contains(*i)) { + ids.iter().for_each(|i| s.remove(*i)); + } else { + ids.into_iter().for_each(|i| s.add(i)); + } + s.target = None; + s + }; + let mut starts = vec![Selection::default()]; + for objects in [vec![art[1]], vec![art[3], art[0], art[1], art[2]], vec![art[2], art[2], NodeId(99)]] { + let mut s = seeded(); + s.objects = objects; + s.key = s.objects.first().copied(); + s.anchors.insert(art[1], BTreeSet::from([(0, 0)])); + starts.push(s); + } + for start in &starts { + for id in [l, empty, art[2], NodeId(99)] { + let mut s = start.clone(); + s.toggle_target(&d, id); + assert_eq!(s, one_by_one(start, id), "toggle_target({id:?}) on {:?}", start.objects); + } + } +} + #[test] fn guides_are_selected_on_their_own() { let mut s = Selection::default(); diff --git a/crates/engine/examples/selection_bench.rs b/crates/engine/examples/selection_bench.rs new file mode 100644 index 0000000000..49296f44d9 --- /dev/null +++ b/crates/engine/examples/selection_bench.rs @@ -0,0 +1,95 @@ +//! `cargo run --release -p vectorcraft-engine --example selection_bench` prints the time of the +//! selection steps behind `select.toggle`, `select.add` and `select.inverse` on selections of 2,000, +//! 20,000 and 50,000 objects, done one id at a time (`old`) and in one pass (`new`), side by side in +//! one process. Each step checks that both give the same selection before it is timed. +//! `ITERS` sets the runs per step (default 7); each row is the median wall time in ms. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use vectorcraft_doc::{NodeId, Selection}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The median time of `old` and of `new` on clones of `start`, run in turn. +fn time(start: &Selection, old: impl Fn(&mut Selection), new: impl Fn(&mut Selection)) -> (f64, f64) { + let (mut a, mut b) = (start.clone(), start.clone()); + old(&mut a); + new(&mut b); + assert_eq!(a, b, "both ways give the same selection"); + let run = |f: &dyn Fn(&mut Selection)| { + let mut s = start.clone(); + let t = Instant::now(); + f(&mut s); + let ms = t.elapsed().as_secs_f64() * 1000.0; + black_box(s); + ms + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + olds.push(run(&old)); + news.push(run(&new)); + } + (median(olds), median(news)) +} + +/// `select.add` before the change: [`Selection::add`] for each id. +fn old_add(s: &mut Selection, ids: &[NodeId]) { + for id in ids { + s.add(*id); + } +} + +/// `select.toggle` before the change: [`Selection::toggle`] for each id. +fn old_toggle(s: &mut Selection, ids: &[NodeId]) { + for id in ids { + s.toggle(*id); + } +} + +/// `select.inverse` before the change: the selectable ids not found by [`Selection::contains`]. +fn old_inverse(s: &mut Selection, selectable: &[NodeId]) { + let ids: Vec = selectable.iter().copied().filter(|id| !s.contains(*id)).collect(); + s.set(ids); +} + +/// `select.inverse` after the change: the selectable ids not in a set of the selected ones. +fn new_inverse(s: &mut Selection, selectable: &[NodeId]) { + let selected: HashSet = s.objects.iter().copied().collect(); + let ids: Vec = selectable.iter().copied().filter(|id| !selected.contains(id)).collect(); + s.set(ids); +} + +fn row(name: &str, (old, new): (f64, f64)) { + println!(" {name:<44} {old:>12.3} ms {new:>12.3} ms {:>9.1}x", old / new.max(1e-9)); +} + +fn main() { + println!(" {:<44} {:>15} {:>15} {:>10}", "step", "old", "new", "speedup"); + for n in [2_000u64, 20_000, 50_000] { + println!("{n} objects"); + let all: Vec = (1..=n).map(NodeId).collect(); + let none = Selection::default(); + let mut every = Selection::default(); + every.set(all.iter().copied()); + let mut half = Selection::default(); + half.set(all.iter().copied().step_by(2)); + let interleaved: Vec = all.iter().copied().skip(n as usize / 4).chain(all.iter().copied().take(n as usize / 4)).collect(); + let half_new: Vec = all.iter().copied().skip(n as usize / 2).collect(); + row("toggle every object off", time(&every, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied()))); + row("toggle every object on", time(&none, |s| old_toggle(s, &all), |s| s.toggle_all(all.iter().copied()))); + row("toggle every object, half selected", time(&half, |s| old_toggle(s, &interleaved), |s| s.toggle_all(interleaved.iter().copied()))); + row("add half the objects, half selected", time(&half, |s| old_add(s, &half_new), |s| s.add_all(half_new.iter().copied()))); + row("inverse, half selected", time(&half, |s| old_inverse(s, &all), |s| new_inverse(s, &all))); + } +} diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 791aa47f39..10d5fb2a40 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1,6 +1,6 @@ //! Select menu. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, HashSet}; use serde_json::{Value, json}; use vectorcraft_color::Paint; @@ -460,7 +460,8 @@ fn reselect(s: &mut Session, _: &Value) -> Result { fn inverse(s: &mut Session, _: &Value) -> Result { let st = s.doc()?; - let ids: Vec = selectable(&st.doc, st.isolation).into_iter().filter(|id| !st.selection.contains(*id)).collect(); + let selected: HashSet = st.selection.objects.iter().copied().collect(); + let ids: Vec = selectable(&st.doc, st.isolation).into_iter().filter(|id| !selected.contains(id)).collect(); s.select(|_, sel| sel.set(ids.iter().copied()))?; ok() } @@ -491,11 +492,7 @@ fn set(s: &mut Session, p: &Value) -> Result { fn add(s: &mut Session, p: &Value) -> Result { let ids = checked_ids_param(s, p, "ids", "select.add")?; - s.select(|_, sel| { - for i in ids { - sel.add(i); - } - })?; + s.select(|_, sel| sel.add_all(ids))?; selection_result(s) } @@ -506,11 +503,7 @@ fn toggle(s: &mut Session, p: &Value) -> Result { let value = p.get("id").ok_or_else(|| bad("select.toggle", "missing id or ids"))?; vec![checked_id(s, value, "select.toggle")?] }; - s.select(|_, sel| { - for id in ids { - sel.toggle(id); - } - })?; + s.select(|_, sel| sel.toggle_all(ids))?; selection_result(s) } diff --git a/crates/engine/tests/it/selection_commands.rs b/crates/engine/tests/it/selection_commands.rs index 4e9b8e10b1..c5bcc1d9dd 100644 --- a/crates/engine/tests/it/selection_commands.rs +++ b/crates/engine/tests/it/selection_commands.rs @@ -61,6 +61,20 @@ fn selection_commands_report_the_resulting_selection() { } } +#[test] +fn toggle_and_add_handle_each_listed_id_in_order() { + let (mut s, a, b) = session(); + let c = NodeId(s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + // `a` goes off and back on at the end, `b` goes off, and `c` comes on. + assert_eq!(s.execute("select.toggle", &json!({"ids": [a.0, b.0, c.0, a.0]})).unwrap(), json!({"count": 2, "ids": [c.0, a.0]})); + assert_eq!(s.execute("select.add", &json!({"ids": [b.0, a.0, b.0]})).unwrap(), json!({"count": 3, "ids": [c.0, a.0, b.0]})); + // Inverse selects the objects that were not selected, in document order. + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.inverse", &json!({})).unwrap(); + assert_eq!(s.active().unwrap().selection.objects, [a, c]); +} + #[test] fn single_id_toggle_validates_before_mutating() { let (mut s, a, _) = session(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..bc1a780f99 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -673,6 +673,7 @@ since 2026-10-01. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. +- **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. From 642d95ab4acf206551d1c8522c1b5a780b0d23ad Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:20:19 -0800 Subject: [PATCH 4/8] Spiral: dragging turns the spiral to the pointer, and the click dialog starts it along Constrain Angle A spiral dragged out with the Spiral tool now turns about its center so that its outer end is at the pointer, so dragging around the center turns it. A pointer within 0.01 pt of the center keeps the last direction. Alt, Ctrl/Cmd, Up/Down, Space and Escape work as before, and Shift does not change the direction. With General > Constrain Angle other than 0 degrees or a whole turn, a spiral placed from the Spiral dialog starts along the turned x axis, with its bounding box turned. shape.spiral takes an optional rotation (degrees clockwise about cx, cy). Without it, or at 0 or a whole turn, spirals are drawn as before; a rotation that is not a number is an error and adds nothing. --- crates/engine/src/cmd/create.rs | 38 ++++++---- crates/engine/src/tests/constrain_new.rs | 89 ++++++++++++++++++++++++ crates/tools/src/draw2/family.rs | 65 +++++++++++++++-- crates/ui-egui/src/dialogs/shapes.rs | 20 ++++++ docs/gaps.md | 4 +- docs/mcp.md | 11 +++ docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 8 files changed, 210 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 4fca34a3ef..e0d4934d5b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -58,7 +58,15 @@ pub fn specs() -> Vec { flare ), cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), - cmd!("shape.spiral", "Spiral", [], None, "{cx, cy, radius, decay=80 (%), segments=10, clockwise?} → {id}", has_doc, spiral), + cmd!( + "shape.spiral", + "Spiral", + [], + None, + "{cx, cy, radius, decay=80 (%), segments=10, clockwise?, rotation?: deg clockwise about (cx, cy)} (0: outer end at (cx + radius, cy)) → {id}", + has_doc, + spiral + ), cmd!( "shape.arc", "Arc", @@ -116,13 +124,6 @@ pub fn specs() -> Vec { ] } -/// Insert a new object at the top of the insertion parent with the current paint and new-art -/// template; select it. -pub(crate) fn add_art(s: &mut Session, label: &str, kind: NodeKind, name: Option) -> Result { - let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); - add_look(s, label, kind, look, name) -} - /// Insert a new object looking like `look` (drawing modes apply); select it. pub(crate) fn add_look(s: &mut Session, label: &str, kind: NodeKind, look: NewArt, name: Option) -> Result { insert_look(s, label, kind, look, name, true) @@ -134,7 +135,8 @@ pub(crate) fn insert_look(s: &mut Session, label: &str, kind: NodeKind, look: Ne insert_look_turned(s, label, kind, look, name, select, 0.0) } -/// [`add_art`] for an object made turned by a `rotation` param (degrees, clockwise on the page): +/// Insert a new object at the top of the insertion parent with the current paint and new-art +/// template, made turned by a `rotation` param (degrees, clockwise on the page), and select it: /// its bounding box turns with it, as after the Rotate tool. fn add_art_turned(s: &mut Session, label: &str, kind: NodeKind, rotation: f64) -> Result { let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); @@ -300,7 +302,7 @@ fn path_kind(path: PathData, live: Option) -> NodeKind { /// a box (rectangle, ellipse, grid) runs along the turned axes from `pivot`, the point the dialog /// placed at the click (its top-left corner `x`, `y`, or a grid's reference point), which stays /// put; an arc sized by its lengths turns about its reference point `x`, `y`, which the dialog -/// placed at the click; a polygon or star turns its base orientation about its centre. The params as they are at +/// placed at the click; a polygon, star or spiral turns its base orientation about its centre. The params as they are at /// 0° or a whole turn, for other commands and when they already carry a `rotation`. pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) -> Value { let base = s.prefs.constrain_angle; @@ -316,7 +318,7 @@ pub fn constrain_click(s: &Session, cmd: &str, mut params: Value, pivot: Point) o.insert("y".into(), json!(c.y - h / 2.0)); o.insert("rotation".into(), json!(rotation)); } - "shape.polygon" | "shape.star" => { + "shape.polygon" | "shape.star" | "shape.spiral" => { o.insert("rotation".into(), json!(rotation)); } "shape.arc" if o.contains_key("lengthX") || o.contains_key("lengthY") => { @@ -581,6 +583,10 @@ fn line(s: &mut Session, p: &Value) -> Result { } fn spiral(s: &mut Session, p: &Value) -> Result { + let rotation = if p.get("rotation").is_some() { f64_req(p, "rotation", "shape.spiral")? } else { 0.0 }; + if !rotation.is_finite() { + return Err(bad("shape.spiral", "rotation must be finite")); + } let c = Point::new(f64_req(p, "cx", "shape.spiral")?, f64_req(p, "cy", "shape.spiral")?); let segments = count_or(p, "segments", 10, "shape.spiral")?.clamp(2, 1000) as u32; let path = shapes::spiral( @@ -590,7 +596,15 @@ fn spiral(s: &mut Session, p: &Value) -> Result { segments, switch_or(p, "clockwise", true, "shape.spiral")?, ); - add_art(s, "Spiral", path_kind(path, None), None) + // The outer end turns clockwise from (cx + radius, cy) about the center; 0 and whole turns + // leave the path as it is, and quarter turns are exact. + let path = if bbox_turn(rotation) == 0.0 { + path + } else { + let c = c.to_vec2(); + path.transformed(Affine::translate(c) * vectorcraft_geom::rotate_deg(rotation) * Affine::translate(-c)) + }; + add_art_turned(s, "Spiral", path_kind(path, None), constrained_turn(s, rotation)) } fn arc(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/tests/constrain_new.rs b/crates/engine/src/tests/constrain_new.rs index d78ceae054..9a26e45867 100644 --- a/crates/engine/src/tests/constrain_new.rs +++ b/crates/engine/src/tests/constrain_new.rs @@ -506,3 +506,92 @@ fn arc_rotation_turns_it_and_must_be_a_number() { } } } + +/// The outer end of the spiral `id`. +fn spiral_outer_end(s: &Session, id: NodeId) -> Point { + *path_points(s, id).last().unwrap() +} + +/// A spiral dragged out turns about its center so that its outer end is at the pointer, in every +/// direction and with a turned Constrain Angle too; its bounding box stays on the page, except +/// along the turned x axis, where it is the click dialog's spiral with its turned box. +#[test] +fn a_dragged_spiral_turns_its_outer_end_to_the_pointer() { + let mut s = new_doc(); + for deg in [0.0, 30.0] { + set_angle(&mut s, deg); + s.select_tool("spiral", ViewInfo::default()).unwrap(); + for (x, y) in [(260.0, 200.0), (200.0, 260.0), (140.0, 200.0), (200.0, 140.0), (240.0, 170.0)] { + gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, x, y), (Up, x, y)]); + let id = last_id(&s); + let end = spiral_outer_end(&s, id); + assert!(near(end, x, y), "{deg}°, to ({x}, {y}): {end:?}"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{deg}°, to ({x}, {y})"); + } + } + let mut s = new_doc(); + set_angle(&mut s, 90.0); + s.select_tool("spiral", ViewInfo::default()).unwrap(); + gesture(&mut s, Mods::default(), &[(Down, 200.0, 200.0), (Drag, 230.0, 230.0), (Drag, 200.0, 150.0), (Up, 200.0, 150.0)]); + let id = last_id(&s); + assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0)); + assert_eq!(bbox_angle(&s, id), 90.0, "along the turned x axis"); +} + +/// A spiral placed by the click dialog starts along the turned x axis, about the click: at 90° its +/// outer end is straight above the center, exactly, and its bounding box turns with it; at 0°, a +/// whole turn and with a `rotation` given the dialog's params are unchanged. +#[test] +fn constrain_angle_turns_a_click_made_spiral() { + let mut s = new_doc(); + let click = Point::new(200.0, 200.0); + let p = json!({"cx": 200.0, "cy": 200.0, "radius": 50.0, "decay": 80.0, "segments": 10, "clockwise": true}); + assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "0°"); + set_angle(&mut s, 360.0); + assert_eq!(constrain_click(&s, "shape.spiral", p.clone(), click), p, "a whole turn"); + set_angle(&mut s, 90.0); + let mut given = p.clone(); + given["rotation"] = json!(10.0); + assert_eq!(constrain_click(&s, "shape.spiral", given.clone(), click), given, "a given rotation"); + let turned = constrain_click(&s, "shape.spiral", p.clone(), click); + assert_eq!(turned["rotation"], json!(-90.0)); + let id = NodeId(s.execute("shape.spiral", &turned).unwrap()["id"].as_u64().unwrap()); + assert_eq!(spiral_outer_end(&s, id), Point::new(200.0, 150.0)); + assert_eq!(bbox_angle(&s, id), 90.0); + set_angle(&mut s, 30.0); + let id = NodeId(s.execute("shape.spiral", &constrain_click(&s, "shape.spiral", p, click)).unwrap()["id"].as_u64().unwrap()); + let r = 30f64.to_radians(); + let end = spiral_outer_end(&s, id); + assert!(near(end, 200.0 + 50.0 * r.cos(), 200.0 - 50.0 * r.sin()), "{end:?}"); + assert!(close(bbox_angle(&s, id), 30.0), "{}", bbox_angle(&s, id)); +} + +/// `shape.spiral` turns by an explicit `rotation` (clockwise) about its center; 0 and a whole +/// turn draw it exactly as without one; a `rotation` that is not a number is refused and adds +/// nothing. +#[test] +fn spiral_rotation_turns_it_and_must_be_a_number() { + let mut s = new_doc(); + let base = json!({"cx": 100, "cy": 100, "radius": 40, "segments": 6}); + let with = |r: Value| { + let mut p = base.clone(); + p["rotation"] = r; + p + }; + let plain = NodeId(s.execute("shape.spiral", &base).unwrap()["id"].as_u64().unwrap()); + let plain = path_points(&s, plain); + assert_eq!(*plain.last().unwrap(), Point::new(140.0, 100.0), "upright: the outer end to the right"); + for r in [json!(0), json!(360)] { + let id = NodeId(s.execute("shape.spiral", &with(r.clone())).unwrap()["id"].as_u64().unwrap()); + assert_eq!(path_points(&s, id), plain, "{r}"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "{r}"); + } + let id = NodeId(s.execute("shape.spiral", &with(json!(90))).unwrap()["id"].as_u64().unwrap()); + assert_eq!(spiral_outer_end(&s, id), Point::new(100.0, 140.0), "a quarter turn clockwise"); + assert_eq!(bbox_angle(&s, id).to_bits(), 0.0f64.to_bits(), "not the Constrain Angle's turn"); + for bad in [json!("x"), Value::Null, json!(true)] { + let p = with(bad); + assert!(s.execute("shape.spiral", &p).is_err(), "{p}"); + assert_eq!(last_id(&s), id, "nothing added for {p}"); + } +} diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8d7fc38df5..8bdbb4db0f 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -5,7 +5,8 @@ //! start point and the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering too. //! While dragging, ↑/↓ change the arc's slope, the spiral's segments, the grid rows or the //! concentric dividers; ←/→ change grid columns / radial dividers. C switches the arc between open -//! and closed, and F switches its base between the X and Y axes. While a spiral is dragged out, Alt +//! and closed, and F switches its base between the X and Y axes. A spiral's outer end follows the +//! pointer, so dragging around the center turns the spiral. While a spiral is dragged out, Alt //! and Ctrl/Cmd keep its inner end at the distance from the center on the first modified drag as //! the outer end follows the pointer: Alt adds or removes whole winds of four segments, and //! Ctrl/Cmd changes the decay. @@ -48,6 +49,9 @@ pub struct FamilyTool { spiral_end: Option, /// The segment count when Alt alone starts adjusting winds. spiral_alt_base: Option, + /// The direction (degrees clockwise on the page from the x axis) of the drag's last pointer at + /// least 0.01 pt from the center, 0 before there is one: the spiral's outer end turns to it. + spiral_bearing: f64, /// Rows / concentric dividers. pub rows: u32, /// Columns / radial dividers. @@ -108,6 +112,7 @@ impl FamilyTool { clockwise: true, spiral_end: None, spiral_alt_base: None, + spiral_bearing: 0.0, rows: 5, columns: 5, skew: [0.0; 2], @@ -202,6 +207,13 @@ impl FamilyTool { } } + /// The direction (degrees clockwise on the page from the x axis) from a spiral's center `start` + /// to the pointer `p`, or the last one when `p` is less than 0.01 pt from the center. + fn spiral_bearing_to(&self, start: Point, p: Point) -> f64 { + let d = p - start; + if d.hypot() >= 0.01 { d.y.atan2(d.x).to_degrees() } else { self.spiral_bearing } + } + /// The skew a letter changes while a grid is dragged out, as an index into `skew`, and the /// direction: F lowers and V raises the skew of the horizontal dividers (a rectangular grid's /// rows) or the radial dividers (a polar grid's), X lowers and C raises that of the vertical @@ -244,12 +256,16 @@ impl FamilyTool { /// arc and the grids are drawn along the x and y axes turned by it, as the rectangle is. pub fn command_at(&self, start: Point, p: Point, m: Mods, base: f64) -> (String, Value) { match self.id { + // The spiral: its outer end at the pointer, turned about the center. "spiral" => { let r = p.distance(start).max(0.01); - ( - "shape.spiral".into(), - json!({"cx": start.x, "cy": start.y, "radius": r, "decay": self.decay, "segments": self.segments, "clockwise": self.clockwise}), - ) + let mut params = + json!({"cx": start.x, "cy": start.y, "radius": r, "decay": self.decay, "segments": self.segments, "clockwise": self.clockwise}); + let rotation = self.spiral_bearing_to(start, p); + if rotation != 0.0 { + params["rotation"] = json!(rotation); + } + ("shape.spiral".into(), params) } // The grids: the dragged box (along the Constrain Angle's axes) with the tool's options. "rectangularGrid" | "polarGrid" => { @@ -308,6 +324,7 @@ impl Tool for FamilyTool { self.began = false; self.spiral_end = None; self.spiral_alt_base = None; + self.spiral_bearing = 0.0; self.before_drag = None; vec![] } @@ -329,6 +346,7 @@ impl Tool for FamilyTool { } if self.id == "spiral" { self.hold_spiral_end(s, ev.pos, ev.mods); + self.spiral_bearing = self.spiral_bearing_to(s, ev.pos); } let (c, v) = self.command_at(s, ev.pos, ev.mods, cx.constrain_angle); out.push(Action::Preview(c, v)); @@ -982,6 +1000,43 @@ mod tests { assert_eq!(t.spiral_alt_base, None, "Up after Down clears the Alt base"); } + /// A spiral dragged out turns to the pointer (`rotation` clockwise from the x axis), none to + /// the right as before; a pointer back on the center keeps the last direction, ↑ keeps it, + /// Shift and Constrain Angle leave it to the pointer, and the next drag starts from none. + #[test] + fn spiral_drag_turns_the_spiral_to_the_pointer() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.constrain_angle = 30.0; + let preview = |a: Vec| match &a[..] { + [.., Action::Preview(c, v)] if c == "shape.spiral" => v.clone(), + _ => panic!("{a:?}"), + }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = FamilyTool::new("spiral"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 100.0))); + assert!(v.get("rotation").is_none(), "to the right: {v}"); + assert_eq!(v["radius"], json!(50.0)); + for ((x, y), rotation) in [((100.0, 150.0), 90.0), ((50.0, 100.0), 180.0), ((100.0, 50.0), -90.0), ((130.0, 130.0), 45.0)] { + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(shift))); + assert!((v["rotation"].as_f64().unwrap() - rotation).abs() < 1e-9, "to ({x}, {y}): {v}"); + } + let v = preview(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 100.0))); + assert!((v["rotation"].as_f64().unwrap() - 45.0).abs() < 1e-9, "on the center: {v}"); + assert_eq!(v["radius"], json!(0.01)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 140.0)); + let v = preview(t.key(&cx, ToolKey::Up, Mods::default())); + assert!((v["rotation"].as_f64().unwrap() - 90.0).abs() < 1e-9, "after ↑: {v}"); + assert_eq!(v["segments"], json!(11)); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 140.0)), vec![Action::Commit]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.spiral_bearing, 0.0, "a new drag starts from none"); + } + #[test] fn arc_drag_uses_stored_segment_options() { let mut t = FamilyTool::new("arc"); diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index b807bc5274..3305ddf38f 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -517,6 +517,26 @@ mod tests { assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); } + /// With General › Constrain Angle at 90°, the Spiral dialog's spiral starts straight up from the + /// click, and the tool's options keep no turn. + #[test] + fn spiral_click_dialog_starts_along_the_constrain_angle() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("prefs.set", json!({"key": "constrainAngle", "value": 90})).unwrap(); + app.run("tool.select", json!({"tool": "spiral"})).unwrap(); + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().expect("Spiral dialog").fields.insert("radius".into(), json!(35.0)); + super::super::confirm(&mut app).unwrap(); + + let st = app.session.doc().unwrap(); + let id = *st.selection.objects.first().unwrap(); + let path = st.doc.node(id).unwrap().path_data().unwrap(); + let outer = path.subpaths[0].anchors.last().unwrap().p; + assert_eq!(outer, vectorcraft_geom::Point::new(40.0, 25.0)); + assert!(app.session.tool_options_of("spiral").get("rotation").is_none()); + } + #[test] fn alt_click_centres_the_typed_size_on_the_click() { let fields = |alt: bool| Dialog::new("rectangle", json!({"x": 100.0, "y": 50.0, "alt": alt, "width": "40 pt", "height": "20 pt"})); diff --git a/docs/gaps.md b/docs/gaps.md index a85090ce5f..e67deabe2c 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -488,8 +488,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Until a choice is made (`default`), the panels follow General › Transform Pattern Tiles as before, and the menu checks Transform Both while it is on and Transform Object Only while it is off; a choice overrides it. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. -- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Spirals, flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (). Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Flares and the Pen's new paths are not turned yet. Estimate unchanged. +- **Done (2026-10-21, #394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Flares and the Pen's new paths are not turned yet. Estimate unchanged. **2026-10-24:** General › Corner Radius is the Rounded Rectangle tool's radius: the tool takes the preference when chosen and when it changes while the tool is active (or lent a selection tool for a drag), and the radius ↑/↓ set while drawing one, or a Tool Options value, becomes the preference, clamped to its 0–1296 pt range (). Estimate unchanged. - **Done (2026-10-17):** Background Export shows its progress in a dialog with Cancel and Continue in Background (#2564), on the shared cancel token (#2546); a cancelled export writes no file. Save As, Export for Screens and Export Selection don't show it yet. Estimate unchanged. **2026-11-06:** opening a file that takes longer than 0.4 s shows a progress window too, with a moving bar, Cancel and Continue in Background (part of #5930); Save and Place still show only the status bar's spinner. Estimate unchanged. - **Done:** quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the controls with Threshold and Advanced (Paths, Corners, Noise), as the public documentation describes (). Other context-specific Properties gaps remain. - **Done (2026-10-31, #394):** Units › East Asian Type is read, and Q and Ha are units. 1 Q and 1 Ha are each a diff --git a/docs/mcp.md b/docs/mcp.md index 123523b500..14461280b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -768,6 +768,17 @@ Constrain Angle's negative. `shape.arc` takes `rotation` in degrees clockwise on reference point `x`, `y`; the arc's bounding box turns with it. Without `rotation`, or at 0° or a whole turn, the arc is upright, and a `rotation` that is not a number is an error that adds nothing. +A Spiral tool drag sends `shape.spiral` with the spiral's outer end at the pointer: `radius` is the pointer's distance +from the center `cx`, `cy` and `rotation` its direction in degrees clockwise on the page from the x axis, left out when +it is 0, so dragging around the center turns the spiral. A pointer less than 0.01 pt from the center keeps the last +direction (none before the first). Shift and General › Constrain Angle do not change a dragged spiral's direction. The +Spiral dialog's spiral, placed by a click, takes a `rotation` of the Constrain Angle's negative when the angle is other +than 0° or a whole turn, so its outer end starts along the turned x axis, and its bounding box turns with it. +`shape.spiral` takes `rotation` in degrees clockwise about `cx`, `cy`; without it, or at 0 or a whole turn, the outer +end is at `cx + radius`, `cy` as before, and a `rotation` that is not a number is an error that adds nothing. The +bounding box turns only when `rotation` is the Constrain Angle's negative, as for `shape.polygon` and `shape.star`, so a +drag that points along the turned x axis makes the same spiral, with the same turned box, as the dialog. + While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 61a69f1b6f..bf2a11e56c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -669,6 +669,7 @@ since 2026-10-01. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. +- **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 431f1e46fd..ecaf62eb01 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -468,7 +468,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | -| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); spirals, flares and Pen paths are not turned | +| Preferences › General › Constrain Angle | done | arrow keys and Shift drags along the turned axes; the Rectangle, Rounded Rectangle, Ellipse and grid tools, point and area type and the shape size dialogs draw along them with the bounding box turned; Shift-drawn polygons and stars keep the turned base orientation; the Line Segment tool's Shift steps count from it (#394, ); flares and Pen paths are not turned | | Tabs panel: a stop drags from where the press landed, a stop just added included | done | #1458 | | Outline view keeps template layers in Preview, dimmed | done | #1486; a picture placed to be traced stays visible under the outlines | | Outline view draws on a white canvas, the artboards as their edges | done | Outline shows only the paths ([Outline mode](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/preview-artwork-as-outlines.html)). VectorCraft's own rule for the canvas: in every interface brightness and Canvas Color the whole canvas is white, pasteboard included; the artboards draw no paper (no Simulate Colored Paper or artboard color, and no paper with Hide Artboards); the artboard names and the ruler origin's crosshair are dark gray; split views and floating windows follow their own view. Tests `outline_draws_on_a_white_canvas_with_artboards_as_edges`, `outline_draws_no_colored_paper`, `a_pane_draws_its_own_views_outline`, `the_ruler_origin_crosshair_shows_on_the_outline_canvas` | From 2af27232e0198cefa859cd4239a21cd9563f6949 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 09:42:15 -0800 Subject: [PATCH 5/8] Path Precision Tools: a path that ends on a curve still divides it after the curve is cut The crossing search took a crossing only where the straight pieces it splits two curves into actually cross. A line trimmed at a curve ends where that search found the crossing, up to about 0.0001 pt off the curve. Once the curve was cut as well, its segments were split differently, the line's end could fall just short of them, and the end no longer counted as a place on the curve. Trim at Crossings then removed the curve past that line, to the next crossing or the whole path. An open end of a path that lies within 0.001 pt of another path now meets it at the nearest point there, at any angle. Corners of a path and closed paths keep the exact test, and paths that lie along each other still don't cross. Trim at Crossings and its hover, Add Points at Crossings (with and without cut) and the Join tool's trim and join of crossing paths use this search. The params text of Trim at Crossings and Add Points at Crossings and docs/mcp.md say so. --- crates/engine/src/cmd/addons/pathtools.rs | 2 +- .../engine/src/cmd/addons/pathtools/trim.rs | 2 +- .../src/cmd/addons/pathtools/trim/tests.rs | 42 +++++++++ .../pathops/src/addons/pathtools/crossings.rs | 94 ++++++++++++------- crates/pathops/src/addons/pathtools/tests.rs | 55 +++++++++++ docs/mcp.md | 7 +- 6 files changed, 165 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index f84fb20f57..1c730e02b4 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -147,7 +147,7 @@ pub fn specs() -> Vec { "Add Points at Crossings", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}", + "{cut?: bool (false: add anchors where the paths cross; true: also cut them there), selfCrossings?: bool (false: where a path crosses itself too, a curved segment that loops over itself included), ids?: [id…] (default: the selection)} where the paths under the objects cross one another, an open end that lies within 0.001 pt of another path counting as crossing it there, as one undo step; at most 10000 segments → {ids, crossings (anchors placed)}", has_selection, crossings ), diff --git a/crates/engine/src/cmd/addons/pathtools/trim.rs b/crates/engine/src/cmd/addons/pathtools/trim.rs index f1ffab9ba0..e42817ebf9 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim.rs @@ -33,7 +33,7 @@ pub(super) fn specs() -> Vec { "Trim at Crossings", [], None, - "{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}", + "{at: [x, y], tolerance?: pt 0..100 (3; how near `at` a path counts as under it)} or {rect: [x, y, width, height]} or {points: [[x, y]…] (2 to 100000 points)} remove stretches of paths, a stretch running between two neighboring places where the path is crossed by another path or by itself, or from such a place to an open end: `at` removes the stretch of the nearest path at that point, `rect` every stretch the rectangle touches, `points` every stretch the line through the points crosses. Give exactly one of the three. Every path that can be edited takes part, selected or not, compound path members included; hidden and locked paths, guides and clipping paths (compound ones' members included) are neither trimmed nor counted as crossing; in isolation mode only paths inside the isolated object are trimmed. A path that ends on another, or within 0.001 pt of it, marks a place on the other; paths that lie along each other don't cross. A closed path that loses a stretch becomes open, an open path that loses a middle stretch becomes two paths with its appearance in its place in the stacking order, and a path nothing crosses is removed whole; a live shape becomes a plain path. One undo step, none when nothing is removed → {ids (the paths left of those trimmed), removed (stretches)}", has_doc, trim )] diff --git a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs index a36c705e4f..d24f7243ce 100644 --- a/crates/engine/src/cmd/addons/pathtools/trim/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/trim/tests.rs @@ -648,3 +648,45 @@ fn bad_params_are_refused_and_change_nothing() { assert_eq!(steps(&s), n); assert!(*s.doc().unwrap().doc == *before); } + +#[test] +fn a_line_ending_on_a_curve_that_was_cut_still_divides_it_there() { + // An open egg-shaped curve, lines across it whose stubs on the left are trimmed away, so each + // line ends on the curve, and the curve's bottom trimmed off below the last line, which cuts + // its segments there. A click on the curve between the last two lines removes only that + // stretch: the lines' ends on it still divide it, however the curve was cut. Twenty placements, + // as how near a cut end lies to the curve depends on the coordinates. + for shift in 0..20 { + let dx = shift as f64 * 7.31; + let mut s = session(); + let egg = json!({"anchors": [ + {"x": 160.0 + dx, "y": 40.0, "out": [110.0 + dx, 80.0]}, + {"x": 92.3 + dx, "y": 190.7, "in": [88.0 + dx, 140.0], "out": [97.0 + dx, 240.0]}, + {"x": 170.0 + dx, "y": 268.0, "in": [130.0 + dx, 265.0], "out": [210.0 + dx, 271.0]}, + {"x": 236.4 + dx, "y": 170.2, "in": [238.0 + dx, 230.0], "out": [233.0 + dx, 110.0]}, + {"x": 150.0 + dx, "y": 20.0, "in": [200.0 + dx, 40.0]} + ], "closed": false}); + let egg = NodeId(s.execute("path.create", &egg).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let ys: Vec = (0..8).map(|k| 70.0 + k as f64 * 23.17 + shift as f64 * 0.37).collect(); + let lines: Vec = ys.iter().map(|y| line(&mut s, &[(40.0 + dx, *y), (300.0 + dx, *y)], false)).collect(); + for y in &ys { + assert_eq!(s.execute(TRIM, &json!({"at": [50.0 + dx, y], "tolerance": 0.5})).unwrap()["removed"], json!(1)); + } + assert_eq!(s.execute(TRIM, &json!({"at": [170.0 + dx, 268.0], "tolerance": 0.5})).unwrap()["removed"], json!(1)); + let start = |id: NodeId| path(&s, id).subpaths[0].anchors[0].p; + let ends: Vec = lines.iter().map(|id| start(*id)).collect(); + // Off every path but the lines: the curve's pieces. + let off_curve = |s: &Session, p: Point| { + stack(s).into_iter().filter(|id| !lines.contains(id)).filter_map(|id| path(s, id).nearest(p)).map(|n| n.4).fold(f64::INFINITY, f64::min) + }; + let (a, b) = (ends[6], ends[7]); + let click = path(&s, egg).nearest(a.midpoint(b)).unwrap().3; + assert!(off_curve(&s, a) < 1e-3 && off_curve(&s, click) < 1e-3); + assert_eq!(s.execute(TRIM, &json!({"at": [click.x, click.y], "tolerance": 0.5})).unwrap()["removed"], json!(1)); + assert!(off_curve(&s, click) > 0.5, "{shift}: the stretch clicked is left"); + for (k, e) in ends.iter().enumerate().take(7) { + assert!(off_curve(&s, *e) < 1e-3, "{shift}: the curve no longer reaches line {k}'s end"); + } + } +} diff --git a/crates/pathops/src/addons/pathtools/crossings.rs b/crates/pathops/src/addons/pathtools/crossings.rs index bcc254aa82..63a83d6c31 100644 --- a/crates/pathops/src/addons/pathtools/crossings.rs +++ b/crates/pathops/src/addons/pathtools/crossings.rs @@ -34,9 +34,19 @@ fn flat(c: &CubicBez) -> bool { off(c.p1) <= FLAT && off(c.p2) <= FLAT } -/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel -/// ones never do). -fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { +/// Which ends of a segment are open ends of its path: (start, end). +type Open = (bool, bool); + +/// The open ends of segment `s` of `sp`. +fn open_ends(sp: &SubPath, s: usize) -> Open { + (!sp.closed && s == 0, !sp.closed && s + 1 == sp.segment_count()) +} + +/// Where the straight pieces `a` and `b` cross: (t on `a`, t on `b`), or `None` when their chords +/// don't cross (parallel ones never do, so paths lying along each other don't cross). An end in +/// `open_a` or `open_b` (start, end) that lies within [`SAME`] of the other piece meets it at the +/// point of that piece nearest it, at any angle. +fn pieces_cross(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open) -> Option<(f64, f64)> { let (da, db) = (a.p3 - a.p0, b.p3 - b.p0); let den = da.cross(db); if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 { @@ -45,12 +55,28 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> { let w = b.p0 - a.p0; let (s, u) = (w.cross(db) / den, w.cross(da) / den); let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v); - (within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0))) + if within(s) && within(u) { + // The pieces are straight but their parameters needn't run evenly along them. + let (s, u) = (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)); + return Some((a.nearest(a.p0.lerp(a.p3, s), 1e-9).t, b.nearest(b.p0.lerp(b.p3, u), 1e-9).t)); + } + let ends_a = [(open_a.0, 0.0, a.p0), (open_a.1, 1.0, a.p3)].into_iter().filter(|e| e.0).map(|(_, ta, p)| { + let n = b.nearest(p, 1e-9); + ((ta, n.t), n.distance_sq) + }); + let ends_b = [(open_b.0, 0.0, b.p0), (open_b.1, 1.0, b.p3)].into_iter().filter(|e| e.0).map(|(_, tb, p)| { + let n = a.nearest(p, 1e-9); + ((n.t, tb), n.distance_sq) + }); + ends_a.chain(ends_b).filter(|e| e.1 < SAME * SAME).min_by(|x, y| x.1.total_cmp(&y.1)).map(|e| e.0) } /// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control -/// boxes meet until each piece is straight. `None` once `budget` steps are spent. -fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option> { +/// boxes meet until each piece is straight. `None` once `budget` steps are spent. `open_a` and +/// `open_b` are the segments' ends that are open ends of their paths (start, end): such an end +/// within [`SAME`] of the other segment meets it there, as a path cut where another crosses it +/// ends a little off that path. +fn segment_crossings(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open, budget: &mut usize) -> Option> { let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)]; let mut found: Vec<(f64, f64)> = vec![]; while let Some((a0, a1, b0, b1, depth)) = stack.pop() { @@ -60,10 +86,9 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option= MAX_DEPTH { - if let Some((s, u)) = chords_cross(&ca, &cb) { - // The pieces are straight but their parameters needn't run evenly along them. - let x = ca.p0.lerp(ca.p3, s); - let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t); + // Only a piece's ends that are the segment's open ends reach past it. + let (oa, ob) = ((open_a.0 && a0 == 0.0, open_a.1 && a1 == 1.0), (open_b.0 && b0 == 0.0, open_b.1 && b1 == 1.0)); + if let Some((ta, tb)) = pieces_cross(&ca, &cb, oa, ob) { found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0))); } continue; @@ -152,18 +177,21 @@ fn shared_anchors(sp: &SubPath, with_length: &[usize], i: usize, j: usize) -> Ve /// Where segments `a` and `b` cross, without the places at the anchors in `shared`: two segments that /// meet at an anchor don't cross there, but they can cross again elsewhere. -fn crossings_apart(a: &CubicBez, b: &CubicBez, shared: &[Point], budget: &mut usize) -> Option> { - let mut found = segment_crossings(a, b, budget)?; +fn crossings_apart(a: (&CubicBez, Open), b: (&CubicBez, Open), shared: &[Point], budget: &mut usize) -> Option> { + let ((a, open_a), (b, open_b)) = (a, b); + let mut found = segment_crossings(a, b, open_a, open_b, budget)?; found.retain(|(ta, _)| !shared.iter().any(|p| a.eval(*ta).distance(*p) < SAME)); Some(found) } /// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself, a segment /// that loops over itself included): for each path, the places on it, in order. Segments that meet -/// at an anchor they share don't count as crossing there. `None` past [`MAX_CROSSING_SEGMENTS`] -/// segments or when the curves are too tangled to sort out, or when a coordinate isn't finite. +/// at an anchor they share don't count as crossing there, and an open end of a path that lies +/// within 0.001 pt of another path (or of itself) meets it there; paths that lie along each other +/// don't cross. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled +/// to sort out, or when a coordinate isn't finite. pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option>> { - let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![]; + let mut segs: Vec<(usize, usize, usize, CubicBez, Rect, Open)> = vec![]; for (k, path) in paths.iter().enumerate() { for (si, sp) in path.subpaths.iter().enumerate() { for s in 0..sp.segment_count() { @@ -171,7 +199,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option MAX_CROSSING_SEGMENTS { return None; } @@ -181,11 +209,11 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option>> = paths.iter().map(|p| p.subpaths.iter().map(with_length_from).collect()).collect(); let mut out: Vec> = vec![vec![]; paths.len()]; let mut budget = MAX_STEPS; - for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() { + for (i, (ka, sa, ia, ca, ra, oa)) in segs.iter().enumerate() { if self_crossings && let Some((s, t)) = self_crossing(ca) { out.get_mut(*ka)?.extend([(*sa, *ia, s), (*sa, *ia, t)]); } - for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) { + for (kb, sb, ib, cb, rb, ob) in segs.iter().skip(i + 1) { if (ka == kb && !self_crossings) || !ra.inflate(SAME, SAME).overlaps(*rb) { continue; } @@ -193,7 +221,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option shared_anchors(sp, w, *ia, *ib), _ => vec![], }; - for (ta, tb) in crossings_apart(ca, cb, &shared, &mut budget)? { + for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, &mut budget)? { out.get_mut(*ka)?.push((*sa, *ia, ta)); out.get_mut(*kb)?.push((*sb, *ib, tb)); } @@ -248,41 +276,43 @@ impl Work { } /// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself -/// included): the places on `path`, in order, within the work of [`Work::default`]. +/// included): the places on `path`, in order, within the work of [`Work::default`]. An open end of +/// a path that lies within 0.001 pt of another meets it there, as [`crossings_on_within`] says. pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option> { crossings_on_within(path, others, &mut Work::default()) } /// [`crossings_on`], drawing on `work`. Only the segments of `others` whose control boxes meet the /// box of `path` are compared with it, so the paths far from it cost one box test per segment. -/// Segments of `path` that meet at an anchor they share don't count as crossing there, and a -/// segment of `others` with a coordinate that isn't finite is left out. `None` when `path` has more -/// than [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than +/// Segments of `path` that meet at an anchor they share don't count as crossing there, an open end +/// of a path that lies within 0.001 pt of another meets it there, and a segment of `others` with a +/// coordinate that isn't finite is left out. `None` when `path` has more than +/// [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than /// [`MAX_CROSSED_BY_SEGMENTS`] segments of `others` lie in its box, when the pairs of segments to /// look at are more than `work` has left, or when the curves are too tangled to sort out in the /// steps it has left. pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Work) -> Option> { - let mut own: Vec<(usize, usize, CubicBez, Rect)> = vec![]; + let mut own: Vec<(usize, usize, CubicBez, Rect, Open)> = vec![]; for (si, sp) in path.subpaths.iter().enumerate() { for s in 0..sp.segment_count() { let c = sp.segment(s); if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) { return None; } - own.push((si, s, c, control_box(&c))); + own.push((si, s, c, control_box(&c), open_ends(sp, s))); if own.len() > MAX_CROSSING_SEGMENTS { return None; } } } let Some(reach) = own.iter().map(|o| o.3).reduce(|a, b| a.union(b)).map(|r| r.inflate(SAME, SAME)) else { return Some(vec![]) }; - let mut near: Vec<(CubicBez, Rect)> = vec![]; + let mut near: Vec<(CubicBez, Rect, Open)> = vec![]; for sp in others.iter().flat_map(|p| &p.subpaths) { for s in 0..sp.segment_count() { let c = sp.segment(s); let r = control_box(&c); if [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) && reach.overlaps(r) { - near.push((c, r)); + near.push((c, r, open_ends(sp, s))); if near.len() > MAX_CROSSED_BY_SEGMENTS { return None; } @@ -293,17 +323,17 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor let with_length: Vec> = path.subpaths.iter().map(with_length_from).collect(); let mut out: Vec = vec![]; let budget = &mut work.steps; - for (i, (sa, ia, ca, ra)) in own.iter().enumerate() { + for (i, (sa, ia, ca, ra, oa)) in own.iter().enumerate() { let ra = ra.inflate(SAME, SAME); if let Some((s, t)) = self_crossing(ca) { out.extend([(*sa, *ia, s), (*sa, *ia, t)]); } - for (cb, rb) in &near { + for (cb, rb, ob) in &near { if ra.overlaps(*rb) { - out.extend(segment_crossings(ca, cb, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta))); + out.extend(segment_crossings(ca, cb, *oa, *ob, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta))); } } - for (sb, ib, cb, rb) in own.iter().skip(i + 1) { + for (sb, ib, cb, rb, ob) in own.iter().skip(i + 1) { if !ra.overlaps(*rb) { continue; } @@ -311,7 +341,7 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor (Some(sp), Some(w)) if sa == sb => shared_anchors(sp, w, *ia, *ib), _ => vec![], }; - for (ta, tb) in crossings_apart(ca, cb, &shared, budget)? { + for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, budget)? { out.push((*sa, *ia, ta)); out.push((*sb, *ib, tb)); } diff --git a/crates/pathops/src/addons/pathtools/tests.rs b/crates/pathops/src/addons/pathtools/tests.rs index 3c6c592d71..4b5628e34e 100644 --- a/crates/pathops/src/addons/pathtools/tests.rs +++ b/crates/pathops/src/addons/pathtools/tests.rs @@ -689,3 +689,58 @@ fn a_slice_of_a_curve_keeps_its_shape_and_the_anchors_it_runs_through() { assert!(slice(&circle, (2.0, 1.0)).anchors.is_empty()); assert!(slice(&circle, (f64::NAN, 1.0)).anchors.is_empty()); } + +#[test] +fn an_open_end_a_hair_off_another_path_still_meets_it() { + // A bow from (0, 0) to (100, 100), and where a line across at y = 50 crosses it. + let bow = PathData::single(SubPath::new( + vec![Anchor { h_out: pt(0.0, 55.0), ..Anchor::corner(pt(0.0, 0.0)) }, Anchor { h_in: pt(45.0, 100.0), ..Anchor::corner(pt(100.0, 100.0)) }], + false, + )); + let across = PathData::single(line(&[(-50.0, 50.0), (150.0, 50.0)], false)); + let at = crossings_on(&across, &[&bow]).unwrap(); + assert_eq!(at.len(), 1); + let p = across.subpaths[0].segment(0).eval(at[0].2); + // A line ending 0.00005 pt short of the bow, or past it, as a line cut where the bow crosses it + // can: the bow is crossed there, on both searches. + let on_bow = |l: &PathData| crossings_on(&bow, &[l]).unwrap().iter().map(|q| bow.subpaths[0].segment(q.1).eval(q.2)).collect::>(); + for off in [-5e-5, 5e-5] { + let stub = PathData::single(line(&[(-50.0, 50.0), (p.x + off, 50.0)], false)); + let found = on_bow(&stub); + assert!(found.len() == 1 && found[0].distance(p) < 1e-3, "{off}: {found:?}"); + let both = crossings(&[&stub, &bow], false).unwrap(); + assert_eq!((both[0].len(), both[1].len()), (1, 1), "{off}: {both:?}"); + } + // 0.01 pt short is not on it. + assert!(on_bow(&PathData::single(line(&[(-50.0, 50.0), (p.x - 0.01, 50.0)], false))).is_empty()); + // The bow's own open end 0.00005 pt short of an upright meets it there. + let upright = PathData::single(line(&[(100.00005, 50.0), (100.00005, 150.0)], false)); + let found = crossings_on(&upright, &[&bow]).unwrap(); + assert!(found.len() == 1 && near(upright.subpaths[0].segment(0).eval(found[0].2).y, 100.0, 1e-3), "{found:?}"); + // Two ends that each stop 0.0009 pt short of a corner lie 0.0013 pt apart: they don't meet. + let flat = PathData::single(line(&[(0.0, 0.0), (99.9991, 0.0)], false)); + let post = PathData::single(line(&[(100.0, 0.0009), (100.0, 50.0)], false)); + assert!(crossings_on(&flat, &[&post]).unwrap().is_empty() && crossings_on(&post, &[&flat]).unwrap().is_empty()); + // Two ends that each stop 0.0004 pt short of a corner lie 0.0006 pt apart: they meet. + let flat = PathData::single(line(&[(0.0, 0.0), (99.9996, 0.0)], false)); + let post = PathData::single(line(&[(100.0, 0.0004), (100.0, 50.0)], false)); + assert_eq!((crossings_on(&flat, &[&post]).unwrap().len(), crossings_on(&post, &[&flat]).unwrap().len()), (1, 1)); + // A level line that crosses a quarter circle near its top, where the two meet at under 3 + // degrees, cut 0.0015 pt short along its length: its end lies under 0.0001 pt from the arc and + // meets it there. + use kurbo::ParamCurveNearest; + let arc = PathData::single(quarter()); + let level = PathData::single(line(&[(50.0, 99.9), (-50.0, 99.9)], false)); + let at = crossings_on(&level, &[&arc]).unwrap(); + assert_eq!(at.len(), 1); + let end = level.subpaths[0].segment(0).eval(at[0].2) + Vec2::new(0.0015, 0.0); + assert!(arc.subpaths[0].segment(0).nearest(end, 1e-12).distance_sq.sqrt() < 1e-4); + let stub = PathData::single(line(&[(50.0, 99.9), (end.x, end.y)], false)); + let found = crossings_on(&arc, &[&stub]).unwrap(); + assert!(found.len() == 1 && arc.subpaths[0].segment(0).eval(found[0].2).distance(end) < 1e-3, "{found:?}"); + assert_eq!(crossings(&[&stub, &arc], false).unwrap().iter().map(Vec::len).collect::>(), [1, 1]); + // A corner of a closed path as near a line is not an open end: it doesn't reach the line. + let wedge = PathData::single(line(&[(180.0, 0.0), (220.0, 0.0), (200.0, 49.99995)], true)); + let floor = PathData::single(line(&[(150.0, 50.0), (250.0, 50.0)], false)); + assert!(crossings_on(&floor, &[&wedge]).unwrap().is_empty() && crossings_on(&wedge, &[&floor]).unwrap().is_empty()); +} diff --git a/docs/mcp.md b/docs/mcp.md index 7c45340f2b..84c9cf9aa4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12343,8 +12343,9 @@ Commands: - `addon.pathtools.crossings {cut?, selfCrossings?, ids?}` adds anchors where the selected paths cross one another (and where each crosses itself, with `selfCrossings`), or with `cut` also cuts them there: a path of one subpath becomes a path per piece. Segments that meet at an anchor they share, or with only segments of no length between them, don't - cross there, and they cross where they meet again elsewhere. With `selfCrossings`, a curved segment that loops over - itself crosses itself. At most 10,000 segments at once. + cross there, and they cross where they meet again elsewhere. An open end of a path that lies within 0.001 pt of + another path crosses it there. With `selfCrossings`, a curved segment that loops over itself crosses itself. At most + 10,000 segments at once. - `addon.pathtools.divideDashes {dash?, gap?, fit?, removeGaps?}` cuts the selected paths into separate open paths along the curve, each `dash` long (0.01 to 1,000,000 pt, 10 by default) with `gap` between them (0 to 1,000,000 pt, 0 by default: the pieces touch), every piece keeping the path's appearance, as one undo step. The gap pieces are left @@ -12426,7 +12427,7 @@ Commands: Every path that can be edited takes part, selected or not, compound path members included. Hidden and locked paths, guides and clipping paths are not trimmed and do not count as crossing, the members of a compound clipping path included; type, images and symbol instances take no part. In isolation mode only paths inside the isolated object - are trimmed, and paths outside it still count as crossing. A path that ends on another marks a place on the other. Paths that lie along each other do not cross there. + are trimmed, and paths outside it still count as crossing. A path that ends on another, or within 0.001 pt of it, marks a place on the other. Paths that lie along each other do not cross there. Crossings are found on the paths' own outlines, without strokes, brushes or effects. A closed path that loses a stretch becomes open. An open path that loses a middle stretch becomes two paths with its appearance, in its place in the stacking order. A path that nothing crosses is removed whole, a compound path that loses its last member is From ea4e3bce29ce83a8ca09632ef6b5279160f419a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 07:08:52 -0800 Subject: [PATCH 6/8] Color Guide: a script run or a resting link keeps the base color it showed Running a script or a plug-in now ends the spot color base's link, as a batch step already did, so a script that deletes the spot color and makes another of the same name does not make the new one the base. Commands that only list scripts or plug-ins keep the link. While the link waits for an Undo, the color it captures before a command is the one the guide shows, not that of a new spot color of the same name. --- crates/ui-egui/src/panels/color_guide.rs | 58 ++++++++++++++++++++++-- docs/target-app-parity.md | 2 +- 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/color_guide.rs b/crates/ui-egui/src/panels/color_guide.rs index 28b0726920..b13d00f1d1 100644 --- a/crates/ui-egui/src/panels/color_guide.rs +++ b/crates/ui-egui/src/panels/color_guide.rs @@ -116,10 +116,11 @@ pub(crate) fn before_command(app: &VectorcraftApp) -> LinkBefore { let group = st.zip(s).and_then(|(st, s)| st.doc.swatch_groups.iter().find(|g| g.swatches.iter().any(|w| w.name == s.swatch)).map(|g| g.name.clone())); let docs = if s.is_some() { app.session.documents().iter().map(|d| d.uid).collect() } else { Vec::new() }; - // The color it shows: its swatch's tint in its document, while that is a spot color there. + // The color it shows: its swatch's tint in its document, while that is a spot color there and + // the link does not rest (a resting link shows the color it last showed). let shown = st .zip(s) - .filter(|(st, s)| st.doc.swatch(&s.swatch).is_some_and(|w| w.spot)) + .filter(|(st, s)| !s.resting && st.doc.swatch(&s.swatch).is_some_and(|w| w.spot)) .and_then(|(st, s)| st.doc.tint_paint(&s.swatch, s.tint)?.color()); let color = s.map(|_| shown.unwrap_or_else(|| base_color(app))); LinkBefore { active, group, color, docs, active_index: app.session.active_index() } @@ -225,7 +226,7 @@ fn follow_batch(app: &VectorcraftApp, base: u64, name: String, steps: &[Value], for (i, step) in steps.iter().enumerate() { let sid = step["command"].as_str().unwrap_or_default(); let (p, r) = (&step["params"], results.get(i).unwrap_or(&Value::Null)); - if sid.starts_with("script.") || sid.starts_with("plugin.") { + if runs_code(sid) { return None; } match docs.in_base() { @@ -268,15 +269,23 @@ fn follow_batch(app: &VectorcraftApp, base: u64, name: String, steps: &[Value], spots.next().is_none().then_some(first) } +/// Whether command `id` runs a script or a plug-in (Run Script, a plug-in filter or a plug-in's own +/// command), whose commands the panel does not follow. +fn runs_code(id: &str) -> bool { + matches!(id, "script.run" | "plugin.run") || vectorcraft_engine::cmd::plugin::is_command_id(id) +} + /// Command `id` ran with `params` and replied `reply`: a spot color base linked to a swatch that /// Swatch Options renamed links to the new name, and one whose swatch a command deleted or made a /// process color is no longer linked to it, so a later spot color of the same name does not /// become the base; the base keeps the color it showed. A `command.batch`'s steps are followed in -/// order ([`follow_batch`]). +/// order ([`follow_batch`]). A script or a plug-in may do anything, so it ends the link. pub(crate) fn after_command(app: &mut VectorcraftApp, id: &str, params: &Value, reply: &Value, before: LinkBefore) { let Some(s) = app.ui.color_guide_spot.as_ref() else { return }; let (base, n) = (s.doc, s.swatch.clone()); - let name = if id == "command.batch" { + let name = if runs_code(id) { + None + } else if id == "command.batch" { let steps = params["commands"].as_array().map(Vec::as_slice).unwrap_or_default(); let results = reply["results"].as_array().map(Vec::as_slice).unwrap_or_default(); follow_batch(app, base, n, steps, results, &before) @@ -1388,6 +1397,45 @@ mod tests { assert_eq!(spot_name(&app).as_deref(), Some("Ink U")); } + /// While the link rests, a new spot color of the same name that the panel did not follow does + /// not give the base its color when the next command ends the link. + #[test] + fn a_resting_link_keeps_the_color_it_showed() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + let shown = base_color(&app); + app.session.execute("swatch.delete", &json!({"name": "Ink"})).unwrap(); + frame(&mut app, &ctx); + app.session.execute("swatch.new", &json!({"name": "Ink", "color": "#00cc66", "spot": true})).unwrap(); + frame(&mut app, &ctx); + assert!(app.ui.color_guide_spot.as_ref().is_some_and(|s| s.resting), "resting"); + assert_eq!(base_color(&app), shown, "a resting link shows the color it showed"); + app.run("swatch.new", json!({"name": "Spare", "color": "#999999"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "another command ends it"); + assert_eq!(base_color(&app), shown, "the base keeps the color it showed"); + } + + /// A script run ends the link: a script that deletes the spot color and makes another of the + /// same name does not make the new one the base, and the base keeps the color it showed. Listing + /// scripts or plug-ins keeps it. + #[test] + fn a_script_run_ends_the_link() { + let mut app = spot_app(1.0); + let ctx = egui::Context::default(); + frame(&mut app, &ctx); + // Commands that only list scripts or plug-ins keep the link, also as batch steps. + app.run("script.engines", json!({})).unwrap(); + app.run("plugin.list", json!({})).unwrap(); + app.run("command.batch", json!({"commands": [{"command": "script.engines"}]})).unwrap(); + assert!(app.ui.color_guide_spot.is_some(), "a script or plug-in listing"); + let shown = base_color(&app); + let source = "vc.run('swatch.delete', {name: 'Ink'}); vc.run('swatch.new', {name: 'Ink', color: '#00cc66', spot: true});"; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert!(app.ui.color_guide_spot.is_none(), "a script ran"); + assert_eq!(base_color(&app), shown, "the base keeps the color it showed"); + } + /// A `command.batch` that switches, opens, closes or moves documents follows the spot color /// base's swatch in its own document and leaves the link alone for steps in the others. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eb8aae5389..bbc27cd18e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1766,7 +1766,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. - - **Color Guide tints of a spot color:** when the Color Guide's base is a spot color, or a tint of one, chosen in the Swatches panel, with the Color panel's tint slider or with the base chip, the cells right of the center in the base row of Tints/Shades are tints of that spot color: a click paints the art with the tint, a drag carries it, and Save Colors as Swatches and Save Color Group to Swatches make tint swatches ("Ink 60%") linked to the spot color, so they follow an edit of it. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/color-guide-panel-overview.html) says spot colors are kept only on the right side of Tints/Shades and every other variation gives process colors. The tint percentages (the base's tint reduced by the share each cell goes toward white), the shades on the left staying process colors, a Limit to Library giving process colors, and a global process base keeping plain colors are VectorCraft's own rules. So are these: renaming the spot color in Swatch Options, also as a `command.batch` step, keeps it the base, and so do an Undo and a Redo of the rename; deleting it (or its color group), making it a process color or closing its document ends the link, so a later spot color of the same name does not become the base until it is chosen, and the base keeps the color it showed. A batch's steps in other documents leave the link alone. `swatch.new {colors}` and `swatch.newGroup {colors}` take `{swatch, tint}` entries. Tests: `a_spot_color_base_gives_tints_of_that_spot_color`, `a_tinted_spot_base_gives_lighter_tints_and_a_lost_link_gives_process_colors`, `a_renamed_spot_color_stays_the_base`, `a_deleted_spot_color_ends_the_link`, `an_undone_rename_keeps_the_link`, `a_batch_follows_the_spot_color_across_documents`, `a_deleted_color_group_ends_the_link`, `saved_spot_tints_are_tint_swatches_of_the_spot_color`, `a_dragged_spot_tint_becomes_a_tint_swatch`, `a_clicked_spot_color_swatch_becomes_a_linked_color_guide_base`, `colors_entries_naming_a_spot_color_save_tint_swatches`. + - **Color Guide tints of a spot color:** when the Color Guide's base is a spot color, or a tint of one, chosen in the Swatches panel, with the Color panel's tint slider or with the base chip, the cells right of the center in the base row of Tints/Shades are tints of that spot color: a click paints the art with the tint, a drag carries it, and Save Colors as Swatches and Save Color Group to Swatches make tint swatches ("Ink 60%") linked to the spot color, so they follow an edit of it. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/color-guide-panel-overview.html) says spot colors are kept only on the right side of Tints/Shades and every other variation gives process colors. The tint percentages (the base's tint reduced by the share each cell goes toward white), the shades on the left staying process colors, a Limit to Library giving process colors, and a global process base keeping plain colors are VectorCraft's own rules. So are these: renaming the spot color in Swatch Options, also as a `command.batch` step, keeps it the base, and so do an Undo and a Redo of the rename; deleting it (or its color group), making it a process color or closing its document ends the link, so a later spot color of the same name does not become the base until it is chosen, and the base keeps the color it showed. A batch's steps in other documents leave the link alone. Running a script or a plug-in, also as a batch step, ends the link, and a spot color of the same name that appears while the link waits for an Undo does not give the base its color. `swatch.new {colors}` and `swatch.newGroup {colors}` take `{swatch, tint}` entries. Tests: `a_spot_color_base_gives_tints_of_that_spot_color`, `a_tinted_spot_base_gives_lighter_tints_and_a_lost_link_gives_process_colors`, `a_renamed_spot_color_stays_the_base`, `a_deleted_spot_color_ends_the_link`, `an_undone_rename_keeps_the_link`, `a_batch_follows_the_spot_color_across_documents`, `a_deleted_color_group_ends_the_link`, `a_resting_link_keeps_the_color_it_showed`, `a_script_run_ends_the_link`, `saved_spot_tints_are_tint_swatches_of_the_spot_color`, `a_dragged_spot_tint_becomes_a_tint_swatch`, `a_clicked_spot_color_swatch_becomes_a_linked_color_guide_base`, `colors_entries_naming_a_spot_color_save_tint_swatches`. - **Stroke visibility (#1253):** adding paint to a previously unpainted zero-width stroke restores the existing 1 pt default (`PaintDefaults::default`, `Appearance::set_stroke`), for the selected appearance item, the new-art defaults and Swap Fill/Stroke. Positive widths are kept; recoloring a painted zero-width stroke keeps its explicit zero. A real Eyedropper-to-new-shape sequence reproduces the zero-width inheritance. Five engine regressions cover creation, defaults, targeted items, preserved widths and one-step Undo/Redo (`crates/engine/tests/it/stroke_visibility.rs`). - **Gradients:** lossless, validated gradient params; gradients follow rotate, reflect, shear, non-uniform scale and distortions; the Gradient tool edits the fill or stroke of the active proxy, type included; an interactive on-canvas annotator (move, length/angle, rotate, add/move/delete/duplicate stops, midpoints, a stop popover, Delete and arrow keys). The Gradient panel has the Fill/Stroke proxy, a gradient-swatch dropdown with Save to Swatches, midpoint locations, Alt-drag to copy or swap stops, swatch drops on the ramp and a stop eyedropper; copied appearances and graphic styles place gradients on each target's own bounds; gradient handles, both ends of a vector drawn on the art and the start of a clicked one snap as other drawn points do (path segments, construction guides and View › Snap to Glyph's guides included) and honour Constrain Angle. Gradient stops stay linked to global and spot swatches. Freeform gradients (points and lines) are edited on the canvas; radial gradients have an extent ellipse, an aspect handle and an off-centre focal point (SVG `fx`/`fy`, PDF two-point radials). A stroke's gradient runs within, along or across it. Object ▸ Expand turns gradients into N objects or a gradient mesh. A gradient stop that loses its link to a spot swatch (the swatch deleted, a recolor or adjustment that unlinks it, a library gradient, or a library character style linked to a swatch the document lacks) keeps the color it shows at full tint and drops the process plates it printed with that ink, as a stop given a plain color does; this is VectorCraft's own rule. Evidence: `tests::mapping_links_drops_the_process_plates_of_unlinked_stops` in `crates/color`, `tests::linked_stops::deleting_a_spot_swatch_takes_the_process_plates_of_the_stops_it_unlinks` and `tests::library::library_stops_unlinked_from_their_swatch_keep_no_process_plates` in `crates/engine`. From 9ae9da71b801128ef9536fb515c17e8323efe0a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 08:02:49 -0800 Subject: [PATCH 7/8] Fix numeric reference points in bounds transforms --- crates/engine/src/cmd/object/bounds.rs | 12 ++++- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/tests/bboxrotate.rs | 69 ++++++++++++++++++++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 2 + 5 files changed, 86 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index 0a427e3ea0..cf0473f353 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -56,6 +56,7 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res /// direct-selected anchors are what changes ([`Bounds::Anchors`]). fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchors: bool) -> Result { check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?; + let refi = reference_index(p)?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; check_switches(p, &["proportional"], "object.setBounds")?; @@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1]; let (m, all) = (margins(vs), margins(v)); let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]]; - let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize; let rp = vectorcraft_geom::reference_point(v, refi); let (w, h) = wanted_size(p, v); // The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is @@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) { /// `b`, the box around the anchors (and the objects selected whole) square to the page, and only /// the anchors, their handles with them, and those objects move or scale. fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec, b: Rect) -> Result { - let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize; + let refi = reference_index(p)?; let rp = vectorcraft_geom::reference_point(b, refi); let (w, h) = wanted_size(p, b); // A single anchor, or anchors in a line, have no size to scale on that side. @@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec, b: Rect) -> R apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true) } +fn reference_index(p: &Value) -> Result { + let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?; + if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 { + return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number")); + } + Ok(reference.min(8.0) as usize) +} + /// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with /// symbol instances measured without the strokes in their art /// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]). diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d9c0b22d4b..7f620b17ff 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -287,7 +287,7 @@ pub fn specs() -> Vec { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), diff --git a/crates/engine/src/tests/bboxrotate.rs b/crates/engine/src/tests/bboxrotate.rs index dfabb77236..db09eba280 100644 --- a/crates/engine/src/tests/bboxrotate.rs +++ b/crates/engine/src/tests/bboxrotate.rs @@ -428,6 +428,75 @@ fn transform_panel_sizes_follow_the_turned_box() { assert!(near(angle(&s, a), 45.0)); } +#[test] +fn set_bounds_whole_number_references_match_integer_references() { + for direct in [false, true] { + for index in 0..=9 { + let run = |reference: Value| { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + if direct { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + } + let before = anchors(&s, a); + let selection = s.doc().unwrap().selection.clone(); + let n = undo_len(&s); + s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + assert_eq!(s.doc().unwrap().selection, selection); + if !direct { + let b = selection_box(&s); + assert!(b.reference_point(index.min(8)).distance(Point::new(200.0, 300.0)) < 1e-6, "{b:?}"); + } + let after = anchors(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(anchors(&s, a), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(anchors(&s, a), after); + after + }; + assert_eq!(run(json!(index as f64)), run(json!(index)), "reference {index}, direct {direct}"); + if index == 8 { + assert_eq!(run(json!(u64::MAX)), run(json!(8)), "large reference, direct {direct}"); + assert_eq!(run(json!(1e100)), run(json!(8)), "large float reference, direct {direct}"); + } + } + } + for reference in [None, Some(Value::Null)] { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + let mut p = json!({"x": 200, "y": 300}); + if let Some(reference) = reference { + p["reference"] = reference; + } + s.execute("object.setBounds", &p).unwrap(); + assert!(selection_box(&s).center().distance(Point::new(200.0, 300.0)) < 1e-6); + } +} + +#[test] +fn set_bounds_rejects_invalid_references_without_changes() { + for direct in [false, true] { + for reference in [json!(-1), json!(-1.0), json!(0.5), json!(8.5), json!("0"), json!(true), json!([]), json!({})] { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 100.0, 50.0); + sel(&mut s, &[a]); + if direct { + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + } + let before = anchors(&s, a); + let selection = s.doc().unwrap().selection.clone(); + let n = undo_len(&s); + assert!(s.execute("object.setBounds", &json!({"x": 200, "y": 300, "reference": reference})).is_err(), "{reference}, direct {direct}"); + assert_eq!(anchors(&s, a), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(undo_len(&s), n); + } + } +} + #[test] fn reset_bounding_box_squares_the_box_in_one_step() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..8e5cfc343d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2076,7 +2076,10 @@ commands fail and change nothing, and `appearance.removeItem` removes nothing. A `artboard.reorder`, `graphicStyle.move`, `appearance.moveItem`, `appearance.duplicateItem` and `effect.move`) puts the item last. A text `start` or `end` is past the end of the text. `object.slice.divide` refuses such a `rows` or `columns`, `recolor.reduce` keeps each color in its own row for such a `colors`, and `layer.setProps` refuses such a -`color`. `object.setBounds` reads a `reference` past 8 as 8, as `object.transformEach` does. +`color`. `object.setBounds` reads a whole-number `reference` past 8 as 8, as `object.transformEach` does. +For `object.setBounds`, `reference` accepts whole numbers of 0 or more, including floating-point representations +such as `0.0`. Negative and fractional values are errors. An omitted or null `reference` uses the center point, 4. +These rules apply to both whole objects and directly selected anchors. An index or place given as a value that is not a whole number of 0 or more, such as `"3"`, `2.5`, `-1` or `true`, is refused with `` `anchor` must be a whole number ``, naming the key: `anchor` of `path.setHandle`, `path.moveAnchor` and `text.setPathHandle`, `segment` of `path.insertAnchor`, `to` of `artboard.reorder`, `library.moveGroup` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..aaddc46c86 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -588,6 +588,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- `object.setBounds` uses the same reference point for whole-number integer and floating-point values, including `0` and `0.0`. It rejects negative and fractional indices without changing geometry, selection, or undo history. An omitted or null reference uses the center, and whole-number references above 8 use point 8. Object and direct-anchor selections follow these rules (`tests::bboxrotate::set_bounds_whole_number_references_match_integer_references`, `set_bounds_rejects_invalid_references_without_changes`). + - **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. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. From 82c9631b57c3efd14156fbdac1267263eb1f8300 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 18 Nov 2026 01:41:52 +0700 Subject: [PATCH 8/8] Render: a gradient mesh past any buffer draws without flattening its outline A damaged .ai can give a gradient mesh whose outline is enormous but finite. draw_mesh_raster flattened that whole outline in device pixels (grown_outline), and kurbo's flatten then asked for more segments than memory holds: a "capacity overflow" panic (seen in import_fuzz's ai_written_meshes_never_panic). An outline wider or taller than 2^24 device pixels now goes to the per-quad drawing path the function already falls back to. --- crates/render/src/live.rs | 11 ++++++++++- crates/render/src/tests/viewraster.rs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 3777c98948..e1940bc79c 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -249,6 +249,10 @@ fn mesh_level(m: &GradientMesh, bounds_px: f64) -> usize { /// of pixels per mesh and frame. const MESH_RASTER_MAX_PIXELS: usize = 4 << 20; +/// The widest and tallest a gradient mesh's outline is in device pixels for [`draw_mesh_raster`] +/// to flatten it (about 16.7 million pixels, far past any buffer it fills). +const MESH_OUTLINE_MAX_EXTENT: f64 = (1u32 << 24) as f64; + /// Draw a tessellated gradient mesh as one image: its quads are filled into a pixel buffer of the /// mesh's on-screen box by scanline (each pixel takes the quad its centre is in, so neighbouring /// quads meet without seams or overlap, and is shaded between the quad's corner colours, so the @@ -262,7 +266,12 @@ const MESH_RASTER_MAX_PIXELS: usize = 4 << 20; fn draw_mesh_raster(ctx: &mut RenderContext, f: &Frame, m: &GradientMesh, quads: &[MeshQuad], alpha: f32) -> bool { let outline = m.outline().to_bezpath(); let dev = f.view.transform_rect_bbox(vectorcraft_geom::Shape::bounding_box(&outline)); - if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) { + // The outline is flattened whole in device pixels ([`grown_outline`]): one far past any + // buffer would make more segments than memory holds, so the caller draws the quads. + if ![dev.x0, dev.y0, dev.x1, dev.y1].iter().all(|v| v.is_finite()) + || dev.width() > MESH_OUTLINE_MAX_EXTENT + || dev.height() > MESH_OUTLINE_MAX_EXTENT + { return false; } let (cw, ch) = (f64::from(ctx.width()), f64::from(ctx.height())); diff --git a/crates/render/src/tests/viewraster.rs b/crates/render/src/tests/viewraster.rs index 7d7399e608..7474772eae 100644 --- a/crates/render/src/tests/viewraster.rs +++ b/crates/render/src/tests/viewraster.rs @@ -463,3 +463,19 @@ fn backdrop_drag_perf() { ); } } + +/// A gradient mesh far larger than any buffer (a damaged file can give one) is drawn without +/// flattening its whole outline in device pixels, which would make more segments than memory holds. +#[test] +fn a_mesh_past_any_buffer_draws_without_flattening_its_outline() { + let side = 1e30; + let mut d = Document::new(595.0, 842.0); + let m = vectorcraft_doc::GradientMesh::from_surface(2, 2, &|u, v| vectorcraft_geom::Point::new(u * side, v * side + u * u * side), &|u, v| { + Color::rgb(u as f32, v as f32, 0.5) + }); + let layer = d.layers[0].id; + let node = Node::new(d.alloc_id(), NodeKind::Mesh(m)); + d.insert(Some(layer), 0, node).unwrap(); + let image = Renderer::new().render(&d, 640, 900, view(1.0, (640, 900)), &RenderOptions::default()); + assert_eq!(image.pixels.len(), 640 * 900 * 4); +}