From d601ec31ca6595f141fba9a9232fd17369def357 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:19:55 -0800 Subject: [PATCH 01/15] Symbols: the Symbol Shifter, Sizer, Stainer and Styler take Shift A Shift-click with the Symbol Shifter brings the symbol instances under the brush one place forward in the stacking order, and Alt+Shift-click sends them one place backward, without moving them on the canvas. The Symbol Sizer with Shift keeps each instance's center, so the set's density stays as it was, even with Resizing Affects Density. The Symbol Stainer and the Symbol Styler with Shift keep the amount of an instance's stain or style and move its color toward the fill color or the selected style; an instance without one is left as it is. symbol.adjust takes shift. No undo step is added when nothing moves or changes, and a shift that is not true or false is an error. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 99 +++++++++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/symbolism_shift.rs | 209 +++++++++++++++++++++ crates/tools/src/symbolism.rs | 40 ++++ docs/mcp.md | 14 ++ docs/target-app-parity.md | 1 + 7 files changed, 363 insertions(+), 3 deletions(-) create mode 100644 crates/engine/src/tests/symbolism_shift.rs diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 3a31281f30..2ba9b2ad29 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. No undo step is added when no instance changes (none under the brush, or average with each already at the mean). A `method` that is none of the three, or a pressure that isn't a number, is an error", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. No undo step is added when no instance changes (none under the brush, average with each already at the mean, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 4ba3b22b62..46a6b5b3c3 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1041,6 +1041,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let use_pressure = switch_or(p, "usePressure", false, C)?; let proportional = switch_or(p, "proportional", true, C)?; let affects_density = switch_or(p, "affectsDensity", false, C)?; + let shift = switch_or(p, "shift", false, C)?; // The Symbol Shifter has no Method. let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? }; // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. @@ -1084,6 +1085,33 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { // for the whole stroke (and for every preview of it). let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; + // Shift with the Symbol Shifter: the instances under the brush come one place forward among + // their siblings (with `alt`, go one place backward), once for the whole stroke. + if tool == "shift" && shift { + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { + let under: std::collections::HashSet = candidates + .iter() + .copied() + .filter(|id| { + d.node(*id).and_then(instance_center).is_some_and(|c| { + pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius) + }) + }) + .collect(); + let moved = restack(d, &under, alt)?; + Ok((moved, moved > 0)) + })?; + return Ok(json!({ "count": count })); + } + // Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style + // moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer + // keeps the instances where they are, Resizing Affects Density included. + let recolor = match tool.as_str() { + "stain" if shift => Some((Paint::solid(color), 0.15)), + "style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)), + _ => None, + }; + let spread = affects_density && !shift; // No undo step when no instance changes (none under the brush, or Average with each at the mean). let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { let mut touched = std::collections::BTreeSet::new(); @@ -1110,6 +1138,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { continue; } let Some(cur) = d.node(*id).and_then(|n| look(d, n)) else { continue }; + // Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount + // of its stain or style, and its paint moves toward the color or the style. An + // instance without one is left as it is. + if let Some((to, step)) = &recolor { + if recolor_keeping_amount(d, *id, cur.fill, to, step * w) { + touched.insert(*id); + } + continue; + } // Average leaves an instance that already has the mean as it is. let at_mean = target.as_ref().is_some_and(|t| match tool.as_str() { "scrunch" => { @@ -1161,8 +1198,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { }; n.transform(about(Affine::scale_non_uniform(kx, ky)), false); // Resizing Affects Density: instances move away from the brush's center as - // they grow and toward it as they shrink. - if affects_density { + // they grow and toward it as they shrink. Shift keeps the instances where + // they are, so the set's density stays as it was. + if spread { n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); } } @@ -1221,3 +1259,60 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "count": count })) } + +/// Move the paint of instance `id`'s stain or style (`fill`, with its amount) toward `to` by `t`, +/// keeping the amount. An instance without a stain or style, or one whose paint does not change, is +/// left as it is. Returns whether it changed. +fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool { + let Some((own, amount)) = fill.filter(|(_, o)| *o > 0.0) else { return false }; + let paint = vectorcraft_doc::blend::lerp_paint(&own, to, t.clamp(0.0, 1.0) as f32); + if paint == own { + return false; + } + let Some(n) = d.node_mut(id) else { return false }; + n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); + let mut f = FillLayer::new(paint); + f.opacity = (amount as f32).min(1.0); + n.appearance.items.insert(0, AppearanceItem::Fill(f)); + true +} + +/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them +/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and +/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how +/// many moved. +fn restack(d: &mut Document, ids: &std::collections::HashSet, back: bool) -> Result { + let mut parents: Vec> = vec![]; + for id in ids { + let par = d.parent_of(*id); + if !parents.contains(&par) { + parents.push(par); + } + } + let mut moved = 0; + for par in parents { + let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); + let ch = d.children_mut(par)?; + let len = Node::guide_run_start(ch); + if len <= floor + 1 { + continue; + } + let picked = |n: &Arc| ids.contains(&n.id); + if back { + for i in floor + 1..len { + if picked(&ch[i]) && !picked(&ch[i - 1]) { + ch.swap(i - 1, i); + moved += 1; + } + } + } else { + for i in (floor..len - 1).rev() { + if picked(&ch[i]) && !picked(&ch[i + 1]) { + ch.swap(i, i + 1); + moved += 1; + } + } + } + } + Ok(moved) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 47bb05b696..53d8633178 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -194,6 +194,7 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbolism_options; +mod symbolism_shift; mod symbollib; mod targeting; mod textcombos; diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs new file mode 100644 index 0000000000..e9ebea9c33 --- /dev/null +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -0,0 +1,209 @@ +//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking +//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler +//! keeping their amount while the color or style changes. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::Point; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" and nothing selected. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + s +} + +/// An instance of Dot centered on (`x`, `y`), not selected. +fn dot(s: &mut Session, x: f64, y: f64) -> NodeId { + let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + id +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn center(s: &Session, id: NodeId) -> Point { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO, + other => panic!("not an instance: {other:?}"), + } +} + +fn width(s: &Session, id: NodeId) -> f64 { + node(s, id).geometric_bounds().unwrap().width() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn state(s: &Session) -> (Document, usize) { + ((*s.doc().unwrap().doc).clone(), undo_len(s)) +} + +fn adjust(s: &mut Session, p: Value) -> Value { + s.execute("symbol.adjust", &p).unwrap() +} + +/// The children of symbol set `set`, in stacking order (the first is at the back). +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// The instance's fill: its color as RGB and its amount. +fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> { + node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity)) +} + +/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected. +fn row(s: &mut Session) -> (NodeId, Vec) { + let pts: Vec = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(s, set); + assert_eq!(ids.len(), 4); + (set, ids) +} + +/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in +/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas. +#[test] +fn shift_click_with_the_shifter_changes_the_stacking_order() { + let mut s = session(); + let (set, ids) = row(&mut s); + let centers: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let click = |s: &mut Session, x: f64, alt: bool| { + adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone() + }; + let steps = undo_len(&s); + assert_eq!(click(&mut s, 120.0, false), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::>(), centers, "nothing moves on the canvas"); + assert_eq!(click(&mut s, 120.0, false), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]); + // Already in front of the others: nothing changes and no undo step is added. + let before = state(&s); + assert_eq!(click(&mut s, 120.0, false), 0); + assert!(state(&s) == before); + // Alt sends it back one place at a time; at the back it stays. + assert_eq!(click(&mut s, 120.0, true), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]); + click(&mut s, 120.0, true); + click(&mut s, 120.0, true); + assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]); + assert_eq!(click(&mut s, 120.0, true), 0); + // Two instances under the brush move together past the next one. + s.execute("edit.undo", &json!({})).unwrap(); + let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true})); + assert_eq!(both["count"], 2); + assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]); + // Without Shift a drag moves the instances, as before. + adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10})); + assert!(center(&s, ids[3]).x > centers[3].x); +} + +/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even +/// with Resizing Affects Density. +#[test] +fn shift_with_the_sizer_keeps_the_density() { + let at = |affects: bool, shift: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + adjust( + &mut s, + json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}), + ); + (center(&s, a), width(&s, a)) + }; + let (moved, _) = at(true, false); + assert!(moved.x > 220.5, "{moved:?}"); + let (kept, grown) = at(true, true); + assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}"); + // It resizes as the Sizer does with Resizing Affects Density off. + assert_eq!(at(false, false), (kept, grown)); + assert_eq!(at(false, true), (kept, grown)); +} + +/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill +/// color; an instance without a stain is left as it is. +#[test] +fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() { + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let (red, amount) = fill(&s, a).unwrap(); + assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}"); + let stain = |s: &mut Session, x: f64| { + adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true})) + }; + assert_eq!(stain(&mut s, 100.0)["count"], 1); + let (color, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount, "the amount stays"); + assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}"); + // More strokes go on toward blue, with the amount still the same. + for _ in 0..30 { + stain(&mut s, 100.0); + } + let (bluer, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}"); + // Alt has no effect with Shift. + let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true}); + adjust(&mut s, green.clone()); + let plain = fill(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + let mut with_alt = green; + with_alt["alt"] = json!(true); + adjust(&mut s, with_alt); + assert_eq!(fill(&s, a), plain); + // No stain on b: nothing changes and no undo step is added. + let before = state(&s); + assert_eq!(stain(&mut s, 300.0)["count"], 0); + assert!(state(&s) == before && fill(&s, b).is_none()); +} + +/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its +/// fill toward the selected style's fill. +#[test] +fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + // A red stain at part strength. + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let (red, amount) = fill(&s, a).unwrap(); + assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}"); + // Half the brush's strength at a point 2.5 pt from the instance: half way to blue. + adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true})); + let (mixed, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}"); + // At the brush's center with full intensity it takes the style's fill. + adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true})); + let (blue, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}"); +} + +/// A `shift` that is not true, false or null is refused and changes nothing. +#[test] +fn a_bad_shift_is_refused() { + let mut s = session(); + dot(&mut s, 100.0, 150.0); + for tool in ["shift", "size", "stain", "style"] { + let before = state(&s); + let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}"); + assert!(state(&s) == before); + } +} diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index f407792170..2b810ddd61 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -48,6 +48,8 @@ pub struct SymbolismTool { active: bool, hover: Option, alt: bool, + /// Shift was held when the drag began (the Shifter, Sizer, Stainer and Styler have a Shift form). + shift: bool, /// Brush diameter in points. pub diameter: f64, /// 1..10. @@ -97,6 +99,7 @@ impl SymbolismTool { active: false, hover: None, alt: false, + shift: false, diameter: 80.0, intensity: 5.0, density: 5.0, @@ -179,6 +182,9 @@ impl SymbolismTool { v["proportional"] = json!(self.proportional); v["affectsDensity"] = json!(self.affects_density); } + if self.shift && matches!(tool, "shift" | "size" | "stain" | "style") { + v["shift"] = json!(true); + } ("symbol.adjust".into(), v) } } @@ -213,6 +219,7 @@ impl Tool for SymbolismTool { self.previewed = 1; self.active = true; self.alt = ev.mods.alt; + self.shift = ev.mods.shift; let (c, v) = self.command(cx); vec![Action::Begin(self.label().into()), Action::Preview(c, v)] } @@ -536,6 +543,39 @@ mod tests { assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); } + /// A drag begun with Shift sends `shift` with the Shifter, Sizer, Stainer and Styler, and only + /// with them; one begun without it sends none. + #[test] + fn shift_reaches_the_tools_that_have_a_shift_form() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let shifted = Mods { shift: true, ..Default::default() }; + for (id, sends) in [ + ("symbolShifter", true), + ("symbolSizer", true), + ("symbolStainer", true), + ("symbolStyler", true), + ("symbolScruncher", false), + ("symbolSpinner", false), + ("symbolScreener", false), + ("symbolSprayer", false), + ] { + let mut t = SymbolismTool::new(id); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0).with_mods(shifted)); + let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") }; + assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id}"); + // The drag keeps the Shift it began with. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 5.0)); + let Action::Preview(_, v) = &a[0] else { panic!("{a:?}") }; + assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id} drag"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 60.0, 5.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)); + let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") }; + assert!(v.get("shift").is_none(), "{id} without Shift: {v}"); + } + } + /// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is /// User Defined. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 3bafb737c6..a48458f075 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3167,6 +3167,20 @@ already walks Image Trace. Short agent entry points: instances moved. - A `method`, an attribute or a density outside these values, a pressure that isn't a number, or no symbol set among the objects of `symbol.setDensity`, is an error and changes nothing. +- The symbolism tools with Shift held ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), + [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)) send + `shift: true` with `symbol.adjust`: a Shift-click with the Symbol Shifter brings the instances under the brush + forward in the stacking order and Alt+Shift sends them backward; the Symbol Sizer keeps the set's density while it + resizes; the Symbol Stainer and the Symbol Styler keep the amount of stain or style and move the color or style + toward the current fill or the selected style. VectorCraft's own rules: + - The Shifter moves each instance within `radius` of any stroke point one place forward among its siblings (with + `alt`, one place backward), past the next one that is not under the brush, once for the whole stroke. It does not + move them on the canvas. It returns `{count}`, the instances that moved. + - The Sizer keeps each instance's center where it is, even with `affectsDensity`. + - The Stainer moves an instance's paint toward `color` by the tool's amount at its distance from the point, and the + Styler toward the style by the brush's strength there, whatever `method` is. An instance without a stain or style + is left as it is, and `alt` has no effect. + - No undo step is added when nothing moves or changes. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bd5fd1c8b8..c071cd7b74 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -983,6 +983,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. + - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). From dba9c8066d45df585ceab9aecca42cfdd6339a29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:48:17 -0800 Subject: [PATCH 02/15] Symbols: Shift with the Symbol Stainer and Styler keeps the instance's other fills The paint of the topmost fill changes in place, so its blend mode, effects and the instance's other appearance items stay as they are. --- crates/engine/src/cmd/brushsym/symbols.rs | 16 +++++++--------- crates/engine/src/tests/symbolism_shift.rs | 10 ++++++++++ 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 46a6b5b3c3..e8e99117cc 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1260,20 +1260,18 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": count })) } -/// Move the paint of instance `id`'s stain or style (`fill`, with its amount) toward `to` by `t`, -/// keeping the amount. An instance without a stain or style, or one whose paint does not change, is -/// left as it is. Returns whether it changed. +/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount) +/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's +/// other appearance items stay as they are. An instance without a stain or style, or one whose +/// paint does not change, is left as it is. Returns whether it changed. fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool { - let Some((own, amount)) = fill.filter(|(_, o)| *o > 0.0) else { return false }; + let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false }; let paint = vectorcraft_doc::blend::lerp_paint(&own, to, t.clamp(0.0, 1.0) as f32); if paint == own { return false; } - let Some(n) = d.node_mut(id) else { return false }; - n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); - let mut f = FillLayer::new(paint); - f.opacity = (amount as f32).min(1.0); - n.appearance.items.insert(0, AppearanceItem::Fill(f)); + let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false }; + f.paint = paint; true } diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs index e9ebea9c33..391c267844 100644 --- a/crates/engine/src/tests/symbolism_shift.rs +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -140,6 +140,15 @@ fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() { adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); let (red, amount) = fill(&s, a).unwrap(); assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}"); + // A second fill below the stain, which Shift leaves as it is. + s.edit("Add fill", |d, _| { + let n = d.node_mut(a).unwrap(); + let lower = n.appearance.fill().unwrap().clone(); + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower })); + Ok(()) + }) + .unwrap(); + let lower = node(&s, a).appearance.items[0].clone(); let stain = |s: &mut Session, x: f64| { adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true})) }; @@ -147,6 +156,7 @@ fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() { let (color, kept) = fill(&s, a).unwrap(); assert_eq!(kept, amount, "the amount stays"); assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}"); + assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays"); // More strokes go on toward blue, with the amount still the same. for _ in 0..30 { stain(&mut s, 100.0); From 9590e0f35a9e3bc31ba06023cfb4a0d0439569b5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:56:27 -0800 Subject: [PATCH 03/15] Symbolism: copied sets keep their density, and the options dialog scrolls - A symbol set duplicated in the same document gets the Symbol Set Density recorded for its source, and a pasted set gets the density recorded for it at Copy (also after Cut, after the source changed, and in another document), so symbol.setDensity spaces the copy from that density. A set with no record at Copy pastes with none. Document::reid copies the record only when the source is the document's own node with that id; the clipboard carries the records. - symbol.adjust counts only the instances it changed: an instance the brush reached but left as it was (the Symbol Screener at a limit) is not counted, and a stroke that changes none adds no undo step. - Method Average gives the Symbol Sprayer's new instance and the Symbol Screener's instances the mean opacity also when it is below 5%. - With Use Pressure Pen, a pressure change of 0.05 or more within a step of the last point gives that point the new pressure. Once a drag has its most points, a change away from the last point is not kept, and a pressure change on a long stroke waits for the next preview or the release instead of sending the whole stroke again. - The Symbolism Tools Options rows scroll, so OK and Cancel stay in view in a short window. --- crates/doc/src/document_guides.rs | 62 ++++++++++++++ crates/doc/src/tests.rs | 37 +++++++++ crates/engine/src/cmd/brushsym/symbolism.rs | 5 +- crates/engine/src/cmd/brushsym/symbols.rs | 8 +- crates/engine/src/cmd/clipboard.rs | 3 + crates/engine/src/cmd/clipboard/resources.rs | 1 + crates/engine/src/cmd/edit.rs | 2 + crates/engine/src/tests/symbolism_options.rs | 81 ++++++++++++++++++ crates/tools/src/symbolism.rs | 83 +++++++++++++++++-- .../ui-egui/src/dialogs/symbolism_options.rs | 44 +++++++++- docs/mcp.md | 3 +- 11 files changed, 315 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ba6e4dc428..ba203610d6 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -500,11 +500,73 @@ impl Document { self.patterns.iter_mut().find(|p| p.name == name) } + /// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`. + /// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and + /// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy. + pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity"; + + /// The Symbol Set Densities recorded for `nodes` and their descendants, by id. + pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap { + let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() }; + let mut out = std::collections::BTreeMap::new(); + let mut stack: Vec<&Node> = nodes.iter().collect(); + while let Some(n) = stack.pop() { + if let Some(v) = record.get(&n.id.0.to_string()) { + out.insert(n.id, v.clone()); + } + stack.extend(n.children().into_iter().flatten().map(|c| &**c)); + } + out + } + + /// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set + /// Densities that `densities` holds for `source` and its descendants, and none for those it + /// holds none for (whatever [`Self::reid`] recorded). + pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap) { + if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) { + return; + } + let mut pairs = vec![(source, copy)]; + while let Some((s, c)) = pairs.pop() { + match densities.get(&s.id) { + Some(v) => { + if let serde_json::Value::Object(m) = + self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default())) + { + m.insert(c.id.0.to_string(), v.clone()); + } + } + None => { + if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) { + m.remove(&c.id.0.to_string()); + } + } + } + if let (Some(sc), Some(cc)) = (s.children(), c.children()) { + pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b))); + } + } + } + /// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken /// in ([`Self::adopt_pixels`]). pub fn reid(&mut self, node: &Node) -> Node { let mut n = node.clone(); n.id = self.alloc_id(); + // A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source + // is this document's node with that id; a node from another document may share the id of an + // unrelated set here. + let density = self + .unknown + .get(Self::SYMBOL_SET_DENSITY_KEY) + .and_then(|m| m.get(node.id.0.to_string())) + .filter(|_| self.node(node.id) == Some(node)) + .cloned(); + if let Some(v) = density + && let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) + { + m.insert(n.id.0.to_string(), v); + } if let NodeKind::Image(im) = &mut n.kind { self.adopt_image_pixels(im); } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index dcbcd87028..0801187b6d 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() { assert!(!ids.contains(&a) && !ids.contains(&b)); } +/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from +/// another document with the same id does not. +#[test] +fn reid_copies_the_set_density_of_the_documents_own_node() { + let (mut d, a, _) = doc_with_rects(); + d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 })); + let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned(); + let own = d.node(a).cloned().unwrap(); + let copy = d.reid(&own); + assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0))); + let foreign = Node::group(a, vec![]); + let copy = d.reid(&foreign); + assert_eq!(density(&d, copy.id), None); +} + +/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy +/// recorded none, whatever [`Document::reid`] found for an identical node in the document. +#[test] +fn carry_set_densities_gives_the_densities_recorded_at_copy() { + let (mut d, a, b) = doc_with_rects(); + d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 })); + let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned(); + let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap()); + // Copy recorded nothing for `a`: the copy reid gave a density loses it. + let copy = d.reid(&na); + assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0))); + d.carry_set_densities(&na, ©, &Default::default()); + assert_eq!(density(&d, copy.id), None); + // Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7. + let g = d.alloc_id(); + let group = Node::group(g, vec![Arc::new(nb)]); + let copy = d.reid(&group); + d.carry_set_densities(&group, ©, &[(b, serde_json::json!(7.0))].into_iter().collect()); + let inner = copy.children().unwrap()[0].id; + assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0)))); +} + #[test] fn setup_round_trips_and_old_files_load() { let (mut d, _, _) = doc_with_rects(); diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index f5df078745..0be2ee37f8 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -84,8 +84,9 @@ pub(super) fn spacing(density: f64) -> f64 { } /// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written -/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it. -const SET_DENSITY_KEY: &str = "symbolSetDensity"; +/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a +/// copy of a set by [`Document::reid`]. +const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY; /// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded). fn set_density_of(d: &Document, set: NodeId) -> Option { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index e8e99117cc..2319e02810 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -975,7 +975,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { if modes.screen && let Some(m) = near { - n.opacity = (m.opacity as f32).clamp(0.05, 1.0); + n.opacity = (m.opacity as f32).clamp(0.0, 1.0); } // The stain and the style are both the instance's fill: the style, set last, replaces // the stain, an averaged one too when the instances under the brush have a fill. @@ -1113,7 +1113,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { }; let spread = affects_density && !shift; // No undo step when no instance changes (none under the brush, or Average with each at the mean). - let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |before, d| { let mut touched = std::collections::BTreeSet::new(); for (j, (q, pressure)) in pts.iter().enumerate() { let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; @@ -1247,7 +1247,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { _ => { let step = (0.1 * w * share) as f32; n.opacity = match &target { - Some(t) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.05, 1.0), + Some(t) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.0, 1.0), None if alt => (n.opacity + step).min(1.0), None => (n.opacity - step).max(0.05), }; @@ -1255,6 +1255,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } } } + // An instance the brush reached but left as it was (at a limit already) is not counted. + touched.retain(|id| d.node(*id) != before.node(*id)); Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 4e086569ae..a25dc857dd 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -100,6 +100,9 @@ pub struct Clipboard { /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. pub guides: Vec, + /// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in + /// [`Self::nodes`]: a pasted set packs from it. + pub set_densities: BTreeMap, } /// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index f457712415..29c562d1dc 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1071,6 +1071,7 @@ impl Clipboard { char_styles: pick(Res::CharStyle, &src.char_styles), para_styles: pick(Res::ParaStyle, &src.para_styles), brushes, + set_densities: src.set_densities_of(&nodes), nodes, ..Default::default() } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 00b6a338f2..09e6178b82 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1454,6 +1454,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for xf in placements { for (k, n) in clip.nodes.iter().enumerate() { let mut c = d.reid(n); + // A pasted symbol set packs from the density recorded for it at Copy. + d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c); let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 05b707f799..061fbe41c3 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -136,6 +136,48 @@ fn average_at_the_mean_adds_no_undo_step() { assert!(state(&s) == before); } +/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque +/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke +/// that changes no instance adds no undo step. +#[test] +fn an_instance_left_as_it_is_is_not_counted() { + let mut s = session(); + let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0)); + s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap(); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true})); + assert_eq!(r["count"], 0, "Alt on an opaque instance"); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10})); + assert_eq!(r["count"], 0, "an instance at 5%"); + assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history"); + // A stroke over both counts only the instance it changes. + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10})); + assert_eq!(r["count"], 1); + assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05); +} + +/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and +/// the Symbol Screener's instances take the mean of the instances under the brush. +#[test] +fn average_keeps_a_mean_opacity_below_five_percent() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let first = members(&s, set)[0]; + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap(); + s.select(|_, sel| sel.set([set])).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap(); + let sprayed = *members(&s, set).last().unwrap(); + assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity); + // Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it. + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap(); + s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap(); + adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}"); +} + /// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. #[test] fn average_evens_out_the_stain_and_the_spacing() { @@ -508,6 +550,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() { assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); } +/// A set duplicated packs from the density recorded for its source, and a pasted set from the +/// density its source had at Copy: after Cut, after the source is given another density, and in +/// another document. +#[test] +fn a_copied_set_packs_from_the_density_of_its_source() { + for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] { + let mut s = session(); + let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.set([set])).unwrap(); + let first = match copy { + "duplicate" => "edit.duplicate", + "cut" => "edit.cut", + _ => "edit.copy", + }; + s.execute(first, &json!({})).unwrap(); + if copy == "changed after copy" { + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + } + if copy == "other document" { + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + } + if copy != "duplicate" { + s.execute("edit.paste", &json!({})).unwrap(); + } + let copied = s.doc().unwrap().selection.objects.clone(); + assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}"); + let ids = members(&s, copied[0]); + let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>(); + let was = xs(&s); + let middle = was.iter().sum::() / 4.0; + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap(); + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}"); + } + } +} + /// A locked instance of the set stays where it is, and the others move. #[test] fn set_density_leaves_a_locked_instance_in_place() { diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index f01b1b7f0a..c2672e16c1 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -11,7 +11,9 @@ use serde_json::{Value, json}; use vectorcraft_geom::{Point, Shape}; use crate::draw2::{FEEDBACK, GestureTool, points_json}; -use crate::{Action, Cursor, MAX_STROKE_SAMPLES, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, previews_at}; +use crate::{ + Action, Cursor, MAX_STROKE_SAMPLES, Mods, Overlay, PREVIEW_ALL_UNTIL, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, previews_at, +}; /// Create a symbolism tool or the brush-aware Paintbrush (None = not one of ours). pub fn create(id: &str) -> Option> { @@ -29,6 +31,10 @@ pub const METHODS: [&str; 3] = ["userDefined", "average", "random"]; /// The values of each Symbol Sprayer option in the Symbolism Tools Options. pub const SPRAY_MODES: [&str; 2] = ["average", "userDefined"]; +/// The smallest change of pen pressure, with Use Pressure Pen, that a drag sample within a step of +/// the last point gives that point. VectorCraft's own value. +const PRESSURE_STEP: f64 = 0.05; + /// The Symbol Sprayer options: (tool option, key in `symbol.spray`'s `attributes`). pub const SPRAY_ATTRIBUTES: [(&str, &str); 6] = [ ("sprayScrunch", "scrunch"), @@ -227,11 +233,27 @@ impl Tool for SymbolismTool { // Sprayer: thin the samples to a fraction of the brush; others: every few pixels. let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) }; // Each preview carries every point so far: a long drag stops growing and previews less often. - if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|(l, _)| l.distance(p) < step) { - return vec![]; - } - self.points.push(sample); - if !previews_at(self.points.len()) { + let full = self.points.len() >= MAX_STROKE_SAMPLES; + let near = self.points.last().is_some_and(|(l, _)| l.distance(p) < step); + let pressed = match self.points.last_mut().filter(|_| full || near) { + // With Use Pressure Pen, the last point takes a pressure change made within a step of it. + Some(last) if near && self.use_pressure && (sample.1 - last.1).abs() >= PRESSURE_STEP => { + last.1 = sample.1; + true + } + Some(_) => return vec![], + None => { + self.points.push(sample); + false + } + }; + // A pressure change adds no point: past the points that all preview, it waits for the + // next preview or the release, so a long stroke is not sent again for each change. + if !previews_at(self.points.len()) || (pressed && self.points.len() > PREVIEW_ALL_UNTIL) { + // A changed pressure on a point already shown leaves the preview out of date. + if pressed { + self.previewed = 0; + } return vec![]; } self.previewed = self.points.len(); @@ -546,6 +568,55 @@ mod tests { assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); } + /// With Use Pressure Pen, a pressure change within a step of the last point gives that point the + /// new pressure and previews it; a smaller change, or one without the option, adds nothing. + #[test] + fn a_pressure_change_in_place_is_kept() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let at = |kind, x: f64, pressure: f32| PointerEvent { pressure, ..PointerEvent::new(kind, x, 5.0) }; + for use_pressure in [true, false] { + let mut t = SymbolismTool::new("symbolSizer"); + t.set_option("usePressure", &json!(use_pressure)); + t.pointer(&cx, &at(PointerKind::Down, 5.0, 0.0)); + let a = t.pointer(&cx, &at(PointerKind::Drag, 6.0, 0.8)); + if use_pressure { + let [Action::Preview(_, v)] = a.as_slice() else { panic!("{a:?}") }; + assert_eq!(v["points"], json!([[5.0, 5.0, f64::from(0.8f32)]])); + assert_eq!(t.pointer(&cx, &at(PointerKind::Drag, 6.5, 0.82)), vec![]); + } else { + assert_eq!(a, vec![]); + } + assert_eq!(t.pointer(&cx, &at(PointerKind::Up, 6.5, 0.0)), vec![Action::Commit]); + } + } + + /// Once a drag has its most points, a pressure change away from the last point leaves that + /// point's pressure as it was. + #[test] + fn a_pressure_change_away_from_the_last_point_of_a_full_drag_is_not_kept() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let at = |kind, x: f64, pressure: f32| PointerEvent { pressure, ..PointerEvent::new(kind, x, 5.0) }; + let mut t = SymbolismTool::new("symbolSizer"); + t.set_option("usePressure", &json!(true)); + t.pointer(&cx, &at(PointerKind::Down, 0.0, 0.5)); + t.points = (0..MAX_STROKE_SAMPLES).map(|i| (Point::new(50.0 * i as f64, 5.0), 0.5)).collect(); + let far = 50.0 * (MAX_STROKE_SAMPLES + 10) as f64; + assert_eq!(t.pointer(&cx, &at(PointerKind::Drag, far, 1.0)), vec![]); + assert_eq!((t.points.len(), t.points.last().map(|(_, pressure)| *pressure)), (MAX_STROKE_SAMPLES, Some(0.5))); + // Within a step of the last point the change is kept, and the long stroke is not previewed + // again for it: the release sends it. + let last = 50.0 * (MAX_STROKE_SAMPLES - 1) as f64; + assert_eq!(t.pointer(&cx, &at(PointerKind::Drag, last + 1.0, 1.0)), vec![]); + assert_eq!(t.points.last().map(|(_, pressure)| *pressure), Some(1.0)); + let a = t.pointer(&cx, &at(PointerKind::Up, last + 1.0, 0.0)); + assert!(matches!(a.first(), Some(Action::Preview(_, v)) if v["points"].as_array().map(Vec::len) == Some(MAX_STROKE_SAMPLES)), "{}", a.len()); + assert_eq!(a.last(), Some(&Action::Commit)); + } + /// A drag begun with Shift sends `shift` with the Shifter, Sizer, Stainer and Styler, and only /// with them; one begun without it sends none. #[test] diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 524b4e5c8c..c930e5de37 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::settings::SYMBOLISM; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, modal, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -55,6 +55,13 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + // The rows scroll when the window is shorter than they are, so the heading and the buttons + // stay in view. + modal::scrolled_rows(ui, "symbolism-options-rows", |ui| rows(app, ui, d)); + false +} + +fn rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let unit = app.session.general_unit(); // The tool whose options show below (the eight tools share one toolbar icon, so they are listed // by name). @@ -103,7 +110,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(10.0); form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); - false } /// The selected symbol sets. @@ -130,6 +136,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { #[cfg(test)] mod tests { use super::*; + use egui_kittest::kittest::Queryable; use vectorcraft_engine::Session; fn app() -> VectorcraftApp { @@ -142,6 +149,39 @@ mod tests { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) } + /// In a short window the rows scroll, and the heading, OK and Cancel stay on the screen. + #[test] + fn the_buttons_stay_in_view_in_a_short_window() { + let mut app = app(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for (physical, zoom) in [(egui::vec2(1366.0, 768.0), 1.5), (egui::vec2(1280.0, 720.0), 1.5), (egui::vec2(800.0, 600.0), 1.0)] { + h.ctx.set_zoom_factor(zoom); + for _ in 0..12 { + h.set_size(physical / zoom); + h.run_steps(1); + } + let screen = h.ctx.content_rect(); + let heading = h.get_by_role_and_label(egui::accesskit::Role::Label, "Symbolism Tools Options").rect(); + assert!(screen.contains_rect(heading), "{physical:?} at {zoom}: the heading {heading:?} in {screen:?}"); + for label in ["OK", "Cancel"] { + let rect = h.get_by_label(label).rect(); + assert!(screen.contains_rect(rect), "{physical:?} at {zoom}: {label} {rect:?} in {screen:?}"); + } + } + } + #[test] fn the_symbolism_tools_share_the_options_ok_sets() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 991140e3b9..1056f256c4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3324,7 +3324,8 @@ already walks Image Trace. Short agent entry points: style. `attributes` left out means `average` for all six. - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and - adds none when no instance moves. `from` is the density each set was created at or last given, and the + adds none when no instance moves. `from` is the density each set was created at or last given (a set + duplicated has its source's, and a pasted set the one its source had at Copy), and the `from` passed applies only to a set without one (a group named "Symbol Set" by hand); the sets moved then have density `to`. A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the instances moved. From c883b808cce7ed2b601a2530b807da0c3a6f5e5a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 09:17:13 -0800 Subject: [PATCH 04/15] Symbolism: a bad pen pressure is refused on a point without coordinates symbol.adjust and symbol.spray skip a point whose x or y is not a number, and the pressure check came after that skip, so a stroke with a point such as [null, 0, "bad"] beside a valid one was applied. The pressure is now checked first, and the command fails with the bad-pressure error and leaves the document as it was. --- crates/engine/src/cmd/brushsym/symbols.rs | 3 ++- crates/engine/src/tests/symbolism_options.rs | 7 +++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 2319e02810..7f727e3147 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -854,11 +854,12 @@ fn samples(p: &Value, cmd: &str) -> Result> { let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; let mut v = Vec::with_capacity(a.len()); for q in a { - let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; + // The pressure is checked first: a point skipped for its coordinates still has a bad one refused. let pressure = match q.get(2) { None | Some(Value::Null) => 1.0, Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?, }; + let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; v.push((Point::new(x, y), pressure.clamp(0.0, 1.0))); } if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) { diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 061fbe41c3..62d4188e3d 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -296,6 +296,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() { json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), "a point's pressure must be a number, not \"hard\"", ); + // Also on a point without coordinates, beside one that has them. + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}), + "a point's pressure must be a number, not \"bad\"", + ); } for key in ["usePressure", "proportional", "affectsDensity"] { let mut p = json!({"tool": "size", "points": [[200, 150]]}); From b782cfbd9e03b490b32e01385cbd6b37a5673564 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 10:31:46 -0800 Subject: [PATCH 05/15] Symbolism: the Symbol Styler applies the style picked in Graphic Styles A click that puts a style into the Graphic Styles panel's selection now sets it as the Symbol Styler's style, and the Styler keeps it when another tool is active. A style name the document has no style for (one picked in another document, renamed or deleted) moves instances toward the document's first style after the default one, as no name does, instead of toward the current fill. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 14 ++++++----- crates/engine/src/tests/symbolism_shift.rs | 20 +++++++++++++++ crates/tools/src/settings.rs | 2 ++ crates/ui-egui/src/panels/graphic_styles.rs | 27 +++++++++++++++------ docs/mcp.md | 4 ++- docs/target-app-parity.md | 2 +- 7 files changed, 54 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index a9fabb5446..abe9cca786 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. No undo step is added when no instance changes (none under the brush, average with each already at the mean, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. No undo step is added when no instance changes (none under the brush, average with each already at the mean, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 7f727e3147..50212848a6 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -868,13 +868,15 @@ fn samples(p: &Value, cmd: &str) -> Result> { Ok(v) } -/// The fill of the graphic style `p` names with `style`, else of the document's first style after -/// the default one. +/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no +/// style for, such as the Symbol Styler's style from another document) of the document's first +/// style after the default one. fn style_paint(d: &Document, p: &Value) -> Option { - match str_param(p, "style") { - Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - } + str_param(p, "style") + .and_then(|n| d.graphic_styles.iter().find(|g| g.name == n)) + .or(d.graphic_styles.get(1)) + .or(d.graphic_styles.first()) + .map(|g| g.appearance.fill_paint()) } /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs index 391c267844..aa081e4386 100644 --- a/crates/engine/src/tests/symbolism_shift.rs +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -205,6 +205,26 @@ fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() { assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}"); } +/// A style name the document has no style for (the Styler's style from another document, or one +/// since renamed or deleted) moves the fill toward the same style as no name. +#[test] +fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() { + let styled = |style: Option<&str>| { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true}); + if let Some(n) = style { + p["style"] = json!(n); + } + adjust(&mut s, p); + fill(&s, a).unwrap() + }; + assert_eq!(styled(Some("No Such Style")), styled(None)); +} + /// A `shift` that is not true, false or null is refused and changes nothing. #[test] fn a_bad_shift_is_refused() { diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 3132c640a4..ce633bbf84 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -44,6 +44,8 @@ const ROWS: &[Row] = &[ "affectsDensity", ], ), + // The graphic style the Symbol Styler applies, set from the Graphic Styles panel. + (&["symbolStyler"], None, &["style"]), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d7b622ba77..f643630ee4 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -1,12 +1,13 @@ //! Graphic Styles panel: the document's styles as rendered thumbnails (Thumbnail View) or rows //! (Small and Large List View), shown on a square or on type. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from -//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list, or applies it -//! to the art it is dropped on (`canvas::panel_drop`); art dragged off the canvas or the Appearance -//! panel's thumbnail dropped on the panel becomes a new style. Holding the right button on a style -//! shows it large, on the selected object when there is one. The Control bar's Style picker lists -//! the same tiles ([`picker`]). Graphic style libraries open in library panels +//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one. The +//! style last clicked into the selection is the one the Symbol Styler applies. Double-click opens +//! Graphic Style Options. Dragging a style moves it in the list, or applies it to the art it is +//! dropped on (`canvas::panel_drop`); art dragged off the canvas or the Appearance panel's +//! thumbnail dropped on the panel becomes a new style. Holding the right button on a style shows +//! it large, on the selected object when there is one. The Control bar's Style picker lists the +//! same tiles ([`picker`]). Graphic style libraries open in library panels //! ([`GraphicStyleLibraries`]). use std::cell::RefCell; @@ -434,6 +435,10 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { Some(Click::Pick(name, m)) => { let order: Vec<&str> = s.d.graphic_styles.iter().map(|g| g.name.as_str()).collect(); let sel = super::swatches::click_selection(ui, "gs-anchor", selected(ui.ctx(), s.d), &order, &name, m); + // The style clicked into the selection is the one the Symbol Styler applies. + if sel.contains(&name) { + app.run("tool.setOption", json!({"tool": "symbolStyler", "values": {"style": name}})).ok(); + } set_pstate(ui.ctx(), "gs-sel", sel); // A plain click also applies the style (with nothing selected the next object drawn // takes it); Shift and Cmd/Ctrl clicks only select. @@ -1016,15 +1021,21 @@ mod tests { selected(&ctx, &app.session.active().unwrap().doc.clone()) }; let linked = |app: &VectorcraftApp| app.session.selection_graphic_style().map(|(g, _)| g.name.clone()); - // A plain click applies the style and selects it alone. + let styler = |app: &VectorcraftApp| app.session.tool_options_of("symbolStyler")["style"].as_str().map(str::to_string); + // A plain click applies the style and selects it alone; the Symbol Styler takes it. assert_eq!(click(&mut app, 0, egui::Modifiers::NONE), [n[0].clone()]); assert_eq!(linked(&app).as_ref(), Some(&n[0])); + assert_eq!(styler(&app).as_ref(), Some(&n[0])); // Shift-click selects from that style to the clicked one, and applies nothing. assert_eq!(click(&mut app, 3, egui::Modifiers::SHIFT), n[..4]); assert_eq!(linked(&app).as_ref(), Some(&n[0])); - // Cmd/Ctrl-click removes a selected style and adds it back. + assert_eq!(styler(&app).as_ref(), Some(&n[3])); + // Cmd/Ctrl-click removes a selected style and adds it back; the Styler keeps its style + // while one is removed. assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone()]); + assert_eq!(styler(&app).as_ref(), Some(&n[3])); assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone(), n[2].clone()]); + assert_eq!(styler(&app).as_ref(), Some(&n[2])); // Shift-click extends from the style Cmd/Ctrl-clicked last. click(&mut app, 0, egui::Modifiers::NONE); click(&mut app, 2, egui::Modifiers::COMMAND); diff --git a/docs/mcp.md b/docs/mcp.md index 1c0fb16e96..e6ab6e472a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3304,7 +3304,9 @@ already walks Image Trace. Short agent entry points: [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` - `proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes` + `proportional` (true) and `affectsDensity` (false). With `tool: style`, a `style` name the document has no graphic style + for counts as none (the document's first style after the default one). The Symbol Styler sends the style last + clicked into the Graphic Styles panel's selection. `symbol.spray` takes `attributes` `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and `style` for the User Defined stain and style. `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol sets a new Symbol Set Density. VectorCraft's own rules: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7d7b15000b..2608039e24 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1023,7 +1023,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. - - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`. + - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). From 8ed0bd80a75b9fe23663ad72acf46f541bc40665 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:24:09 -0800 Subject: [PATCH 06/15] Symbolism: tool.setOption refuses bad Symbolism Tools Options values A `method` or Symbol Sprayer option that is not one of its names, a `diameter`, `intensity` or `density` that is not a number, a switch that is not true or false, and a `symbol` or `style` that is neither a name nor null are errors, and none of the values is set. The Symbolism Tools Options dialog checks the same values before it changes the selected sets' density. --- crates/engine/src/tests/symbolism_options.rs | 21 +++++++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/symbolism.rs | 31 +++++++++++++++++++ .../ui-egui/src/dialogs/symbolism_options.rs | 10 ++++++ docs/mcp.md | 5 ++- 5 files changed, 67 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 62d4188e3d..44d1427fb9 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -259,6 +259,27 @@ fn an_unknown_method_is_refused() { assert_eq!(center(&s, a), Point::new(200.0, 150.0)); } +/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the +/// tool's options stay as they were. +#[test] +fn tool_set_option_refuses_bad_symbolism_options() { + let mut s = session(); + let before = s.tool_options_of("symbolSizer"); + for (key, bad, want) in [ + ("method", json!("smooth"), "`method` must be userDefined, average or random, not \"smooth\""), + ("sprayStain", json!("random"), "`sprayStain` must be average or userDefined, not \"random\""), + ("usePressure", json!("yes"), "`usePressure` must be true or false"), + ("diameter", json!("big"), "`diameter` must be a number"), + ("style", json!(3), "`style` must be a name or null"), + ] { + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}})); + assert_eq!(r, Err(want.to_string()), "{key}"); + assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}"); + } + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap(); + assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined"))); +} + /// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is /// not used. A pressure that isn't a number is an error. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 66ed0a41e3..dd4acc83a5 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1338,6 +1338,7 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + vectorcraft_tools::symbolism::check_options(tool.unwrap_or(self.tool.id()), &values)?; // The Place queue is read later, by a click outside any automation scope: its files must // be readable now, under the roots of whoever sets it. if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) { diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index c2672e16c1..845052ce43 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -86,6 +86,37 @@ fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> { allowed.iter().copied().find(|a| *a == s) } +/// Check the Symbolism Tools Options `values` that `tool.setOption` sets on symbolism tool `tool`: +/// a value of the wrong kind, or a `method` or Symbol Sprayer option that is not one of its names, +/// is an error (stored preferences are not checked: an unknown value there keeps the default). +/// Other tools' options pass. +pub fn check_options(tool: &str, values: &serde_json::Map) -> Result<(), String> { + if !crate::settings::SYMBOLISM.contains(&tool) { + return Ok(()); + } + let names = |allowed: &[&str]| match allowed { + [a, b] => format!("{a} or {b}"), + [rest @ .., last] => format!("{} or {last}", rest.join(", ")), + [] => String::new(), + }; + for (key, v) in values { + let error = match key.as_str() { + "diameter" | "intensity" | "density" => (!v.as_f64().is_some_and(f64::is_finite)).then(|| format!("`{key}` must be a number")), + "usePressure" | "showBrush" | "proportional" | "affectsDensity" => (!v.is_boolean()).then(|| format!("`{key}` must be true or false")), + "symbol" | "style" => (!(v.is_string() || v.is_null())).then(|| format!("`{key}` must be a name or null")), + "method" => one_of(v, &METHODS).is_none().then(|| format!("`method` must be {}, not {v}", names(&METHODS))), + _ if SPRAY_ATTRIBUTES.iter().any(|(k, _)| k == key) => { + one_of(v, &SPRAY_MODES).is_none().then(|| format!("`{key}` must be {}, not {v}", names(&SPRAY_MODES))) + } + _ => None, + }; + if let Some(e) = error { + return Err(e); + } + } + Ok(()) +} + impl SymbolismTool { pub fn new(id: &str) -> Self { let id: &'static str = match id { diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index c930e5de37..c0878996f3 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -125,6 +125,8 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); values.extend(SWITCHES.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.bool(k))))); values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); + // A value `tool.setOption` refuses changes no density either. + vectorcraft_tools::symbolism::check_options(&d.str("tool"), &values)?; let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { @@ -281,6 +283,14 @@ mod tests { app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); super::super::confirm(&mut app).unwrap(); assert_eq!((width(&app), undo(&app)), (was, steps)); + // An option that `tool.setOption` refuses changes neither the density nor the set. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("density".into(), json!(9)); + fields.insert("method".into(), json!("smooth")); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0)); // A higher density packs the set closer, as one undo step. app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); diff --git a/docs/mcp.md b/docs/mcp.md index e6ab6e472a..d866bc8a31 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3306,7 +3306,10 @@ already walks Image Trace. Short agent entry points: `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` `proportional` (true) and `affectsDensity` (false). With `tool: style`, a `style` name the document has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler sends the style last - clicked into the Graphic Styles panel's selection. `symbol.spray` takes `attributes` + clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or + Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a + non-boolean switch, and a `symbol` or `style` that is neither a name nor null, and sets none of the values. + `symbol.spray` takes `attributes` `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and `style` for the User Defined stain and style. `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol sets a new Symbol Set Density. VectorCraft's own rules: From 11942b04d61219becad8896ae0450d8c059bd046 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:36:36 -0800 Subject: [PATCH 07/15] Symbolism: Shift recolors a pattern stain, and the options dialog refuses bad values With Shift, the Symbol Stainer and the Symbol Styler move an instance's stain or style toward the new paint. A pair with no form in between, such as a solid color and a pattern, only switched at half strength, so strokes below that never changed it. Such a paint now takes the new one at once, keeping its amount. OK in Symbolism Tools Options read a checkbox stored as a value other than true or false as false, and a number stored as text that is no number as 0, so the check passed and the density could change. Each value now goes to the check as it is stored, and a value of the wrong kind is refused with no density change. --- crates/engine/src/cmd/brushsym/symbols.rs | 14 ++++++++--- crates/engine/src/tests/symbolism_shift.rs | 22 ++++++++++++++++++ .../ui-egui/src/dialogs/symbolism_options.rs | 23 ++++++++++++++++--- docs/mcp.md | 5 ++-- docs/target-app-parity.md | 2 +- 5 files changed, 57 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 708750806b..ffb7cca8ba 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1300,11 +1300,19 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { /// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount) /// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's -/// other appearance items stay as they are. An instance without a stain or style, or one whose -/// paint does not change, is left as it is. Returns whether it changed. +/// other appearance items stay as they are. A paint with no form between it and `to` (a solid +/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still +/// reach it. An instance without a stain or style, or one whose paint does not change, is left as +/// it is. Returns whether it changed. fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool { + use vectorcraft_doc::blend::lerp_paint; let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false }; - let paint = vectorcraft_doc::blend::lerp_paint(&own, to, t.clamp(0.0, 1.0) as f32); + let t = t.clamp(0.0, 1.0) as f32; + let mut paint = lerp_paint(&own, to, t); + // `lerp_paint` switches such a pair halfway, so just below half it still gives `own`. + if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own { + paint = to.clone(); + } if paint == own { return false; } diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs index aa081e4386..c1c8bdcae0 100644 --- a/crates/engine/src/tests/symbolism_shift.rs +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -205,6 +205,28 @@ fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() { assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}"); } +/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes +/// the new paint at once, at any strength, and keeps its amount. +#[test] +fn shift_changes_a_paint_that_has_no_form_in_between() { + use vectorcraft_color::Paint; + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + s.edit("Pattern fill", |d, _| { + let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() }); + f.opacity = 0.4; + d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + Ok(()) + }) + .unwrap(); + // Low intensity, near the brush's edge: far below half strength. + let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true})); + assert_eq!(r["count"], 1); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(f.opacity, 0.4, "the amount stays"); + assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint); +} + /// A style name the document has no style for (the Styler's style from another document, or one /// since renamed or deleted) moves the fill toward the same style as no name. #[test] diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index c0878996f3..39c5b6ec9d 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -121,9 +121,15 @@ fn selected_sets(app: &VectorcraftApp) -> Vec { /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges), after giving /// a new Symbol Set Density to the selected symbol sets. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let mut values: Map = - NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - values.extend(SWITCHES.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.bool(k))))); + // Each value goes to the check as it is stored, so one of the wrong kind is refused rather than + // read as 0 or false. A number stored as text is read as the field reads it, and other text is + // refused. + let stored = |k: &str| match d.fields.get(k) { + Some(Value::String(s)) => Some(vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |n| json!(n))), + v => v.cloned(), + }; + let mut values: Map = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect(); + values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); // A value `tool.setOption` refuses changes no density either. vectorcraft_tools::symbolism::check_options(&d.str("tool"), &values)?; @@ -291,6 +297,17 @@ mod tests { assert!(super::super::confirm(&mut app).is_err()); assert_eq!((width(&app), undo(&app)), (was, steps)); assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0)); + // So does a checkbox or a number stored as a value of the wrong kind. + for (k, v) in [("usePressure", json!("invalid")), ("proportional", json!(1)), ("intensity", json!("strong")), ("diameter", json!(true))] { + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("density".into(), json!(9)); + fields.insert(k.into(), v); + assert!(super::super::confirm(&mut app).is_err(), "{k}"); + assert_eq!((width(&app), undo(&app)), (was, steps), "{k}"); + let o = app.session.tool_options_of("symbolSizer"); + assert_eq!((o["density"].as_f64(), o["usePressure"].as_bool()), (Some(5.0), Some(false)), "{k}"); + } // A higher density packs the set closer, as one undo step. app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); diff --git a/docs/mcp.md b/docs/mcp.md index 1215dd2d9d..5f9ea72ac0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3460,8 +3460,9 @@ already walks Image Trace. Short agent entry points: move them on the canvas. It returns `{count}`, the instances that moved. - The Sizer keeps each instance's center where it is, even with `affectsDensity`. - The Stainer moves an instance's paint toward `color` by the tool's amount at its distance from the point, and the - Styler toward the style by the brush's strength there, whatever `method` is. An instance without a stain or style - is left as it is, and `alt` has no effect. + Styler toward the style by the brush's strength there, whatever `method` is. A paint with no form between it and + the new one (a solid color and a pattern) takes the new one at once. An instance without a stain or style is left + as it is, and `alt` has no effect. - No undo step is added when nothing moves or changes. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 49b85c8e77..0e76908e11 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1053,7 +1053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. - - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`. + - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; a stain or style with no form between it and the new paint (a solid color and a pattern) takes the new paint at once; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). From 0e1592d76a271ad6a01dd24ceb43d94fa1e56885 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:55:27 -0800 Subject: [PATCH 08/15] Symbolism: the Symbol Styler applies the style by the brush's strength Without Shift, the Symbol Styler gave each instance under the brush the style in full (and Random a fixed share of it), whatever the intensity, the pen pressure or the instance's distance from the brush's center. It now applies the style gradually, as it does the stain: by the brush's strength at the instance, in full only at the center at intensity 10 or full pressure. Random gives each instance its share of that amount. --- crates/engine/src/cmd/brushsym/symbols.rs | 6 +++-- crates/engine/src/tests/symbolism_options.rs | 28 ++++++++++++++++++++ docs/mcp.md | 7 ++--- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index ffb7cca8ba..bdce448ebc 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1265,9 +1265,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { continue; } let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + // The style goes on gradually, by the brush's strength there: in + // full at the center at full intensity or pressure. let step = match (tool.as_str(), method) { - ("style", Method::Random) => (share / 2.0) as f32, - ("style", _) => 1.0, + ("style", Method::Random) => (w * share / 2.0) as f32, + ("style", _) => w as f32, _ => (0.15 * w * share) as f32, }; (paint, if alt { cur - step } else { cur + step }) diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 44d1427fb9..bd9d021b31 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -666,3 +666,31 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() { assert!(matches!(&r, Err(EngineError::Other(msg)) if msg == "no symbol set selected"), "{r:?}"); assert!(state(&s) == before); } + +/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen +/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives +/// each instance a share of that amount. +#[test] +fn the_styler_applies_the_style_by_the_brushs_strength() { + let styled = |extra: Value, x: f64| { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + adjust(&mut s, p); + node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity) + }; + let near = |a: f32, b: f32| (a - b).abs() < 1e-6; + assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center"); + assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5)); + assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge"); + assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25)); + assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0)); + assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style"); + let random = styled(json!({"usePressure": true, "points": [[100, 150, 0.25]], "method": "random"}), 100.0); + assert!(random <= 0.25 + 1e-6, "{random}"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 5f9ea72ac0..d15cae6275 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3417,9 +3417,10 @@ already walks Image Trace. Short agent entry points: [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` - `proportional` (true) and `affectsDensity` (false). With `tool: style`, a `style` name the document has no graphic style - for counts as none (the document's first style after the default one). The Symbol Styler sends the style last - clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or + `proportional` (true) and `affectsDensity` (false). With `tool: style`, the style goes on by the brush's strength at + each instance, in full only at the brush's center at intensity 10 or full pressure, and a `style` name the document + has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler sends + the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a non-boolean switch, and a `symbol` or `style` that is neither a name nor null, and sets none of the values. `symbol.spray` takes `attributes` From 6f70483c433101863a68d616dcf58949f42891e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:07:07 -0800 Subject: [PATCH 09/15] Symbolism: the options dialog skips locked or hidden symbol sets With a locked or hidden symbol set selected, a new Symbol Set Density in Symbolism Tools Options asked symbol.setDensity for that set alone. The command refused it ("no symbol set selected"), so OK failed and none of the options were set. The dialog now leaves out sets that cannot be edited: they keep their density, and the options are set. --- .../ui-egui/src/dialogs/symbolism_options.rs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 39c5b6ec9d..388049c29d 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -112,10 +112,16 @@ fn rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); } -/// The selected symbol sets. +/// The selected symbol sets that can be edited (a locked or hidden one keeps its density). fn selected_sets(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set)).map(|id| id.0).collect() + let editable = st.doc.editable(); + st.selection + .objects + .iter() + .filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(**id)) + .map(|id| id.0) + .collect() } /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges), after giving @@ -308,6 +314,27 @@ mod tests { let o = app.session.tool_options_of("symbolSizer"); assert_eq!((o["density"].as_f64(), o["usePressure"].as_bool()), (Some(5.0), Some(false)), "{k}"); } + // A selected set that is locked keeps its density, and OK still sets the options. + let lock = |app: &mut VectorcraftApp, on: bool| { + app.session + .edit("Lock", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(set)).unwrap().locked = on; + Ok(()) + }) + .unwrap(); + }; + lock(&mut app, true); + let steps_locked = undo(&app); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(8)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps_locked)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(8.0)); + lock(&mut app, false); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + let steps = undo(&app); // A higher density packs the set closer, as one undo step. app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); From 7cf2036a17c23ddef36ba5457e0206eb439b3089 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:21:08 -0800 Subject: [PATCH 10/15] Symbolism: the options dialog refuses an unknown tool before any density change OK in Symbolism Tools Options with a tool field that names no symbolism tool gave the selected symbol sets the new density before tool.setOption refused the tool. The dialog now refuses the tool first, and nothing changes. --- .../ui-egui/src/dialogs/symbolism_options.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 388049c29d..b70a250f97 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -137,14 +137,18 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let mut values: Map = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect(); values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); - // A value `tool.setOption` refuses changes no density either. - vectorcraft_tools::symbolism::check_options(&d.str("tool"), &values)?; + // A tool or a value `tool.setOption` refuses changes no density either. + let tool = d.str("tool"); + if !SYMBOLISM.contains(&tool.as_str()) { + return Err(format!("unknown tool `{tool}`")); + } + vectorcraft_tools::symbolism::check_options(&tool, &values)?; let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; } - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + run_and_close(app, "tool.setOption", json!({ "tool": tool, "values": values })) } #[cfg(test)] @@ -304,7 +308,14 @@ mod tests { assert_eq!((width(&app), undo(&app)), (was, steps)); assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0)); // So does a checkbox or a number stored as a value of the wrong kind. - for (k, v) in [("usePressure", json!("invalid")), ("proportional", json!(1)), ("intensity", json!("strong")), ("diameter", json!(true))] { + for (k, v) in [ + ("usePressure", json!("invalid")), + ("proportional", json!(1)), + ("intensity", json!("strong")), + ("diameter", json!(true)), + ("tool", json!("pen")), + ("tool", json!(null)), + ] { app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); let fields = &mut app.ui.dialog.as_mut().unwrap().fields; fields.insert("density".into(), json!(9)); From fecf69fc580d785090c086cda982d021381e8361 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 18:12:55 -0800 Subject: [PATCH 11/15] Symbols: symbol.adjust collects instances in linear time symbol.adjust checked each symbol instance in the selection against every instance it had already collected, so I instances cost about I^2/2 comparisons on every call, and the symbolism tools call it on every drag frame. It now keeps a HashSet of the ids it has pushed. The list is unchanged: the same ids in the same walk order, each kept where it is first reached. A unit test checks the result for nested groups, a group listed twice and members listed before and after their group, and compares it with a copy of the old collector. --- crates/engine/src/cmd/brushsym/symbols.rs | 71 ++++++++++++++++++----- 1 file changed, 57 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 8852cc9bc5..cd0be378f8 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec { v } +/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in +/// turn first reaches them. +fn instances_in<'a>(nodes: impl IntoIterator) -> Vec { + let (mut v, mut seen) = (vec![], std::collections::HashSet::new()); + for n in nodes { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) { + v.push(c.id); + } + }); + } + v +} + /// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`. fn art_symbols(n: &Node, out: &mut Vec) { vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { @@ -1091,20 +1105,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; - let mut v = vec![]; - if st.selection.is_empty() { - v = instances_of(d, None); - } else { - for id in &st.selection.objects { - if let Some(n) = d.node(*id) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) { - v.push(c.id); - } - }); - } - } - } + let mut v = + if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) }; let editable = d.editable(); v.retain(|id| editable(*id)); v @@ -1363,3 +1365,44 @@ fn restack(d: &mut Document, ids: &std::collections::HashSet, back: bool } Ok(moved) } + +#[cfg(test)] +mod tests { + use super::*; + + fn instance(id: u64) -> Arc { + Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY })) + } + + /// The instances come out in the order a search of the list built so far gives: nested + /// groups, a group listed twice, a member listed after its group and one listed before it. + #[test] + fn instances_in_matches_searching_the_list_so_far() { + let groups: Vec = (0..40u64) + .map(|g| { + let base = g * 100; + let mut children: Vec> = (0..40).map(|i| instance(base + i)).collect(); + let inner = (40..50).map(|i| instance(base + i)).collect(); + children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner))); + children.push(Arc::new(Node::group(NodeId(base + 91), vec![]))); + Node::group(NodeId(base + 99), children) + }) + .collect(); + let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect(); + let mut searched = vec![]; + for n in &nodes { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) { + searched.push(c.id); + } + }); + } + let found = instances_in(nodes.iter().copied()); + assert_eq!(found, searched); + assert_eq!(found.len(), 2_000); + assert_eq!(found[0], NodeId(1_245)); + assert!(instances_in([]).is_empty()); + } +} From 97a2b802a424f95f03c385c6f4d37aefc9cfe802 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:02:02 -0800 Subject: [PATCH 12/15] Symbolism: tool.setOption takes every Symbolism option, and OK checks ranges first - The Symbolism tools' check_option accepts usePressure, method, showBrush, the six Sprayer options, proportional and affectsDensity, so tool.setOption and the options dialog's OK save them. - OK runs both of tool.setOption's checks, ranges included, before symbol.setDensity, so a refused diameter leaves the sets' density. - Average skips a stain or style at opacity 0: the Sprayer's mean and the Stainer and Styler take the visible one's paint. - symbol.adjust reads an instance's look only for Average and the Shift recolor, so the Shifter moves an instance whose transform flattens it. - restack collects the parents in a BTreeSet. - The symbol.spray, symbol.setDensity and symbol.adjust texts and docs/mcp.md describe the size base and jitter, the third point value, the starting density, the Random and Alt Styler, and density errors. --- crates/engine/src/cmd/brushsym.rs | 6 +- crates/engine/src/cmd/brushsym/symbolism.rs | 5 +- crates/engine/src/cmd/brushsym/symbols.rs | 45 ++++---- crates/engine/src/tests/symbolism_options.rs | 106 +++++++++++++++++- crates/engine/src/tests/symbolism_shift.rs | 17 ++- crates/tools/src/symbolism.rs | 3 + .../ui-egui/src/dialogs/symbolism_options.rs | 13 ++- docs/mcp.md | 38 ++++--- docs/target-app-parity.md | 2 +- 9 files changed, 188 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 7e904fd26b..3223ca19e9 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -362,7 +362,7 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", + "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. A point's third value, when given, must be a number or null; the Sprayer does not use it. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size times `scale`, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full. Either size, the mean or the symbol's, is a base that each new instance varies from by up to 10% either way. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), @@ -371,7 +371,7 @@ pub fn specs() -> Vec { "Symbol Set Density", [], None, - "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and the sets moved then have density `to`; a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves (a set already at `to`, or sets of one instance). A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", + "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from each set's starting density: the density the set was created at or last given, or `from` only for a set without one (such as one grouped by hand). Each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·start) of its distance from it, where start is that starting density (each factor at least 0.1), as one undo step, and the sets moved then have density `to`; a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves (a set already at `to`, or sets of one instance). A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", has_doc, symbol_set_density ), @@ -380,7 +380,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. No undo step is added when no instance changes (none under the brush, average with each already at the mean, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. No undo step is added when no instance changes (none under the brush, average with each already at the mean, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index 0be2ee37f8..0e311d12f8 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -204,7 +204,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option) -> Option< cos += l.angle.cos(); opacity += l.opacity; middle += l.center.to_vec2(); - if let Some((p, o)) = &l.fill { + // A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken. + if let Some((p, o)) = &l.fill + && *o > 0.0 + { amount += o; let far = l.center.distance(at); if paint.is_none_or(|(_, nearest)| far < nearest) { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 534dbb0f84..d3d4a9b227 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,5 +1,5 @@ use super::dynamic::{fit_overrides, type_id, type_param}; -use super::symbolism::{Grid, Mean, Method, look, mean, method_param, record_set_density, spacing, spray_modes, wrap_angle}; +use super::symbolism::{Grid, Look, Mean, Method, look, mean, method_param, record_set_density, spacing, spray_modes, wrap_angle}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, @@ -1205,18 +1205,21 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { if w <= 0.0 { continue; } - let Some(cur) = d.node(*id).and_then(|n| look(d, n)) else { continue }; + // Average and the Shift forms of the Stainer and the Styler read the instance's look, + // and Average has no mean of instances without one. The other changes need only its + // center, so an instance without a size (one whose transform flattens it) still moves. + let Some(cur) = look_if(d, *id, method == Method::Average || recolor.is_some()) else { continue }; // Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount // of its stain or style, and its paint moves toward the color or the style. An // instance without one is left as it is. if let Some((to, step)) = &recolor { - if recolor_keeping_amount(d, *id, cur.fill, to, step * w) { + if recolor_keeping_amount(d, *id, cur.and_then(|l| l.fill), to, step * w) { touched.insert(*id); } continue; } // Average leaves an instance that already has the mean as it is. - let at_mean = target.as_ref().is_some_and(|t| match tool.as_str() { + let at_mean = target.as_ref().zip(cur.as_ref()).is_some_and(|(t, cur)| match tool.as_str() { "scrunch" => { let out = (c - t.middle).hypot(); out <= 1e-9 || (t.reach - out).abs() < 1e-9 @@ -1250,8 +1253,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { n.transform(Affine::translate(v), false); } "size" => { - let k = match &target { - Some(t) => (t.scale / cur.scale).powf(w.min(1.0)), + let k = match target.as_ref().zip(cur.as_ref()) { + Some((t, cur)) => (t.scale / cur.scale).powf(w.min(1.0)), None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }), }; // Without Proportional Resizing a drag resizes along its own direction: a @@ -1273,8 +1276,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } } "spin" => { - let a = match (&target, method) { - (Some(t), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), + let a = match (target.as_ref().zip(cur.as_ref()), method) { + (Some((t, cur)), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), // A turn either way, whichever way the drag runs. (None, Method::Random) => 0.1 * w * (share - 1.0), // Turn towards the drag direction; a click spins a little. @@ -1285,10 +1288,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - let (paint, o) = match &target { - // Toward the mean amount, keeping the stain or style the instance has. - Some(t) => { - let (own, cur) = cur.fill.map_or((None, 0.0), |(p, o)| (Some(p), o)); + let (paint, o) = match target.as_ref().zip(cur) { + // Toward the mean amount, keeping the stain or style the instance has + // (one at no opacity is none). + Some((t, cur)) => { + let (own, cur) = cur.fill.filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o)); (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) } None => { @@ -1332,6 +1336,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": count })) } +/// The [`Look`] of instance `id` for the symbolism tools, or None to leave the instance as it is: +/// one without a look (no size) is left only when `needed`. +fn look_if(d: &Document, id: NodeId, needed: bool) -> Option> { + match d.node(id).and_then(|n| look(d, n)) { + None if needed => None, + cur => Some(cur), + } +} + /// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount) /// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's /// other appearance items stay as they are. A paint with no form between it and `to` (a solid @@ -1360,13 +1373,7 @@ fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64 /// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how /// many moved. fn restack(d: &mut Document, ids: &std::collections::HashSet, back: bool) -> Result { - let mut parents: Vec> = vec![]; - for id in ids { - let par = d.parent_of(*id); - if !parents.contains(&par) { - parents.push(par); - } - } + let parents: std::collections::BTreeSet> = ids.iter().map(|id| d.parent_of(*id)).collect(); let mut moved = 0; for par in parents { let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index bd9d021b31..bc5eb86588 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -271,6 +271,7 @@ fn tool_set_option_refuses_bad_symbolism_options() { ("usePressure", json!("yes"), "`usePressure` must be true or false"), ("diameter", json!("big"), "`diameter` must be a number"), ("style", json!(3), "`style` must be a name or null"), + ("diameter", json!(1), "tool `symbolSizer`: `diameter` must be a number from 2 to 2000"), ] { let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}})); assert_eq!(r, Err(want.to_string()), "{key}"); @@ -278,6 +279,16 @@ fn tool_set_option_refuses_bad_symbolism_options() { } let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap(); assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined"))); + // Every option the options dialog sends is taken, together. + let all = json!({ + "diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false, + "sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined", + "sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true, + }); + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap(); + for (key, v) in all.as_object().unwrap() { + assert_eq!(&r[key], v, "{key}"); + } } /// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is @@ -691,6 +702,97 @@ fn the_styler_applies_the_style_by_the_brushs_strength() { assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25)); assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0)); assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style"); - let random = styled(json!({"usePressure": true, "points": [[100, 150, 0.25]], "method": "random"}), 100.0); - assert!(random <= 0.25 + 1e-6, "{random}"); + // Random: instances the same distance from the point take different amounts, each from none to + // the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge). + let mut s = session(); + let ring: Vec = (0..6) + .map(|i| { + let a = f64::from(i) * std::f64::consts::TAU / 6.0; + dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin()) + }) + .collect(); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"})); + let amounts: Vec = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect(); + assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}"); + assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}"); + assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}"); +} + +/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one +/// at no opacity is passed over and counts as no stain in the mean amount. +#[test] +fn average_spray_passes_over_a_stain_at_no_opacity() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 2); + s.edit("Stains", |d, _| { + for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] { + let n = d.node_mut(id).unwrap(); + n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))); + let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color)); + f.opacity = amount; + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap(); + let new: Vec = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect(); + assert_eq!(new.len(), 1); + let f = node(&s, new[0]).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity); +} + +/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves +/// any other, and counts it. +#[test] +fn the_shifter_moves_an_instance_without_a_size() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + s.edit("Flatten", |d, _| { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]); + } + Ok(()) + }) + .unwrap(); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 1); + assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a)); + // Average has no mean of such instances to move toward: it leaves them as they are. + let (before, x) = (state(&s), center(&s, a).x); + let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes +/// the stain the mean picks, not its hidden paint. +#[test] +fn average_stain_replaces_a_stain_at_no_opacity() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0)); + s.edit("Stains", |d, _| { + for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] { + let n = d.node_mut(id).unwrap(); + let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color)); + f.opacity = amount; + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + } + Ok(()) + }) + .unwrap(); + adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10})); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + assert!(f.opacity > 0.0, "{}", f.opacity); } diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs index c1c8bdcae0..ca08dc2069 100644 --- a/crates/engine/src/tests/symbolism_shift.rs +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -228,9 +228,11 @@ fn shift_changes_a_paint_that_has_no_form_in_between() { } /// A style name the document has no style for (the Styler's style from another document, or one -/// since renamed or deleted) moves the fill toward the same style as no name. +/// since renamed or deleted) moves the fill toward the document's first style after the default +/// one, as no name does, and the stain's amount stays. #[test] fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() { + use vectorcraft_color::{Color, Paint}; let styled = |style: Option<&str>| { let mut s = session(); let a = dot(&mut s, 100.0, 150.0); @@ -241,10 +243,19 @@ fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() { if let Some(n) = style { p["style"] = json!(n); } + let stained = node(&s, a).appearance.fill().map(|f| f.opacity); adjust(&mut s, p); - fill(&s, a).unwrap() + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(Some(f.opacity), stained, "the amount stays"); + let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint(); + (f.paint, first) }; - assert_eq!(styled(Some("No Such Style")), styled(None)); + let (missing, first) = styled(Some("No Such Style")); + let (none, _) = styled(None); + assert_eq!(missing, none); + // The paint is the first style's, not the active fill color. + assert_eq!(none, first); + assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0))); } /// A `shift` that is not true, false or null is refused and changes nothing. diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 5bee8a7afb..4b4aeb5865 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -385,6 +385,9 @@ impl Tool for SymbolismTool { "diameter" => c::number(key, v, 2.0, 2000.0), "intensity" | "density" => c::number(key, v, 1.0, 10.0), "symbol" | "style" => c::string_or_null(key, v), + "usePressure" | "showBrush" | "proportional" | "affectsDensity" => c::boolean(key, v), + "method" => c::one_of(key, v, &METHODS), + _ if SPRAY_ATTRIBUTES.iter().any(|(k, _)| *k == key) => c::one_of(key, v, &SPRAY_MODES), _ => Err(c::unknown(key)), } } diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index fcbefba113..6028d3d8c3 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -124,8 +124,8 @@ fn selected_sets(app: &VectorcraftApp) -> Vec { .collect() } -/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges), after giving -/// a new Symbol Set Density to the selected symbol sets. +/// OK: set the brush the Symbolism tools share, after giving a new Symbol Set Density to the +/// selected symbol sets. A value outside its range is refused and changes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { // Each value goes to the check as it is stored, so one of the wrong kind is refused rather than // read as 0 or false. A number stored as text is read as the field reads it, and other text is @@ -137,12 +137,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let mut values: Map = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect(); values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); - // A tool or a value `tool.setOption` refuses changes no density either. + // A tool or a value `tool.setOption` refuses changes no density either: the values go through + // both of its checks, the kinds and then each option's range, before the density changes. let tool = d.str("tool"); if !SYMBOLISM.contains(&tool.as_str()) { return Err(format!("unknown tool `{tool}`")); } vectorcraft_tools::symbolism::check_options(&tool, &values)?; + vectorcraft_tools::option_check::check_values(&vectorcraft_tools::symbolism::SymbolismTool::new(&tool), &values)?; let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { @@ -307,8 +309,11 @@ mod tests { assert!(super::super::confirm(&mut app).is_err()); assert_eq!((width(&app), undo(&app)), (was, steps)); assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0)); - // So does a checkbox or a number stored as a value of the wrong kind. + // So does a checkbox or a number stored as a value of the wrong kind, or a number outside its + // range. for (k, v) in [ + ("diameter", json!(1)), + ("intensity", json!(11)), ("usePressure", json!("invalid")), ("proportional", json!(1)), ("intensity", json!("strong")), diff --git a/docs/mcp.md b/docs/mcp.md index bc054dddf5..58f5bc04e3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3783,38 +3783,48 @@ already walks Image Trace. Short agent entry points: `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` `proportional` (true) and `affectsDensity` (false). With `tool: style`, the style goes on by the brush's strength at - each instance, in full only at the brush's center at intensity 10 or full pressure, and a `style` name the document + each instance: one sample applies it in full only at the brush's center at intensity 10 or full pressure, and the + samples of a stroke add up (two samples at the center at intensity 5 apply it in full). With `alt`, `userDefined` + and `random` remove all of an instance's appearance items under the brush at once, whatever the brush's strength. + A `style` name the document has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler sends the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a - non-boolean switch, and a `symbol` or `style` that is neither a name nor null, and sets none of the values. + `diameter` outside 2..2000 or an `intensity` or `density` outside 1..10, a non-boolean switch, and a `symbol` or + `style` that is neither a name nor null, and sets none of the values. The options dialog's OK checks the same way + before it changes any symbol set's density. `symbol.spray` takes `attributes` `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and `style` for the User Defined stain and style. `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol sets a new Symbol Set Density. VectorCraft's own rules: - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice - it (the Spinner: a turn either way), the same each time the stroke is applied. + it (the Spinner: a turn either way; the Styler without `shift`: from none to the `userDefined` amount), the same + each time the stroke is applied. - `average` moves each instance's value toward the mean of the instances within the brush at that point: the Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when no instance changes. - - With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the - height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows + - With `proportional` false a drag resizes along its own direction: the width by the drag's horizontal share and + the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike), and + one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. - A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the - stroke point: their spacing, size, rotation and opacity, and the stain or style of the nearest one that has one, - at the mean amount. With no instance there it has the symbol's size, no rotation, full opacity and no stain or - style. `attributes` left out means `average` for all six. + stroke point: their spacing, size, rotation and opacity, and the stain or style of the nearest one that has one + with an amount above 0, at the mean amount. With no instance there it has the symbol's size times `scale`, no + rotation, full opacity and no stain or style. The size, the mean or the symbol's, is a base: each new instance + varies from it by up to 10% either way. `attributes` left out means `average` for all six. A point's third value, + when given, must be a number or null; the Sprayer does not use it. - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to - (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and - adds none when no instance moves. `from` is the density each set was created at or last given (a set - duplicated has its source's, and a pasted set the one its source had at Copy), and the - `from` passed applies only to a set without one (a group named "Symbol Set" by hand); the sets moved then have + (1.15 − 0.1·`to`) / (1.15 − 0.1·start) of its distance from it (each factor at least 0.1), as one undo step, and + adds none when no instance moves. start is the density each set was created at or last given (a set + duplicated has its source's, and a pasted set the one its source had at Copy); the + `from` passed is the start only for a set without one (a group named "Symbol Set" by hand). The sets moved then have density `to`. A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the instances moved. - - A `method`, an attribute or a density outside these values, a pressure that isn't a number, or no symbol set - among the objects of `symbol.setDensity`, is an error and changes nothing. + - A `method` or an attribute outside these values, a `from` or `to` of `symbol.setDensity` that is not a number + from 1 to 10, a pressure that isn't a number, or no symbol set among the objects of `symbol.setDensity`, is an + error and changes nothing. `symbol.spray` takes a `density` number outside 1..10 as the nearer end. - The symbolism tools with Shift held ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)) send `shift: true` with `symbol.adjust`: a Shift-click with the Symbol Shifter brings the instances under the brush diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e3032af474..06199e1d00 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1176,7 +1176,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. + - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off; with them, two strokes change from before: a Sprayer stroke over instances of the selected set gives its new instances their mean values, and the Symbol Styler applies the style by the brush's strength, so a click at the brush's center at the default intensity 5 applies it at half opacity instead of in full, and a stroke's samples add up; the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; a stain or style with no form between it and the new paint (a solid color and a pattern) takes the new paint at once; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`. - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). From 83a1fbbcd896fa93bb5eafbe763ca1e50d305f8c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:28:52 -0800 Subject: [PATCH 13/15] Symbolism: the Sprayer's User Defined Style applies the style picked in Graphic Styles A click in the Graphic Styles panel set the style only for the Symbol Styler, so the Sprayer with Style: User Defined sent no style and sprayed the document's first style after the default one. The two tools now share the style option. --- crates/tools/src/settings.rs | 5 +++-- crates/ui-egui/src/panels/graphic_styles.rs | 8 ++++++-- docs/mcp.md | 4 ++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 635ec8e4a0..51c408261e 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -44,8 +44,9 @@ const ROWS: &[Row] = &[ "affectsDensity", ], ), - // The graphic style the Symbol Styler applies, set from the Graphic Styles panel. - (&["symbolStyler"], None, &["style"]), + // The graphic style the Symbol Styler and the Symbol Sprayer's User Defined Style apply, set + // from the Graphic Styles panel. + (&["symbolSprayer", "symbolStyler"], Some("symbolismStyle"), &["style"]), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index b03e2e0662..7c69333bc6 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,7 +3,8 @@ //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from //! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one. The -//! style last clicked into the selection is the one the Symbol Styler applies. Double-click opens +//! style last clicked into the selection is the one the Symbol Styler and the Symbol Sprayer's User +//! Defined Style apply. Double-click opens //! Graphic Style Options. Dragging a style moves it in the list (dropped on //! another style with Alt held, replaces that style with its look), applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a @@ -553,7 +554,8 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { Some(Click::Pick(name, m)) => { let order: Vec<&str> = s.d.graphic_styles.iter().map(|g| g.name.as_str()).collect(); let sel = super::swatches::click_selection(ui, "gs-anchor", selected(ui.ctx(), s.d), &order, &name, m); - // The style clicked into the selection is the one the Symbol Styler applies. + // The style clicked into the selection is the one the Symbol Styler and the Symbol + // Sprayer's User Defined Style apply (the two share it). if sel.contains(&name) { app.run("tool.setOption", json!({"tool": "symbolStyler", "values": {"style": name}})).ok(); } @@ -1709,6 +1711,8 @@ mod tests { assert_eq!(styler(&app).as_ref(), Some(&n[3])); assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone(), n[2].clone()]); assert_eq!(styler(&app).as_ref(), Some(&n[2])); + // The Symbol Sprayer's User Defined Style applies the same style. + assert_eq!(app.session.tool_options_of("symbolSprayer")["style"].as_str(), Some(n[2].as_str())); // Shift-click extends from the style Cmd/Ctrl-clicked last. click(&mut app, 0, egui::Modifiers::NONE); click(&mut app, 2, egui::Modifiers::COMMAND); diff --git a/docs/mcp.md b/docs/mcp.md index 58f5bc04e3..c839b6aa37 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3787,8 +3787,8 @@ already walks Image Trace. Short agent entry points: samples of a stroke add up (two samples at the center at intensity 5 apply it in full). With `alt`, `userDefined` and `random` remove all of an instance's appearance items under the brush at once, whatever the brush's strength. A `style` name the document - has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler sends - the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or + has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler and the + Symbol Sprayer (its User Defined Style) send the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a `diameter` outside 2..2000 or an `intensity` or `density` outside 1..10, a non-boolean switch, and a `symbol` or `style` that is neither a name nor null, and sets none of the values. The options dialog's OK checks the same way From ba919a0ea0fb3a33ac4da296ea762660e2ae59aa Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 23:03:34 +0700 Subject: [PATCH 14/15] Symbols: the step from the previous point reads it with get, so the adjust closure stays under the complexity limit --- crates/engine/src/cmd/brushsym/symbols.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 01b7ac9fab..e9ddf851be 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1210,7 +1210,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let mut touched = std::collections::BTreeSet::new(); let mut sides = Sides::new(); for (j, (q, pressure)) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev); // Use Pressure Pen: the pen's pressure at the point is the intensity there. let strength = if use_pressure { *pressure } else { intensity }; // Average: the mean of the instances under the brush, as they are at this point. From 850338909e934f2e8cbb067dab8927be82bfd76d Mon Sep 17 00:00:00 2001 From: bflatastic Date: Thu, 19 Nov 2026 23:04:07 +0700 Subject: [PATCH 15/15] Symbols: a recolored instance is noted without a nested if --- crates/engine/src/cmd/brushsym/symbols.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index e9ddf851be..14e52ffe4f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1236,9 +1236,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { // instance without one, or without a size, is left as it is. if let Some((to, step)) = &recolor { let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill); - if recolor_keeping_amount(d, *id, fill, to, step * w) { - touched.insert(*id); - } + touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id)); continue; } // Average needs the instance's own values, so it leaves an instance without a size