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 db8e6f930c..60ad1b4328 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 remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() { for kept in [false, true] { 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 0f113c8a9d..ea3181faf9 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; @@ -466,7 +466,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() } @@ -497,11 +498,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) } @@ -512,11 +509,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/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index d304ed27df..ea569c94a5 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 f2ee896dc5..9512f3ddbf 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -272,6 +272,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 e6653bfcd3..1a74c6d831 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! { @@ -755,11 +755,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/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); +} diff --git a/crates/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index f985ab1d63..496ad00bfb 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 ecfd3a2edc..0406ea5f77 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] 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/mcp.md b/docs/mcp.md index 092faabc4c..4ac57d5003 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1660,7 +1660,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 473b1c815f..ee682dfcf7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -691,6 +691,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`. @@ -1767,7 +1768,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`. @@ -2420,6 +2421,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