From cb1796185e1c3af13ffa02bacb85bddb4711165c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:31:39 -0800 Subject: [PATCH 01/11] Symbols: Symbolism Tools Options gain Method, pen pressure and the Sprayer and Sizer options The Symbolism Tools Options dialog adds Use Pressure Pen, Method (User Defined, Average, 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 Tool row switches which tool's options show. symbol.adjust takes method, usePressure with [x, y, pressure] points, proportional and affectsDensity; symbol.spray takes attributes. The new symbol.setDensity gives the selected symbol sets a new Symbol Set Density, from the density each set was created at or last given, as one undo step. A symbolism stroke that changes no instance adds no undo step. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/brushsym.rs | 18 +- crates/engine/src/cmd/brushsym/symbolism.rs | 369 ++++++++++++ crates/engine/src/cmd/brushsym/symbols.rs | 240 ++++++-- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/symbolism_options.rs | 559 ++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/settings.rs | 22 +- crates/tools/src/symbolism.rs | 238 +++++++- .../ui-egui/src/dialogs/symbolism_options.rs | 209 ++++++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 45 +- docs/target-app-parity.md | 1 + 14 files changed, 1637 insertions(+), 74 deletions(-) create mode 100644 crates/engine/src/cmd/brushsym/symbolism.rs create mode 100644 crates/engine/src/tests/symbolism_options.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 19695fd4ff..a56bcdbff8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -892,6 +892,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// Whether an object is a symbol set (the Symbolism Tools Options' Symbol Set Density applies to +/// the selected ones). +pub use brushsym::is_symbol_set; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 1046cada1c..3a31281f30 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,8 +27,12 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// Whether an object is a symbol set. +pub use symbols::is_symbol_set; + mod brushes; mod dynamic; +mod symbolism; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -38,6 +42,7 @@ use brushes::{ }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; +use symbolism::symbol_set_density; use symbols::selected_instances; pub(crate) use symbols::{ expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, @@ -345,16 +350,25 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances)} spray instances into a symbol set → {id, count}", + "{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", has_doc, symbol_spray ), + cmd!( + "symbol.setDensity", + "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}", + has_doc, + symbol_set_density + ), cmd!( "symbol.adjust", "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{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", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs new file mode 100644 index 0000000000..f5df078745 --- /dev/null +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -0,0 +1,369 @@ +//! What the symbolism commands share: the Method and the Symbol Sprayer options of the Symbolism +//! Tools Options, what an instance shows of the values the tools change ([`Look`]), the mean of +//! those values under the brush ([`mean`]), and `symbol.setDensity`. + +use std::collections::HashMap; + +use super::symbols::{instance_center, is_symbol_set}; +use super::{Affine, Document, EngineError, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids}; + +/// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Method { + /// Gradually, in relation to the position of the pointer. + UserDefined, + /// Toward the mean of the instances under the brush. + Average, + /// By an amount that differs from instance to instance. + Random, +} + +/// The `method` of `symbol.adjust` (User Defined when left out or null). +pub(super) fn method_param(p: &Value, cmd: &str) -> Result { + match p.get("method") { + None | Some(Value::Null) => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "userDefined" => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "average" => Ok(Method::Average), + Some(Value::String(s)) if s == "random" => Ok(Method::Random), + Some(v) => Err(bad(cmd, format!("`method` must be userDefined, average or random, not {v}"))), + } +} + +/// The Symbol Sprayer options: whether each value of a new instance is the average of the +/// instances under the brush (true) or the User Defined value (false). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct SprayModes { + pub scrunch: bool, + pub size: bool, + pub spin: bool, + pub screen: bool, + pub stain: bool, + pub style: bool, +} + +impl SprayModes { + /// Whether any value is an average. + pub fn any_average(self) -> bool { + self.scrunch || self.size || self.spin || self.screen || self.stain || self.style + } +} + +/// The `attributes` of `symbol.spray`: `{scrunch?, size?, spin?, screen?, stain?, style?}`, each +/// `average` (also when left out or null) or `userDefined`. Another key or value is an error. +pub(super) fn spray_modes(p: &Value, cmd: &str) -> Result { + let mut m = SprayModes { scrunch: true, size: true, spin: true, screen: true, stain: true, style: true }; + let map = match p.get("attributes") { + None | Some(Value::Null) => return Ok(m), + Some(Value::Object(map)) => map, + Some(v) => return Err(bad(cmd, format!("`attributes` must be an object, not {v}"))), + }; + for (key, v) in map { + let slot = match key.as_str() { + "scrunch" => &mut m.scrunch, + "size" => &mut m.size, + "spin" => &mut m.spin, + "screen" => &mut m.screen, + "stain" => &mut m.stain, + "style" => &mut m.style, + _ => return Err(bad(cmd, format!("unknown attribute `{key}`"))), + }; + *slot = match v { + Value::Null => true, + Value::String(s) if s == "average" => true, + Value::String(s) if s == "userDefined" => false, + v => return Err(bad(cmd, format!("attribute `{key}` must be average or userDefined, not {v}"))), + }; + } + Ok(m) +} + +/// How far apart the Symbol Sprayer keeps instances at Symbol Set Density `density` (1..10), as a +/// share of the symbol's size: a denser set is packed closer. +pub(super) fn spacing(density: f64) -> f64 { + (1.15 - density * 0.1).max(0.1) +} + +/// 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"; + +/// 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 { + d.unknown.get(SET_DENSITY_KEY)?.get(set.0.to_string())?.as_f64().filter(|v| (1.0..=10.0).contains(v)) +} + +/// Record `density` as the Symbol Set Density of `sets`, and drop the records of ids that are no +/// longer symbol sets. +pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64) { + let mut map = match d.unknown.get(SET_DENSITY_KEY) { + Some(Value::Object(m)) => m.clone(), + _ => serde_json::Map::new(), + }; + for set in sets { + map.insert(set.0.to_string(), json!(density)); + } + map.retain(|k, _| k.parse::().ok().and_then(|id| d.node(NodeId(id))).is_some_and(is_symbol_set)); + if map.is_empty() { + d.unknown.remove(SET_DENSITY_KEY); + } else { + d.unknown.insert(SET_DENSITY_KEY.into(), Value::Object(map)); + } +} + +/// What a symbol instance shows of the values the symbolism tools change. +#[derive(Clone, Debug)] +pub(super) struct Look { + pub center: Point, + /// Its size as a share of its symbol's own size (1: the symbol's size). + pub scale: f64, + /// Its rotation in radians. + pub angle: f64, + pub opacity: f64, + /// The fill the Symbol Stainer or the Symbol Styler gave it, with its amount (0..1). + pub fill: Option<(Paint, f64)>, +} + +/// The [`Look`] of instance `n` (None for another object, or an instance without a size). +pub(super) fn look(d: &Document, n: &Node) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let [a, b, c, e, ..] = xf.as_coeffs(); + let natural = d.symbol_natural_xf(symbol).as_coeffs(); + let (sx, sy) = (natural[0].abs().max(1e-9), natural[3].abs().max(1e-9)); + let scale = ((a * e - b * c) / (sx * sy)).abs().sqrt(); + if !(scale.is_finite() && scale > 0.0) { + return None; + } + Some(Look { + center: instance_center(n)?, + scale, + angle: b.atan2(a), + opacity: f64::from(n.opacity), + fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))), + }) +} + +/// The mean of the [`Look`]s of the instances under the brush. +#[derive(Clone, Debug)] +pub(super) struct Mean { + /// The geometric mean of the sizes. + pub scale: f64, + /// The mean direction of the rotations. + pub angle: f64, + pub opacity: f64, + /// The mean stain or style amount; an instance without one counts as 0. + pub amount: f64, + /// The stain or style of the instance nearest the brush's center that has one. + pub paint: Option, + /// The middle of the instances. + pub middle: Point, + /// Their mean distance from [`Mean::middle`]. + pub reach: f64, + /// The mean distance from each of them to the nearest of the others (None for one instance, or + /// when not asked for). + pub gap: Option, +} + +/// For each of `looks`, the distance to the nearest of the others (infinite for one alone). Each +/// is first looked for in the cells around it of a grid `cell` points wide: one found within `cell` +/// is the nearest, since every one that near is in those cells. Otherwise all are measured. +fn nearest_gaps(looks: &[&Look], cell: f64) -> Vec { + let cell = cell.max(1e-6); + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, l) in looks.iter().enumerate() { + cells.entry(key(l.center, cell)).or_default().push(i); + } + let distance = |i: usize, j: usize| if i == j { None } else { Some(looks.get(j)?.center.distance(looks.get(i)?.center)) }; + (0..looks.len()) + .map(|i| { + let mut best = f64::INFINITY; + for j in around(&cells, looks.get(i).map_or(Point::ZERO, |l| l.center), cell) { + best = distance(i, j).map_or(best, |d| best.min(d)); + // Instances on top of each other: none can be nearer. + if best == 0.0 { + break; + } + } + if best <= cell { best } else { (0..looks.len()).filter_map(|j| distance(i, j)).fold(f64::INFINITY, f64::min) } + }) + .collect() +} + +/// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with +/// [`Mean::gap`] when `gap_cell` gives the grid width [`nearest_gaps`] uses. +pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option) -> Option { + if looks.is_empty() { + return None; + } + let n = looks.len() as f64; + let (mut log_scale, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO); + let mut paint: Option<(&Paint, f64)> = None; + for l in looks { + log_scale += l.scale.ln(); + sin += l.angle.sin(); + cos += l.angle.cos(); + opacity += l.opacity; + middle += l.center.to_vec2(); + if let Some((p, o)) = &l.fill { + amount += o; + let far = l.center.distance(at); + if paint.is_none_or(|(_, nearest)| far < nearest) { + paint = Some((p, far)); + } + } + } + let middle = (middle / n).to_point(); + // Rotations that cancel out have no mean direction: the first instance's stands for it. + let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle }; + // One instance under the brush has no spacing there. + let gap = gap_cell.filter(|_| looks.len() > 1).map(|cell| nearest_gaps(looks, cell).iter().sum::() / n); + Some(Mean { + scale: (log_scale / n).exp(), + angle, + opacity: opacity / n, + amount: amount / n, + paint: paint.map(|(p, _)| p.clone()), + middle, + reach: looks.iter().map(|l| l.center.distance(middle)).sum::() / n, + gap, + }) +} + +/// `angle` (radians) brought into −π..π. +pub(super) fn wrap_angle(angle: f64) -> f64 { + let turn = std::f64::consts::TAU; + let a = angle.rem_euclid(turn); + if a > std::f64::consts::PI { a - turn } else { a } +} + +/// The instances of a symbol set by where they are, to find those under a brush without looking at +/// every one for every point of a stroke. +pub(super) struct Grid { + cell: f64, + looks: Vec, + cells: HashMap<(i64, i64), Vec>, +} + +fn key(p: Point, cell: f64) -> (i64, i64) { + ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64) +} + +/// The indices in the cell of `at`, then in the eight around it. Saturating: a point far out on the +/// canvas has a key at the end of the range. +fn around(cells: &HashMap<(i64, i64), Vec>, at: Point, cell: f64) -> impl Iterator + '_ { + let (cx, cy) = key(at, cell); + let ring = (cx.saturating_sub(1)..=cx.saturating_add(1)) + .flat_map(move |x| (cy.saturating_sub(1)..=cy.saturating_add(1)).map(move |y| (x, y))) + .filter(move |c| *c != (cx, cy)); + std::iter::once((cx, cy)).chain(ring).flat_map(move |c| cells.get(&c).into_iter().flatten().copied()) +} + +impl Grid { + /// `looks` in cells `cell` points wide (the brush's radius). + pub fn new(looks: Vec, cell: f64) -> Self { + let cell = cell.max(1.0); + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, l) in looks.iter().enumerate() { + cells.entry(key(l.center, cell)).or_default().push(i); + } + Self { cell, looks, cells } + } + + /// The mean of the instances within `radius` (at most the cell width) of `at`, with + /// [`Mean::gap`] when `with_gap` is set. + pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option { + let near: Vec<&Look> = + around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect(); + mean(&near, at, with_gap.then_some(radius / 4.0)) + } +} + +/// `symbol.setDensity {from, to, ids?|id?}`: space the instances of the selected symbol sets as +/// Symbol Set Density `to` packs them, from the density each set was created at or last given +/// (`from` for a set without one): each instance moves along the line from the middle of its set's +/// instances, to [`spacing`]`(to) / `[`spacing`]` of the set's density` of its distance from it. +/// The sets moved then have density `to`. One undo step, and none when no instance moves. +pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.setDensity"; + let density = |key: &str| match p.get(key) { + Some(v) => v.as_f64().filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| bad(C, format!("`{key}` must be a number from 1 to 10, not {v}"))), + None => Err(bad(C, format!("missing `{key}`"))), + }; + let (from, to) = (density("from")?, density("to")?); + crate::cmd::edit::refuse_symbol_part(s)?; + let st = s.doc()?; + let d = &st.doc; + let named = named_ids(p)?; + let ids: Vec = named.clone().unwrap_or_else(|| st.selection.objects.clone()); + if let Some(missing) = named.iter().flatten().find(|id| d.node(**id).is_none()) { + return Err(EngineError::Other(format!("no object {}", missing.0))); + } + let editable = d.editable(); + let mut sets: Vec = vec![]; + for id in ids { + if d.node(id).is_some_and(is_symbol_set) && editable(id) && !sets.contains(&id) { + sets.push(id); + } + } + if sets.is_empty() { + return Err(EngineError::Other("no symbol set selected".into())); + } + let mut moves: Vec<(NodeId, Vec2)> = vec![]; + let mut changed: Vec = vec![]; + for set in &sets { + // A set packs from the density it was created at or last given, else from `from`. + let ratio = spacing(to) / spacing(set_density_of(d, *set).unwrap_or(from)); + let centers: Vec<(NodeId, Point)> = + d.node(*set).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| Some((c.id, instance_center(c)?))).collect(); + if centers.len() < 2 { + continue; + } + let middle = (centers.iter().fold(Vec2::ZERO, |sum, (_, c)| sum + c.to_vec2()) / centers.len() as f64).to_point(); + let before = moves.len(); + // A locked or hidden instance stays where it is. + moves.extend( + centers.iter().filter(|(id, _)| editable(*id)).map(|(id, c)| (*id, (*c - middle) * (ratio - 1.0))).filter(|(_, v)| v.hypot() > 1e-9), + ); + if moves.len() > before { + changed.push(*set); + } + } + drop(editable); + if !moves.is_empty() { + s.edit("Symbol Set Density", |d, _| { + for (id, v) in &moves { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*v), false); + } + } + record_set_density(d, &changed, to); + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed), "count": moves.len() })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(x: f64, y: f64) -> Look { + Look { center: Point::new(x, y), scale: 1.0, angle: 0.0, opacity: 1.0, fill: None } + } + + /// The gaps are each instance's distance to its nearest neighbor, measured against every other + /// instance: close pairs whose members are far apart in the order, instances on top of each + /// other, and instances farther apart than the grid's cells. + #[test] + fn nearest_gaps_match_measuring_every_pair() { + let mut looks: Vec = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect(); + // The second member of each pair comes 300 places later. + looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0))); + looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]); + let refs: Vec<&Look> = looks.iter().collect(); + let brute: Vec = (0..refs.len()) + .map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)) + .collect(); + assert_eq!(nearest_gaps(&refs, 10.0), brute); + assert_eq!(nearest_gaps(&refs[..1], 10.0), [f64::INFINITY]); + } +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 1bfb8edea7..4ba3b22b62 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,4 +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::{ 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, @@ -843,16 +844,40 @@ pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result Result> { + Ok(samples(p, cmd)?.into_iter().map(|(q, _)| q).collect()) +} + +/// The stroke's points, each with its pen pressure: the third number of `[x, y, pressure]`, kept +/// within 0..1, and 1 for a point that gives none (or null). A pressure that isn't a number is an +/// error. +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 v: Vec = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(); - if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) { + 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 }; + 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}")))?, + }; + 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()) { return Err(bad(cmd, "points must be finite [x,y] pairs")); } Ok(v) } +/// The fill of the graphic style `p` names with `style`, else 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()), + } +} + /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). -fn jitter(i: usize, q: Point) -> (f64, f64, f64) { +pub(super) fn jitter(i: usize, q: Point) -> (f64, f64, f64) { let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64; for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] { h ^= v; @@ -863,7 +888,8 @@ fn jitter(i: usize, q: Point) -> (f64, f64, f64) { (f(0), f(1), f(2)) } -fn is_symbol_set(n: &Node) -> bool { +/// Whether `n` is a symbol set: the group the Symbol Sprayer sprays instances into. +pub fn is_symbol_set(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set") } @@ -876,6 +902,13 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0); let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0); let alt = switch_or(p, "alt", false, C)?; + let modes = spray_modes(p, C)?; + crate::cmd::paint::check_keep_model(p, C)?; + let stain = match color_param(p, "color", C)? { + Some(c) => crate::cmd::paint::new_color(s, p, c), + None => s.paint.fill.color().unwrap_or(Color::BLACK), + }; + let style = style_paint(&st.doc, p); let size = natural_size(&st.doc, &name); let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); // Only a new Symbol Set needs a layer that takes new art. @@ -903,25 +936,63 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "count": n })); } // Keep instances at least this far apart along the stroke (denser = closer). - let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1); - let mut placed: Vec = vec![]; + let min_gap = size.0.max(size.1) * scale * spacing(density); + // The instances the selected set has, for the values a new one takes as their average. + let existing = set.filter(|_| modes.any_average()).map(|g| { + let d = &st.doc; + let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c)).collect(); + Grid::new(looks, radius) + }); + // Each instance to add: where, the mean of the set's instances under the brush there, and the + // direction of the stroke there (None while the pointer has not moved). + let mut placed: Vec<(Point, Option, Option)> = vec![]; for (i, q) in pts.iter().enumerate() { let (jx, jy, _) = jitter(i, *q); let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); - if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 { + let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch)); + // Scrunch: Average spaces new instances as the ones under the brush are spaced. + let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap); + if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 { continue; } - placed.push(c); + let along = pts.get(i + 1).unwrap_or(q).to_vec2() - pts.get(i.saturating_sub(1)).unwrap_or(q).to_vec2(); + placed.push((c, near, (along.hypot() > 1e-9).then_some(along))); } let count = placed.len(); let reg = s.doc()?.doc.symbol_registration(&name); let id = s.edit("Symbol Sprayer", |d, sel| { let mut nodes = vec![]; - for (i, c) in placed.iter().enumerate() { + for (i, (c, near, along)) in placed.iter().enumerate() { let (_, _, js) = jitter(i + 7, *c); - let k = scale * (1.0 + js * 0.1); + let near = near.as_ref(); + // User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained + // with the fill color and given the style, each in full. + let k = near.filter(|_| modes.size).map_or(scale, |m| m.scale) * (1.0 + js * 0.1); + let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) }; + let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2()); let id = d.alloc_id(); - nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) })); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: turn * place_xf(*c, size, reg) * Affine::scale(k) }); + if modes.screen + && let Some(m) = near + { + n.opacity = (m.opacity as f32).clamp(0.05, 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. + let averaged = near.filter(|m| m.amount > 0.0).and_then(|m| Some((m.paint.clone()?, m.amount as f32))); + let mut fill = if modes.stain { averaged.clone() } else { Some((Paint::solid(stain), 1.0)) }; + if modes.style { + fill = averaged.or(fill); + } else if let Some(paint) = style.as_ref().filter(|p| !matches!(p, Paint::None)) { + // A style without a fill (the default style) gives none. + fill = Some((paint.clone(), 1.0)); + } + if let Some((paint, amount)) = fill { + let mut f = FillLayer::new(paint); + f.opacity = amount.clamp(0.0, 1.0); + n.appearance.items.insert(0, AppearanceItem::Fill(f)); + } + nodes.push(n); } let gid = match set { Some(g) => { @@ -938,13 +1009,18 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { gid } }; + // A new set has the density it is sprayed at; more instances sprayed into a set leave the + // density the set has. + if set.is_none() { + record_set_density(d, &[gid], density); + } sel.set([gid]); Ok(gid) })?; Ok(json!({ "id": id.0, "count": count })) } -fn instance_center(n: &Node) -> Option { +pub(super) fn instance_center(n: &Node) -> Option { match &n.kind { NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO), _ => None, @@ -958,10 +1034,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("unknown tool `{tool}`"))); } crate::cmd::paint::check_keep_model(p, C)?; - let pts = points(p, C)?; + let pts = samples(p, C)?; let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; + 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)?; + // 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. crate::cmd::edit::refuse_symbol_part(s)?; let st = s.doc()?; @@ -969,10 +1050,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; - let style_paint = match str_param(p, "style") { - Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - }; + let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; let mut v = vec![]; @@ -1002,62 +1080,144 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { "screen" => "Symbol Screener", _ => "Symbol Styler", }; - let count = s.edit(label, |d, _| { + // Random: each instance's share of the tool's change, from none of it to twice it, the same + // 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 }; + // 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(); - for (j, q) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO }; + for (j, (q, pressure)) in pts.iter().enumerate() { + let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + // 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. + let target = (method == Method::Average) + .then(|| { + let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius); + let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n))).collect(); + mean(&looks.iter().collect::>(), *q, None) + }) + .flatten(); for id in &candidates { - let Some(n) = d.node_mut(*id) else { continue }; - let Some(c) = instance_center(n) else { continue }; + let Some(c) = d.node(*id).and_then(instance_center) else { continue }; let dist = c.distance(*q); if dist > radius { continue; } - let w = intensity * (1.0 - dist / radius).max(0.0); + let w = strength * (1.0 - dist / radius).max(0.0); if w <= 0.0 { continue; } + let Some(cur) = d.node(*id).and_then(|n| look(d, n)) else { 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" => { + let out = (c - t.middle).hypot(); + out <= 1e-9 || (t.reach - out).abs() < 1e-9 + } + "size" => (t.scale / cur.scale - 1.0).abs() < 1e-9, + "spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9, + "stain" | "style" => { + (t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none()) + } + "screen" => (t.opacity - cur.opacity).abs() < 1e-6, + _ => false, + }); + if at_mean { + continue; + } + let Some(n) = d.node_mut(*id) else { continue }; touched.insert(*id); let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); + let share = share(*id); match tool.as_str() { "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), "scrunch" => { - let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 }; + let v = match &target { + // Toward the instances' mean distance from their middle. + Some(t) => { + let out = c - t.middle; + if out.hypot() > 1e-9 { out * ((t.reach - out.hypot()) / out.hypot() * w.min(1.0)) } else { Vec2::ZERO } + } + None => (*q - c) * (0.15 * w * share) * if alt { -1.0 } else { 1.0 }, + }; n.transform(Affine::translate(v), false); } "size" => { - let k = 1.0 + 0.08 * w; - n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false); + let k = match &target { + Some(t) => (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 + // level drag the width, an upright one the height. A click resizes both. + // The first point of a drag takes the direction to the second. + let along = if j > 0 { delta } else { pts.get(1).map_or(Vec2::ZERO, |(next, _)| *next - *q) }; + let (kx, ky) = if proportional || target.is_some() || along.hypot() <= 1e-9 { + (k, k) + } else { + let level = along.x.abs() / (along.x.abs() + along.y.abs()); + (k.powf(2.0 * level), k.powf(2.0 * (1.0 - level))) + }; + 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 { + n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); + } } "spin" => { - // Turn towards the drag direction; a click spins a little. - let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w }; - n.transform(about(Affine::rotate(if alt { -a } else { a })), false); + let a = match (&target, method) { + (Some(t), _) => 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. + (None, _) if delta.hypot() > 1e-9 => (c - *q).cross(delta).signum() * 0.1 * w, + (None, _) => 0.05 * w, + }; + n.transform(about(Affine::rotate(if alt && target.is_none() { -a } else { a })), false); } "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - if tool == "style" && alt { - n.appearance.items.clear(); - continue; - } - let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); - let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 }; - let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) }; + 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)); + (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) + } + None => { + if tool == "style" && alt { + n.appearance.items.clear(); + continue; + } + let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + let step = match (tool.as_str(), method) { + ("style", Method::Random) => (share / 2.0) as f32, + ("style", _) => 1.0, + _ => (0.15 * w * share) as f32, + }; + (paint, if alt { cur - step } else { cur + step }) + } + }; n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); if o > 0.0 { let mut f = FillLayer::new(paint); - f.opacity = o; + f.opacity = o.min(1.0); n.appearance.items.insert(0, AppearanceItem::Fill(f)); } } _ => { - let step = (0.1 * w) as f32; - n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) }; + 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), + None if alt => (n.opacity + step).min(1.0), + None => (n.opacity - step).max(0.05), + }; } } } } - Ok(touched.len()) + Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..708d845c4b 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -603,6 +603,7 @@ pub(super) const ALLOWED: &[&str] = &[ "symbol.replace", "symbol.selectInstances", "symbol.setCurrent", + "symbol.setDensity", "symbol.sortByName", "symbol.spray", "symbol.unused", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2f849901a4..262f8e980e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -193,6 +193,7 @@ mod swatchlib; mod symbol_nine_slice; mod symbolbounds; mod symboledit; +mod symbolism_options; mod symbollib; mod targeting; mod textcombos; diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs new file mode 100644 index 0000000000..05b707f799 --- /dev/null +++ b/crates/engine/src/tests/symbolism_options.rs @@ -0,0 +1,559 @@ +//! The Symbolism Tools Options the commands take: Method and pen pressure in `symbol.adjust`, the +//! Symbol Sizer's two options, the Symbol Sprayer's `attributes`, and `symbol.setDensity`. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" (its first instance is at 10, 10) 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 bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn xf(s: &Session, id: NodeId) -> Affine { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf, + other => panic!("not an instance: {other:?}"), + } +} + +fn center(s: &Session, id: NodeId) -> Point { + xf(s, id) * Point::ZERO +} + +/// The instance's rotation in radians. +fn angle(s: &Session, id: NodeId) -> f64 { + let c = xf(s, id).as_coeffs(); + c[1].atan2(c[0]) +} + +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() +} + +/// `cmd` with `p` fails with the bad-parameter message `want` and leaves the document and the +/// undo history as they were. +fn refused(s: &mut Session, cmd: &str, p: Value, want: &str) { + let before = state(s); + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{cmd} {p}: {r:?}"); + assert!(state(s) == before, "{cmd} {p} changed the document"); +} + +/// The children of symbol set `set`. +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// Method Average brings the sizes, rotations and opacities of the instances under the brush +/// toward their mean, whichever way Alt is; User Defined changes each one by the same amount. +#[test] +fn average_brings_the_instances_under_the_brush_toward_their_mean() { + // Two instances 20 pt apart, the first grown, turned and faded alone. + let pair = || { + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + let only_a = json!([[200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "spin", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": only_a, "radius": 5, "intensity": 10})); + } + (s, a, b) + }; + let (mut s, a, b) = pair(); + let (wa, wb) = (bounds(&s, a).width(), bounds(&s, b).width()); + let (ra, oa) = (angle(&s, a), node(&s, a).opacity); + assert!(wa > wb + 1.0 && ra.abs() > 0.1 && oa < 0.9, "{wa} {wb} {ra} {oa}"); + assert_eq!((angle(&s, b), node(&s, b).opacity), (0.0, 1.0)); + // User Defined grows both by the same factor: they stay as far apart in size. + let between = json!([[210, 150], [210, 150], [210, 150]]); + let (mut user, ..) = pair(); + adjust(&mut user, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10})); + let ratio = |s: &Session| xf(s, a).determinant() / xf(s, b).determinant(); + assert!((ratio(&user) - ratio(&s)).abs() < 1e-9); + // Average: the two sizes meet at their geometric mean. + let before = ratio(&s); + let product = xf(&s, a).determinant() * xf(&s, b).determinant(); + let (mut alt, ..) = pair(); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + assert!((ratio(&s) - 1.0).abs() < (before - 1.0).abs() / 2.0, "{} from {before}", ratio(&s)); + assert!((xf(&s, a).determinant() * xf(&s, b).determinant() / product - 1.0).abs() < 1e-9); + adjust(&mut alt, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average", "alt": true})); + assert_eq!([xf(&alt, a), xf(&alt, b)], [xf(&s, a), xf(&s, b)], "Alt does not reverse an average"); + // The rotations and the opacities meet too. + adjust(&mut s, json!({"tool": "spin", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (na, nb) = (angle(&s, a), angle(&s, b)); + assert!((na - nb).abs() < ra.abs() / 2.0 && nb.abs() > 1e-3, "{na} {nb} from {ra}"); + adjust(&mut s, json!({"tool": "screen", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}"); +} + +/// Average over instances that already have the mean, or a stroke over no instance, changes +/// nothing and adds no undo step. +#[test] +fn average_at_the_mean_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let before = state(&s); + for tool in ["scrunch", "size", "spin", "stain", "screen", "style"] { + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150], [202, 150]], "radius": 30, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } + let r = adjust(&mut s, json!({"tool": "size", "points": [[50, 50]], "radius": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. +#[test] +fn average_evens_out_the_stain_and_the_spacing() { + let mut s = session(); + let (a, b, c) = (dot(&mut s, 180.0, 150.0), dot(&mut s, 200.0, 150.0), dot(&mut s, 260.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[180, 150], [180, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let amount = |s: &Session, id| node(s, id).appearance.fill().map_or(0.0, |f| f.opacity); + let stained = amount(&s, a); + assert!(stained > 0.2 && amount(&s, b) == 0.0); + adjust( + &mut s, + json!({"tool": "stain", "points": [[190, 150], [190, 150]], "radius": 30, "intensity": 10, "method": "average", "color": "#0000ff"}), + ); + assert!(amount(&s, a) < stained && amount(&s, b) > 0.0, "{} {}", amount(&s, a), amount(&s, b)); + // The stained instance keeps its red, and the other takes the red of the stained one. + for id in [a, b] { + assert_eq!(node(&s, id).appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + } + // Scrunch: the three are 20 and 60 apart; their distances from their middle even out. + let reach = |s: &Session| { + let xs = [a, b, c].map(|id| center(s, id).x); + let middle = xs.iter().sum::() / 3.0; + xs.map(|x| (x - middle).abs()) + }; + let spread = |r: [f64; 3]| r.iter().cloned().fold(0.0, f64::max) - r.iter().cloned().fold(f64::INFINITY, f64::min); + let before = spread(reach(&s)); + adjust(&mut s, json!({"tool": "scrunch", "points": [[213, 150], [213, 150]], "radius": 120, "intensity": 10, "method": "average"})); + assert!(spread(reach(&s)) < before * 0.8, "{} from {before}", spread(reach(&s))); +} + +/// Method Random gives each instance its own share of the change, the same for a stroke however +/// often it is applied; User Defined changes instances at the same distance alike. +#[test] +fn random_changes_each_instance_by_its_own_share() { + let grown = |method: Option<&str>| { + let mut s = session(); + let ids = [(180.0, 150.0), (220.0, 150.0), (200.0, 130.0), (200.0, 170.0)].map(|(x, y)| dot(&mut s, x, y)); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10}); + if let Some(m) = method { + p["method"] = json!(m); + } + adjust(&mut s, p); + ids.map(|id| bounds(&s, id).width()) + }; + let user = grown(None); + assert!(user.iter().all(|w| (w - user[0]).abs() < 1e-9 && *w > 20.5), "{user:?}"); + assert_eq!(grown(Some("userDefined")), user); + let random = grown(Some("random")); + assert!(random.iter().any(|w| (w - random[0]).abs() > 0.05), "{random:?}"); + // From none of the User Defined change to twice it. + let twice = user[0] * user[0] / 20.0; + assert!(random.iter().all(|w| *w >= 20.0 - 1e-9 && *w <= twice + 1e-9), "{random:?} within 20..{twice}"); + assert_eq!(grown(Some("random")), random); +} + +/// A `method` that is none of the three is an error and changes nothing; the Symbol Shifter takes +/// one and shifts as it does without. +#[test] +fn an_unknown_method_is_refused() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (bad, shown) in [(json!("smooth"), "\"smooth\""), (json!(3), "3"), (json!(true), "true"), (json!("Average"), "\"Average\"")] { + for tool in ["size", "shift"] { + let want = format!("`method` must be userDefined, average or random, not {shown}"); + refused(&mut s, "symbol.adjust", json!({"tool": tool, "points": [[200, 150]], "method": bad}), &want); + } + } + let shifted = |method: Value| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [215, 150]], "intensity": 10, "method": method})); + center(&s, a) + }; + let moved = shifted(Value::Null); + assert!(moved.x > 205.0); + for method in ["average", "random", "userDefined"] { + assert_eq!(shifted(json!(method)), moved, "{method}"); + } + assert_eq!(center(&s, a), Point::new(200.0, 150.0)); +} + +/// 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] +fn pen_pressure_is_the_intensity_with_use_pressure() { + let width = |points: Value, use_pressure: Option, intensity: f64| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 40, "intensity": intensity}); + if let Some(on) = use_pressure { + p["usePressure"] = json!(on); + } + let count = adjust(&mut s, p)["count"].as_u64().unwrap(); + (bounds(&s, a).width(), count) + }; + let (light, _) = width(json!([[200, 150, 0.25]]), Some(true), 5.0); + let (hard, _) = width(json!([[200, 150, 1.0]]), Some(true), 5.0); + assert!(20.0 < light && light < hard, "{light} {hard}"); + // Full pressure is intensity 10, whatever `intensity` says; a point without a pressure has 1. + assert_eq!(width(json!([[200, 150]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150]]), Some(true), 1.0).0, hard); + assert_eq!(width(json!([[200, 150, null]]), Some(true), 1.0).0, hard); + // No pressure: the instance stays as it is. + assert_eq!(width(json!([[200, 150, 0]]), Some(true), 5.0), (20.0, 0)); + // A pressure outside 0..1 is kept within it. + assert_eq!(width(json!([[200, 150, 7]]), Some(true), 5.0).0, hard); + // Without Use Pressure Pen the pressure is not used. + assert_eq!(width(json!([[200, 150, 0.25]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150, 0.25]]), Some(false), 10.0).0, hard); + let mut s = session(); + dot(&mut s, 200.0, 150.0); + for tool in ["size", "shift"] { + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), + "a point's pressure must be a number, not \"hard\"", + ); + } + for key in ["usePressure", "proportional", "affectsDensity"] { + let mut p = json!({"tool": "size", "points": [[200, 150]]}); + p[key] = json!("yes"); + refused(&mut s, "symbol.adjust", p, &format!("`{key}` must be true or false")); + } +} + +/// The Symbol Sizer without Proportional Resizing resizes along the drag: a level drag the width, +/// an upright one the height, a click both. +#[test] +fn the_sizer_without_proportional_resizing_resizes_along_the_drag() { + let size = |points: Value, proportional: Option| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 60, "intensity": 10}); + if let Some(on) = proportional { + p["proportional"] = json!(on); + } + adjust(&mut s, p); + (bounds(&s, a).width(), bounds(&s, a).height()) + }; + let level = json!([[195, 150], [205, 150]]); + let (w, h) = size(level.clone(), Some(false)); + assert!(w > 21.0 && (h - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 145], [200, 155]]), Some(false)); + assert!(h > 21.0 && (w - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 150]]), Some(false)); + assert!(w > 20.5 && (w - h).abs() < 1e-9, "{w} x {h}"); + // Proportional Resizing (the default) keeps the shape for any drag, at the same area. + let (pw, ph) = size(level.clone(), None); + assert!(pw > 20.5 && (pw - ph).abs() < 1e-9, "{pw} x {ph}"); + assert_eq!(size(level.clone(), Some(true)), (pw, ph)); + let (w, h) = size(level, Some(false)); + assert!((w * h - pw * ph).abs() < 1e-6, "{w} x {h} against {pw} x {ph}"); +} + +/// With Resizing Affects Density an instance moves away from the brush's center as it grows and +/// toward it as it shrinks; without, it stays where it is. +#[test] +fn resizing_affects_density_moves_instances_from_the_brush_center() { + let at = |affects: Option, alt: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "alt": alt}); + if let Some(on) = affects { + p["affectsDensity"] = json!(on); + } + adjust(&mut s, p); + (center(&s, a), bounds(&s, a).width()) + }; + let (stays, grown) = at(None, false); + assert!((stays.x - 220.0).abs() < 1e-9 && grown > 20.5); + assert_eq!(at(Some(false), false), (stays, grown)); + let (away, width) = at(Some(true), false); + assert!(away.x > 220.5 && (away.y - 150.0).abs() < 1e-9 && width > 20.5, "{away:?}"); + let (toward, width) = at(Some(true), true); + assert!(toward.x < 219.5 && width < 19.5, "{toward:?}"); +} + +/// A new instance of the Symbol Sprayer takes the mean of the selected set's instances under the +/// brush for each attribute that is `average`, and the plain value for each that is `userDefined`. +#[test] +fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { + 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]; + // In an area without instances an average is the plain value. + assert!(node(&s, first).opacity == 1.0 && node(&s, first).appearance.fill().is_none() && angle(&s, first) == 0.0); + // Grow, fade and stain the set's one instance. + let on_it = json!([[200, 150], [200, 150], [200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "screen", "stain"] { + adjust(&mut s, json!({"tool": tool, "points": on_it, "radius": 40, "intensity": 10, "color": "#ff0000"})); + } + let look = |s: &Session, id: NodeId| { + let n = node(s, id); + (bounds(s, id).width(), n.opacity, n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity))) + }; + let (width, opacity, stain) = look(&s, first); + assert!(width > 24.0 && opacity < 0.7 && stain.as_ref().is_some_and(|(_, amount)| *amount > 0.5), "{width} {opacity} {stain:?}"); + let spray = |s: &mut Session, at: Value, extra: Value| { + let mut p = json!({"name": "Dot", "points": at, "radius": 30}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("symbol.spray", &p).unwrap(); + *members(s, set).last().unwrap() + }; + // Average (the default): the new instance, sprayed beside it, looks like it. + let near = spray(&mut s, json!([[215, 150]]), json!({})); + let (w, o, f) = look(&s, near); + assert!((w / width - 1.0).abs() < 0.11, "{w} of {width}"); + assert_eq!((o, f), (opacity, stain.clone())); + // The averages of two instances that look alike are theirs. + let third = spray(&mut s, json!([[208, 165]]), json!({"attributes": {"size": "average", "screen": null}})); + assert_eq!(look(&s, third).1, opacity); + // Style: Average replaces a User Defined stain with the fill of the instances under the brush. + let mixed = spray(&mut s, json!([[205, 160]]), json!({"attributes": {"stain": "userDefined"}, "color": "#0000ff"})); + assert_eq!(look(&s, mixed).2.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + // Outside the brush's radius of every instance, the plain values. + let far = spray(&mut s, json!([[330, 250]]), json!({})); + let (w, o, f) = look(&s, far); + assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0 && f.is_none(), "{w} {o} {f:?}"); + // User Defined: the symbol's size and opaque; Style: Average still gives the fill under the brush. + let user = json!({"size": "userDefined", "screen": "userDefined", "stain": "userDefined", "spin": "userDefined"}); + let plain = spray(&mut s, json!([[212, 140]]), json!({"attributes": user, "color": "#0000ff"})); + let (w, o, f) = look(&s, plain); + assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0, "{w} {o}"); + assert_eq!(f.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + assert_eq!(angle(&s, plain), 0.0, "one point has no direction"); + // With no fill under the brush, Stain: User Defined is the fill color in full, and a User Defined + // style without a fill (the document has only the default style) leaves it. + let blue = spray(&mut s, json!([[330, 40]]), json!({"attributes": user, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + let styled = json!({"stain": "userDefined", "style": "userDefined"}); + let blue = spray(&mut s, json!([[330, 100]]), json!({"attributes": styled, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + // Spin: User Defined turns the instances the way the stroke runs (here: down the page). + let down = spray(&mut s, json!([[100, 40], [100, 140]]), json!({"attributes": {"spin": "userDefined"}})); + assert!((angle(&s, down) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{}", angle(&s, down)); + let level = spray(&mut s, json!([[40, 260], [140, 260]]), json!({})); + assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush"); +} + +/// Spin: Average turns a new instance to the mean direction of the instances under the brush, and +/// Scrunch: Average spaces new instances as those under the brush are spaced. +#[test] +fn the_sprayer_averages_rotation_and_spacing() { + // A set of six instances 30 pt apart, turned by a drag of the Symbol Spinner; then a stroke + // along the row, 4 pt between its points, with Scrunch as given. Returns the rotations of the + // six, how many instances the stroke added and the rotation of the last one. + let sprayed = |scrunch: &str| { + let mut s = session(); + let row: Vec = (0..6).map(|i| json!([100.0 + 30.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": row, "radius": 2, "density": 10}); + let set = NodeId(s.execute("symbol.spray", &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(members(&s, set).len(), 6); + adjust(&mut s, json!({"tool": "spin", "points": [[175, 60], [176, 60], [177, 60], [178, 60]], "radius": 200, "intensity": 10})); + let turned: Vec = members(&s, set).iter().map(|id| angle(&s, *id)).collect(); + let stroke: Vec = (0..40).map(|i| json!([100.0 + 4.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": stroke, "radius": 40, "density": 10, "attributes": {"scrunch": scrunch}}); + let n = s.execute("symbol.spray", &p).unwrap()["count"].as_u64().unwrap(); + let new = *members(&s, set).last().unwrap(); + (turned, n, angle(&s, new)) + }; + let (turned, plain, _) = sprayed("userDefined"); + assert!(turned.iter().all(|a| a.abs() > 0.05 && a.signum() == turned[0].signum()), "{turned:?}"); + // User Defined keeps new instances 3 pt apart (20 pt × 0.15 at density 10); Average keeps them + // as far apart as the instances under the brush are, about 30 pt. + let (_, spaced, new_angle) = sprayed("average"); + assert!(spaced < plain, "{spaced} spaced like the row against {plain}"); + assert!(new_angle.signum() == turned[0].signum() && new_angle.abs() > 0.05, "{new_angle} against {turned:?}"); +} + +/// The Symbol Sprayer's `attributes` must be an object of the six keys, each `average` or +/// `userDefined`; anything else is an error and sprays nothing. +#[test] +fn bad_sprayer_attributes_are_refused() { + let mut s = session(); + let calls = [ + (json!("average"), "`attributes` must be an object, not \"average\"".to_string()), + (json!(["size"]), "`attributes` must be an object, not [\"size\"]".to_string()), + (json!({"density": "average"}), "unknown attribute `density`".to_string()), + (json!({"size": "big"}), "attribute `size` must be average or userDefined, not \"big\"".to_string()), + (json!({"spin": true}), "attribute `spin` must be average or userDefined, not true".to_string()), + (json!({"style": "Average"}), "attribute `style` must be average or userDefined, not \"Average\"".to_string()), + ]; + for (attributes, want) in calls { + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "attributes": attributes}), &want); + } + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "keepModel": "yes"}), "`keepModel` must be true or false"); + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150, "x"]]}), "a point's pressure must be a number, not \"x\""); + let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"}); + assert_eq!(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "attributes": all})).unwrap()["count"], 1); +} + +/// `symbol.setDensity` spaces a symbol set's instances from its middle as the new density packs +/// them, as one undo step, and adds none when no instance moves. +#[test] +fn set_density_spaces_the_instances_of_a_symbol_set() { + let mut s = session(); + let row: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 8); + let centers = |s: &Session| ids.iter().map(|id| center(s, *id)).collect::>(); + let middle = |c: &[Point]| Point::new(c.iter().map(|p| p.x).sum::() / 8.0, c.iter().map(|p| p.y).sum::() / 8.0); + let (was, steps) = (centers(&s), undo_len(&s)); + // From 5 to 9: 0.25 / 0.65 of each distance from the middle, which stays where it is. + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert_eq!(undo_len(&s), steps + 1); + let now = centers(&s); + let (m, ratio) = (middle(&was), 0.25 / 0.65); + assert!(middle(&now).distance(m) < 1e-9); + for (before, after) in was.iter().zip(&now) { + assert!(after.distance(m + (*before - m) * ratio) < 1e-9, "{before:?} -> {after:?}"); + } + // Back from 9 to 5: where they were, once for a set named twice. + let r = s.execute("symbol.setDensity", &json!({"from": 9, "to": 5, "ids": [set.0, set.0]})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); + // The density the set has (5, a `from` of 7 notwithstanding), or a set of one instance: no + // instance moves and no undo step is added. + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 7, "to": 5})).unwrap(), json!({"ids": [], "count": 0})); + s.select(|_, sel| sel.clear()).unwrap(); + let one = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 40]]})).unwrap()["id"].as_u64().unwrap()); + let steps_with_one = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 1, "to": 10, "ids": [one.0]})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!((steps_with_one, undo_len(&s)), (steps + 1, steps + 1)); + // Undo puts a spaced set back. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 1, "id": set.0})).unwrap(); + assert!(centers(&s)[0].distance(was[0]) > 1.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); +} + +/// A set packs from the density it was created at, whatever `from` says and whatever density more +/// instances were sprayed into it at; a set without a recorded density packs from `from`. +#[test] +fn set_density_starts_from_the_density_a_set_was_sprayed_at() { + 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()); + let ids = members(&s, set); + 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})).unwrap(); + let ratio = 0.25 / 0.95; + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * ratio)).abs() < 1e-9, "{before} -> {after}"); + } + // Given density 2, the set stays at 2 when more instances are sprayed into it at 9. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 2, "ids": [set.0]})).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 200]], "radius": 4, "density": 9})).unwrap(); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 9, "to": 2, "ids": [set.0]})).unwrap()["count"], 0); + // Without the record (a set grouped by hand), `from` is the starting density. + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 200.0, 150.0)); + s.select(|_, sel| sel.set([a, b])).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(group) { + n.name = Some("Symbol Set".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [group.0]})).unwrap(); + assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); +} + +/// A locked instance of the set stays where it is, and the others move. +#[test] +fn set_density_leaves_a_locked_instance_in_place() { + let mut s = session(); + let row: Vec = (0..3).map(|i| json!([100.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + s.edit("Lock", |d, _| { + if let Some(n) = d.node_mut(ids[0]) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + assert!(r["count"].as_u64().is_some_and(|n| (1..=2).contains(&n)), "{r}"); + assert_eq!(center(&s, ids[0]), was[0]); + assert!(center(&s, ids[2]).distance(was[2]) > 1.0); +} + +/// `symbol.setDensity` refuses a density left out, not a number or outside 1..10, an id naming no +/// object, and objects with no symbol set among them. +#[test] +fn set_density_refuses_bad_densities_and_objects_without_a_set() { + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + for (p, want) in [ + (json!({"to": 5}), "missing `from`".to_string()), + (json!({"from": 5}), "missing `to`".to_string()), + (json!({"from": "5", "to": 6}), "`from` must be a number from 1 to 10, not \"5\"".to_string()), + (json!({"from": 5, "to": 11}), "`to` must be a number from 1 to 10, not 11".to_string()), + (json!({"from": 0, "to": 5}), "`from` must be a number from 1 to 10, not 0".to_string()), + (json!({"from": null, "to": 5}), "`from` must be a number from 1 to 10, not null".to_string()), + ] { + refused(&mut s, "symbol.setDensity", p, &want); + } + let before = state(&s); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [987_654]})).is_err()); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": "all"})).is_err()); + // An instance is not a set, and neither is nothing selected. + let member = members(&s, set)[0]; + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [member.0]})).is_err()); + s.select(|_, sel| sel.clear()).unwrap(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})); + assert!(matches!(&r, Err(EngineError::Other(msg)) if msg == "no symbol set selected"), "{r:?}"); + assert!(state(&s) == before); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index e801df4a7a..1ecdb6c98a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -937,7 +937,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a4d1b1a64f..5603a0795d 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -23,7 +23,27 @@ const ROWS: &[Row] = &[ // Global Brush Dimensions. (LIQUIFY, Some("liquify"), &["width", "height", "angle", "intensity", "usePressure", "showBrush"]), (LIQUIFY, None, &["detail", "simplify", "simplifyOn", "rate", "complexity", "horizontal", "vertical", "affectAnchors", "affectIn", "affectOut"]), - (SYMBOLISM, Some("symbolism"), &["diameter", "intensity", "density"]), + // Symbolism Tools Options: the general options, then the Symbol Sprayer's and the Symbol Sizer's. + ( + SYMBOLISM, + Some("symbolism"), + &[ + "diameter", + "intensity", + "density", + "usePressure", + "method", + "showBrush", + "sprayScrunch", + "spraySize", + "spraySpin", + "sprayScreen", + "sprayStain", + "sprayStyle", + "proportional", + "affectsDensity", + ], + ), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 580e61d4fd..f407792170 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -23,9 +23,26 @@ pub fn create(id: &str) -> Option> { }) } +/// The values of Method in the Symbolism Tools Options. +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 Symbol Sprayer options: (tool option, key in `symbol.spray`'s `attributes`). +pub const SPRAY_ATTRIBUTES: [(&str, &str); 6] = [ + ("sprayScrunch", "scrunch"), + ("spraySize", "size"), + ("spraySpin", "spin"), + ("sprayScreen", "screen"), + ("sprayStain", "stain"), + ("sprayStyle", "style"), +]; + pub struct SymbolismTool { id: &'static str, - points: Vec, + /// The drag's points, each with its pen pressure (0..1). + points: Vec<(Point, f64)>, /// How many points the last preview had ([`previews_at`] thins previews of a long drag). previewed: usize, active: bool, @@ -41,6 +58,24 @@ pub struct SymbolismTool { pub symbol: Option, /// Graphic style for the Styler (None = the document's first non-default style). pub style: Option, + /// Use Pressure Pen: each point's pen pressure is the intensity there. + pub use_pressure: bool, + /// Method of the Scruncher, Sizer, Spinner, Stainer, Screener and Styler: one of [`METHODS`]. + pub method: &'static str, + /// Show Brush Size and Intensity: the brush outline follows the pointer. + pub show_brush: bool, + /// The Symbol Sprayer options, in the order of [`SPRAY_ATTRIBUTES`]: each one of [`SPRAY_MODES`]. + pub spray: [&'static str; 6], + /// Symbol Sizer: Proportional Resizing. + pub proportional: bool, + /// Symbol Sizer: Resizing Affects Density. + pub affects_density: bool, +} + +/// `v` as one of `allowed`, when it is one. +fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> { + let s = v.as_str()?; + allowed.iter().copied().find(|a| *a == s) } impl SymbolismTool { @@ -67,6 +102,12 @@ impl SymbolismTool { density: 5.0, symbol: None, style: None, + use_pressure: false, + method: "userDefined", + show_brush: true, + spray: ["average"; 6], + proportional: true, + affects_density: false, } } @@ -86,14 +127,28 @@ impl SymbolismTool { /// The command + params for the gesture so far. pub fn command(&self, cx: &ToolContext) -> (String, Value) { let radius = self.diameter / 2.0; - let pts = points_json(&self.points); if self.id == "symbolSprayer" { - let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt}); + let pts = points_json(&self.points.iter().map(|(p, _)| *p).collect::>()); + let attributes: serde_json::Map = + SPRAY_ATTRIBUTES.iter().zip(self.spray).map(|((_, key), mode)| (key.to_string(), json!(mode))).collect(); + let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt, "attributes": attributes}); if let Some(s) = &self.symbol { v["name"] = json!(s); } + // Stain: User Defined stains the new instances with the fill color in its own model. + if self.spray[4] == "userDefined" + && let Some(c) = cx.paint.fill.color() + { + v["color"] = serde_json::to_value(c).unwrap_or(Value::Null); + v["keepModel"] = json!(true); + } + if let Some(s) = &self.style { + v["style"] = json!(s); + } return ("symbol.spray".into(), v); } + let pressure = self.use_pressure; + let pts = Value::Array(self.points.iter().map(|(p, f)| if pressure { json!([p.x, p.y, f]) } else { json!([p.x, p.y]) }).collect()); let tool = match self.id { "symbolShifter" => "shift", "symbolScruncher" => "scrunch", @@ -113,6 +168,17 @@ impl SymbolismTool { if let Some(s) = &self.style { v["style"] = json!(s); } + if pressure { + v["usePressure"] = json!(true); + } + // The Symbol Shifter has no Method. + if tool != "shift" { + v["method"] = json!(self.method); + } + if tool == "size" { + v["proportional"] = json!(self.proportional); + v["affectsDensity"] = json!(self.affects_density); + } ("symbol.adjust".into(), v) } } @@ -140,9 +206,10 @@ impl Tool for SymbolismTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; self.hover = Some(p); + let sample = (p, f64::from(ev.pressure).clamp(0.0, 1.0)); match ev.kind { PointerKind::Down => { - self.points = vec![p]; + self.points = vec![sample]; self.previewed = 1; self.active = true; self.alt = ev.mods.alt; @@ -153,10 +220,10 @@ 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) { + if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|(l, _)| l.distance(p) < step) { return vec![]; } - self.points.push(p); + self.points.push(sample); if !previews_at(self.points.len()) { return vec![]; } @@ -193,9 +260,15 @@ impl Tool for SymbolismTool { vec![] } fn overlays(&self, _cx: &ToolContext) -> Vec { - let Some(p) = self.hover else { return vec![] }; - let circle = kurbo::Circle::new(p, self.diameter / 2.0).to_path(0.1); - vec![Overlay::Path { path: circle, color: FEEDBACK, width: 1.0, dashed: false }] + let Some(p) = self.hover.filter(|_| self.show_brush) else { return vec![] }; + let ring = |radius: f64, dashed| Overlay::Path { path: kurbo::Circle::new(p, radius).to_path(0.1), color: FEEDBACK, width: 1.0, dashed }; + let mut v = vec![ring(self.diameter / 2.0, false)]; + // The intensity: a dashed ring that fills the brush at 10. A pen's pressure sets it instead + // with Use Pressure Pen, so no ring is drawn then. + if !self.use_pressure && self.intensity < 10.0 { + v.push(ring(self.diameter / 2.0 * self.intensity / 10.0, true)); + } + v } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { match self.id { @@ -210,7 +283,22 @@ impl Tool for SymbolismTool { } } fn options(&self) -> Value { - json!({"diameter": self.diameter, "intensity": self.intensity, "density": self.density, "symbol": self.symbol, "style": self.style}) + let mut v = json!({ + "diameter": self.diameter, + "intensity": self.intensity, + "density": self.density, + "symbol": self.symbol, + "style": self.style, + "usePressure": self.use_pressure, + "method": self.method, + "showBrush": self.show_brush, + "proportional": self.proportional, + "affectsDensity": self.affects_density, + }); + for ((key, _), mode) in SPRAY_ATTRIBUTES.iter().zip(self.spray) { + v[*key] = json!(mode); + } + v } fn set_option(&mut self, key: &str, v: &Value) { match key { @@ -219,7 +307,16 @@ impl Tool for SymbolismTool { "density" => self.density = v.as_f64().unwrap_or(self.density).clamp(1.0, 10.0), "symbol" => self.symbol = v.as_str().map(str::to_string), "style" => self.style = v.as_str().map(str::to_string), - _ => {} + "usePressure" => self.use_pressure = v.as_bool().unwrap_or(self.use_pressure), + "method" => self.method = one_of(v, &METHODS).unwrap_or(self.method), + "showBrush" => self.show_brush = v.as_bool().unwrap_or(self.show_brush), + "proportional" => self.proportional = v.as_bool().unwrap_or(self.proportional), + "affectsDensity" => self.affects_density = v.as_bool().unwrap_or(self.affects_density), + _ => { + if let Some(i) = SPRAY_ATTRIBUTES.iter().position(|(k, _)| *k == key) { + self.spray[i] = one_of(v, &SPRAY_MODES).unwrap_or(self.spray[i]); + } + } } } } @@ -376,6 +473,125 @@ mod tests { assert!(matches!(&a[1], Action::Preview(_, v) if v["color"] == fill && v["keepModel"] == true), "{a:?}"); } + /// The Symbolism Tools Options the tools keep, with what each is before it is set. + #[test] + fn the_options_dialog_fields_are_tool_options() { + let mut t = SymbolismTool::new("symbolSizer"); + let o = t.options(); + assert_eq!((o["usePressure"].clone(), o["method"].clone(), o["showBrush"].clone()), (json!(false), json!("userDefined"), json!(true))); + assert_eq!((o["proportional"].clone(), o["affectsDensity"].clone()), (json!(true), json!(false))); + for (key, _) in SPRAY_ATTRIBUTES { + assert_eq!(o[key], "average", "{key}"); + } + for (key, v) in [ + ("usePressure", json!(true)), + ("method", json!("random")), + ("showBrush", json!(false)), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ("sprayStain", json!("userDefined")), + ] { + t.set_option(key, &v); + assert_eq!(t.options()[key], v, "{key}"); + } + // A value that is none of an option's choices leaves it as it was. + for (key, v) in [("method", json!("smooth")), ("method", json!(2)), ("sprayStain", json!("random")), ("usePressure", json!("yes"))] { + let before = t.options(); + t.set_option(key, &v); + assert_eq!(t.options(), before, "{key}: {v}"); + } + } + + /// The adjusting tools send the Method (the Shifter has none), the Sizer its two options, and + /// with Use Pressure Pen each point's pen pressure. + #[test] + fn adjust_tools_send_the_method_the_sizer_options_and_the_pen_pressure() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let press = |t: &mut SymbolismTool| { + let down = PointerEvent { pressure: 0.25, ..PointerEvent::new(PointerKind::Down, 5.0, 5.0) }; + match t.pointer(&cx, &down).swap_remove(1) { + Action::Preview(_, v) => v, + other => panic!("{other:?}"), + } + }; + let mut sizer = SymbolismTool::new("symbolSizer"); + let v = press(&mut sizer); + assert_eq!((v["method"].clone(), v["proportional"].clone(), v["affectsDensity"].clone()), (json!("userDefined"), json!(true), json!(false))); + assert_eq!((v["points"].clone(), v.get("usePressure")), (json!([[5.0, 5.0]]), None)); + sizer.set_option("usePressure", &json!(true)); + sizer.set_option("method", &json!("average")); + sizer.set_option("affectsDensity", &json!(true)); + let v = press(&mut sizer); + assert_eq!((v["points"].clone(), v["usePressure"].clone()), (json!([[5.0, 5.0, 0.25]]), json!(true))); + assert_eq!((v["method"].clone(), v["affectsDensity"].clone()), (json!("average"), json!(true))); + let mut shifter = SymbolismTool::new("symbolShifter"); + shifter.set_option("method", &json!("random")); + let v = press(&mut shifter); + assert!(v.get("method").is_none() && v.get("proportional").is_none(), "{v}"); + let mut spinner = SymbolismTool::new("symbolSpinner"); + spinner.set_option("method", &json!("random")); + let v = press(&mut spinner); + assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); + } + + /// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is + /// User Defined. + #[test] + fn the_sprayer_sends_its_attributes() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolSprayer"); + t.set_option("usePressure", &json!(true)); + let spray = |t: &mut SymbolismTool| match t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)).swap_remove(1) { + Action::Preview(c, v) if c == "symbol.spray" => v, + other => panic!("{other:?}"), + }; + let v = spray(&mut t); + let average = + json!({"scrunch": "average", "size": "average", "spin": "average", "screen": "average", "stain": "average", "style": "average"}); + assert_eq!((v["attributes"].clone(), v.get("color"), v["points"].clone()), (average, None, json!([[5.0, 5.0]]))); + t.set_option("sprayStain", &json!("userDefined")); + t.set_option("spraySpin", &json!("userDefined")); + let v = spray(&mut t); + assert_eq!( + (v["attributes"]["stain"].clone(), v["attributes"]["spin"].clone(), v["attributes"]["size"].clone()), + (json!("userDefined"), json!("userDefined"), json!("average")) + ); + assert_eq!((v["color"].clone(), v["keepModel"].clone()), (serde_json::to_value(p.fill.color().unwrap()).unwrap(), json!(true))); + } + + /// Show Brush Size and Intensity: the brush's outline with a dashed ring for the intensity + /// inside it; no ring with Use Pressure Pen or at intensity 10, and nothing with it off. + #[test] + fn show_brush_size_and_intensity_draws_the_brush() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolScruncher"); + assert!(t.overlays(&cx).is_empty(), "no pointer yet"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + let rings = |t: &SymbolismTool| { + t.overlays(&cx) + .into_iter() + .map(|o| match o { + Overlay::Path { path, dashed, .. } => (path.bounding_box().width().round(), dashed), + other => panic!("{other:?}"), + }) + .collect::>() + }; + assert_eq!(rings(&t), [(80.0, false), (40.0, true)]); + t.set_option("intensity", &json!(10)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("intensity", &json!(2)); + t.set_option("usePressure", &json!(true)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("showBrush", &json!(false)); + assert!(t.overlays(&cx).is_empty()); + } + #[test] fn brackets_change_diameter_and_intensity() { let (d, _) = doc_with_rect(); diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 33d902b90e..524b4e5c8c 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -1,10 +1,16 @@ //! Symbolism Tools Options (double-click a Symbolism tool): the brush the eight tools share, which //! lasts across tool switches and is saved with the preferences. OK sets it with -//! `tool.setOption {tool, values}`. +//! `tool.setOption {tool, values}`, and gives a new Symbol Set Density to the selected symbol sets +//! with `symbol.setDensity`. //! -//! Fields: `tool`; `diameter` (points), `intensity` and `density` (Symbol Set Density), 1–10. +//! Fields: `tool` (the tool whose options show; the Tool row changes it); `diameter` (points), +//! `intensity` and `density` (Symbol Set Density), 1–10; `usePressure`; `method` (`userDefined`, +//! `average` or `random`); `showBrush`; `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, +//! `sprayStain` and `sprayStyle` (Symbol Sprayer, each `average` or `userDefined`); `proportional` +//! and `affectsDensity` (Symbol Sizer); `densityWas` (the density the dialog opened with). use serde_json::{Map, Value, json}; +use vectorcraft_tools::settings::SYMBOLISM; use super::{DialogResult, DialogSpec, form, run_and_close}; use crate::state::Dialog; @@ -14,19 +20,35 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "symbolismOptions"; pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 340.0, ..DialogSpec::FORM }; -/// The options the dialog edits. -const KEYS: [&str; 3] = ["diameter", "intensity", "density"]; +/// The numbers the dialog edits. +const NUMBERS: [&str; 3] = ["diameter", "intensity", "density"]; + +/// The checkboxes the dialog edits. +const SWITCHES: [&str; 4] = ["usePressure", "showBrush", "proportional", "affectsDensity"]; + +/// The Symbol Sprayer options. +const SPRAY: [&str; 6] = ["sprayScrunch", "spraySize", "spraySpin", "sprayScreen", "sprayStain", "sprayStyle"]; + +/// The density the dialog opened with: OK spaces the selected symbol sets from it to the new one. +const DENSITY_WAS: &str = "densityWas"; /// Width of the label column. const LABEL_W: f32 = 130.0; +/// Width of the dropdowns. +const CHOICE_W: f32 = 170.0; + /// Open the options of Symbolism tool `tool` (one of `vectorcraft_tools::settings::SYMBOLISM`) /// with their current values. pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { let o = app.session.tool_options_of(tool); - let mut fields: Map = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + let keys = NUMBERS.iter().chain(&SWITCHES).chain(&SPRAY).chain(&["method"]); + let mut fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + if let Some(density) = fields.get("density").cloned() { + fields.insert(DENSITY_WAS.into(), density); + } fields.insert("tool".into(), json!(tool)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); json!({ "dialog": KIND }) @@ -34,22 +56,74 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { 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). + let tools: Vec<(&str, &str)> = SYMBOLISM.iter().filter_map(|id| Some((*id, vectorcraft_tools::tool_info(id)?.label))).collect(); + form::choice(ui, d, "tool", tl!("Tool:"), (LABEL_W, CHOICE_W), &tools); + let tool = d.str("tool"); + ui.add_space(6.0); widgets::label_row(ui, tl!("Diameter:"), LABEL_W, |ui| { form::length(ui, d, "diameter", unit, 100.0); }); - for (key, label) in [("intensity", tl!("Intensity:")), ("density", tl!("Symbol Set Density:"))] { - widgets::label_row(ui, label, LABEL_W, |ui| { - if let Some(v) = widgets::range_field(ui, ("symbolism", key), d.f64(key, 5.0), 1.0..=10.0, "", 0, 100.0) { - d.fields.insert(key.into(), json!(v)); + let pressure = d.bool("usePressure"); + widgets::label_row(ui, tl!("Intensity:"), LABEL_W, |ui| { + ui.add_enabled_ui(!pressure, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", "intensity"), d.f64("intensity", 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert("intensity".into(), json!(v)); } }); + }); + widgets::label_row(ui, "", LABEL_W, |ui| form::check(ui, d, "usePressure", tl!("Use Pressure Pen"))); + widgets::label_row(ui, tl!("Symbol Set Density:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", "density"), d.f64("density", 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert("density".into(), json!(v)); + } + }); + // The Symbol Sprayer and the Symbol Shifter have no Method. + ui.add_enabled_ui(!["symbolSprayer", "symbolShifter"].contains(&tool.as_str()), |ui| { + let methods = [("userDefined", tl!("User Defined")), ("average", tl!("Average")), ("random", tl!("Random"))]; + form::choice(ui, d, "method", tl!("Method:"), (LABEL_W, CHOICE_W), &methods); + }); + if tool == "symbolSprayer" { + ui.add_space(10.0); + widgets::subheader(ui, tl!("Symbol Sprayer Options")); + ui.add_space(4.0); + let modes = [("average", tl!("Average")), ("userDefined", tl!("User Defined"))]; + let labels = [tl!("Scrunch:"), tl!("Size:"), tl!("Spin:"), tl!("Screen:"), tl!("Stain:"), tl!("Style:")]; + for (key, label) in SPRAY.iter().zip(labels) { + form::choice(ui, d, key, label, (LABEL_W, CHOICE_W), &modes); + } } + if tool == "symbolSizer" { + ui.add_space(10.0); + widgets::subheader(ui, tl!("Symbol Sizer Options")); + ui.add_space(4.0); + form::check(ui, d, "proportional", tl!("Proportional Resizing")); + form::check(ui, d, "affectsDensity", tl!("Resizing Affects Density")); + } + ui.add_space(10.0); + form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); false } -/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). +/// The selected symbol sets. +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() +} + +/// 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 values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); + 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))))); + values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); + 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 })) } @@ -58,12 +132,21 @@ mod tests { use super::*; use vectorcraft_engine::Session; - #[test] - fn the_symbolism_tools_share_the_options_ok_sets() { + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app + } + + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn the_symbolism_tools_share_the_options_ok_sets() { + let mut app = app(); app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); - let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + let text = painted(&mut app); for label in ["Symbolism Tools Options", "Diameter:", "Intensity:", "Symbol Set Density:"] { assert!(text.contains(label), "{label} in {text}"); } @@ -78,4 +161,100 @@ mod tests { let o = app.session.tool_options_of("symbolSprayer"); assert_eq!((o["diameter"].as_f64(), o["intensity"].as_f64(), o["density"].as_f64()), (Some(120.0), Some(9.0), Some(2.0))); } + + /// Every tool shows the general options; the Symbol Sprayer and the Symbol Sizer show their own + /// sections, and the Tool row's choice decides which. + #[test] + fn the_sprayer_and_the_sizer_show_their_sections() { + let mut app = app(); + let general = ["Tool:", "Use Pressure Pen", "Method:", "User Defined", "Show Brush Size and Intensity"]; + let sprayer = ["Symbol Sprayer Options", "Scrunch:", "Size:", "Spin:", "Screen:", "Stain:", "Style:"]; + let sizer = ["Symbol Sizer Options", "Proportional Resizing", "Resizing Affects Density"]; + for (tool, own, others) in + [("symbolSprayer", &sprayer[..], &sizer[..]), ("symbolSizer", &sizer[..], &sprayer[..]), ("symbolStainer", &[][..], &sprayer[..])] + { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let text = painted(&mut app); + for label in general.iter().chain(own) { + assert!(text.contains(label), "{tool}: {label} in {text}"); + } + for label in others { + assert!(!text.contains(label), "{tool}: no {label} in {text}"); + } + } + // The Stainer's dialog, switched to the Sizer with the Tool row. + app.ui.dialog.as_mut().unwrap().fields.insert("tool".into(), json!("symbolSizer")); + let text = painted(&mut app); + assert!(text.contains("Proportional Resizing") && !text.contains("Scrunch:"), "{text}"); + } + + /// OK sets Method, Use Pressure Pen, Show Brush Size and Intensity and the Sprayer's and the + /// Sizer's options for the eight tools, and the dialog opens with them again. + #[test] + fn ok_sets_the_method_the_pen_and_the_tool_sections() { + let mut app = app(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.str("method"), d.bool("usePressure"), d.bool("showBrush")), ("userDefined".to_string(), false, true)); + assert_eq!((d.str("sprayStain"), d.bool("proportional"), d.bool("affectsDensity")), ("average".to_string(), true, false)); + for (k, v) in [ + ("method", json!("random")), + ("usePressure", json!(true)), + ("showBrush", json!(false)), + ("sprayStain", json!("userDefined")), + ("spraySpin", json!("userDefined")), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ] { + d.fields.insert(k.into(), v); + } + super::super::confirm(&mut app).unwrap(); + let o = app.session.tool_options_of("symbolScreener"); + assert_eq!((o["method"].as_str(), o["usePressure"].as_bool(), o["showBrush"].as_bool()), (Some("random"), Some(true), Some(false))); + assert_eq!( + (o["sprayStain"].as_str(), o["spraySpin"].as_str(), o["sprayScrunch"].as_str()), + (Some("userDefined"), Some("userDefined"), Some("average")) + ); + assert_eq!((o["proportional"].as_bool(), o["affectsDensity"].as_bool()), (Some(false), Some(true))); + app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("method"), d.bool("usePressure"), d.bool("affectsDensity")), ("random".to_string(), true, true)); + } + + /// A new Symbol Set Density spaces the instances of the selected symbol set, as one undo step; + /// the same density, or no set selected, adds none. + #[test] + fn ok_gives_a_new_density_to_the_selected_symbol_set() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let points: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = app.run("symbol.spray", json!({"name": "Dot", "points": points, "radius": 4})).unwrap()["id"].as_u64().unwrap(); + let width = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(vectorcraft_doc::NodeId(set)).and_then(|n| n.geometric_bounds()).map(|b| b.width()).unwrap() + }; + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (was, steps) = (width(&app), undo(&app)); + // The same density: the set stays as it is. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps)); + // 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)); + super::super::confirm(&mut app).unwrap(); + assert!(width(&app) < was * 0.8, "{} of {was}", width(&app)); + assert_eq!(undo(&app), steps + 1); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + // Without a set selected only the option changes. + app.run("select.set", json!({"ids": []})).unwrap(); + let (was, steps) = (width(&app), undo(&app)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(2)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(2.0)); + } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d43d17220c..0034f0f578 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -938,7 +938,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 37ffd74300..9c008cb725 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1897,7 +1897,7 @@ and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalM in `text.setRangeStyle` and `text.setFormat`, which also checks `hyphenate`, `hyphenateCapitalized` and `romanHangingPunctuation`; `effective` and `story` in `text.getRange`; `story` in `text.setRangeStyle`; `on` in `type.opticalMarginAlignment`, `type.dynamicText`, `type.systemLayout` and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in -`symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in +`symbol.spray` and `symbol.adjust`; `usePressure`, `proportional` and `affectsDensity` in `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in `swatch.delete`; `fromArtwork`, `toGlobal` and `includeTints` in `swatch.newGroup`; `global` and `selection` in `swatch.addUsedColors`; `visible` in `appearance.setItem`; `copy` in `appearance.transfer`; `reverse` and `append` in `appearance.copyFrom`; `reverse` and `stroke` in `paint.editGradient`; `stroke` in `paint.setGradientGeom` and in @@ -3098,6 +3098,36 @@ already walks Image Trace. Short agent entry points: symbol's scale are left as they are, and no undo step is added when nothing changes; an id that names no object, or objects without a symbol instance, is an error. It returns `{ids}`, the instances it changed. The menu item and the button are enabled only while a selected instance would change. +- The 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)): + `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` + `{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. + - `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 + 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. + - `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 + `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. + - 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. - 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 @@ -10067,7 +10097,11 @@ tool keeps last across tool switches (and documents) and are saved with the pref `prefs.get`'s full object), as the reference app keeps them: the Liquify tools' brush and tool options, Mirror & Cut's axis and side, Puppet Warp's mesh, the Symbolism brush, the line, grid, pencil, brush and eraser tools' options, polygon sides and star points, the Flare Tool Options and the Shape Builder Tool Options. The Liquify tools share one set of Global Brush Dimensions (width, height, angle, -intensity), and the Symbolism tools one brush. Interaction state (pins, a reference point) starts afresh. In the +intensity), and the Symbolism tools one brush: `diameter` (80), `intensity` (5), `density` (5), `usePressure` (false), +`method` (`userDefined`), `showBrush` (true), `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` +and `sprayStyle` (each `average`), `proportional` (true) and `affectsDensity` (false); these starting values are +VectorCraft's own. With `showBrush` the brush's outline follows the pointer, with a dashed ring inside it at +`intensity`/10 of its radius (no ring at 10 or with `usePressure`). Interaction state (pins, a reference point) starts afresh. In the desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). @@ -10096,7 +10130,12 @@ drag that places the rings' end point, Space held moves the flare at its current are the artboard's top-left corner in document points, while the dialog shows X and Y at the reference point the Transform panel uses, counted from the ruler origin), a graph tool's the selected graph's Graph Type (an error without one), a Symbolism tool's the Symbolism Tools Options (dialog -`symbolismOptions`: `diameter` in points, `intensity` and `density` 1–10, one brush for the eight tools) and the +`symbolismOptions`: `tool` (the tool whose options show, which the Tool row changes), `diameter` in points, +`intensity` and `density` 1–10, `usePressure`, `method` (`userDefined`, `average` or `random`), `showBrush`, the +Symbol Sprayer's `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` and `sprayStyle` (each +`average` or `userDefined`) and the Symbol Sizer's `proportional` and `affectsDensity`: one brush for the eight +tools. OK runs `tool.setOption {tool, values}`, and with symbol sets selected and a new `density` it first runs +`symbol.setDensity` from the density the dialog opened with) and the Magic Wand tool's its panel. `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard) opens Artboard Options for a new artboard, with `new: true` and the name, position and size that `artboard.new {}` would give it. OK runs `artboard.new` with the fields and makes the new artboard the active one, and Cancel adds no artboard. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9ba8866a8c..64f4fa4054 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -972,6 +972,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`. - **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`. - **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 d601ec31ca6595f141fba9a9232fd17369def357 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:19:55 -0800 Subject: [PATCH 02/11] 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 03/11] 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 04/11] 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 05/11] 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 06/11] 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 07/11] 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 08/11] 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 09/11] 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 10/11] 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 11/11] 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));