This commit is contained in:
bflatastic committed 2026-11-18 08:19:25 +07:00
commit dc4407f110
22 files changed
+2556 -96

No files matched your search

+62
View File
@@ -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<NodeId, serde_json::Value> {
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<NodeId, serde_json::Value>) {
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);
}
+37
View File
@@ -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, &copy, &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, &copy, &[(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();
+4
View File
@@ -893,6 +893,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;
/// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every
/// frame without running the command).
pub use brushsym::current_symbol;
+16 -2
View File
@@ -27,11 +27,15 @@ 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;
/// The Symbols panel's current symbol, as `symbol.list` answers it.
pub use symbols::current_symbol;
mod brushes;
mod dynamic;
mod symbolism;
mod symbols;
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
@@ -41,6 +45,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,
@@ -348,16 +353,25 @@ pub fn specs() -> Vec<CommandSpec> {
"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, 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
),
+370
View File
@@ -0,0 +1,370 @@
//! 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<Method> {
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<SprayModes> {
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, 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<f64> {
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::<u64>().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<Look> {
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<Paint>,
/// 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<f64>,
}
/// 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<f64> {
let cell = cell.max(1e-6);
let mut cells: HashMap<(i64, i64), Vec<usize>> = 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<f64>) -> Option<Mean> {
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::<f64>() / 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::<f64>() / 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<Look>,
cells: HashMap<(i64, i64), Vec<usize>>,
}
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<usize>>, at: Point, cell: f64) -> impl Iterator<Item = usize> + '_ {
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<Look>, cell: f64) -> Self {
let cell = cell.max(1.0);
let mut cells: HashMap<(i64, i64), Vec<usize>> = 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<Mean> {
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<Value> {
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<NodeId> = 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<NodeId> = 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<NodeId> = 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<Look> = (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<f64> = (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]);
}
}
+308 -40
View File
@@ -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,
@@ -877,16 +878,43 @@ pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result<Valu
// ---------- symbolism tools ----------
fn points(p: &Value, cmd: &str) -> Result<Vec<Point>> {
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<Vec<(Point, f64)>> {
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
let v: Vec<Point> = 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 {
// 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()) {
return Err(bad(cmd, "points must be finite [x,y] pairs"));
}
Ok(v)
}
/// 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<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).
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;
@@ -897,7 +925,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")
}
@@ -910,6 +939,13 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
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.
@@ -937,25 +973,63 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
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<Point> = 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<Mean>, Option<Vec2>)> = 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.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.
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) => {
@@ -972,13 +1046,18 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
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<Point> {
pub(super) fn instance_center(n: &Node) -> Option<Point> {
match &n.kind {
NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO),
_ => None,
@@ -992,10 +1071,16 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
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)?;
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.
crate::cmd::edit::refuse_symbol_part(s)?;
let st = s.doc()?;
@@ -1003,10 +1088,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
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<NodeId> = {
let d = &st.doc;
let mut v = vec![];
@@ -1036,62 +1118,248 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
"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 };
// 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<NodeId> = 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, |before, 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::<Vec<_>>(), *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 };
// 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" => {
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. 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);
}
}
"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);
// 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) => (w * share / 2.0) as f32,
("style", _) => w as f32,
_ => (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.0, 1.0),
None if alt => (n.opacity + step).min(1.0),
None => (n.opacity - step).max(0.05),
};
}
}
}
}
Ok(touched.len())
// 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 }))
}
/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount)
/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's
/// other appearance items stay as they are. A paint with no form between it and `to` (a solid
/// 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 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;
}
let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false };
f.paint = paint;
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<NodeId>, back: bool) -> Result<usize> {
let mut parents: Vec<Option<NodeId>> = 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<Node>| 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)
}
+3
View File
@@ -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<vectorcraft_doc::Guide>,
/// 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<NodeId, Value>,
}
/// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level
@@ -1082,6 +1082,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()
}
+2
View File
@@ -1458,6 +1458,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 {
@@ -614,6 +614,7 @@ pub(super) const ALLOWED: &[&str] = &[
"symbol.replace",
"symbol.selectInstances",
"symbol.setCurrent",
"symbol.setDensity",
"symbol.sortByName",
"symbol.spray",
"symbol.unused",
+2
View File
@@ -197,6 +197,8 @@ mod swatchlib;
mod symbol_nine_slice;
mod symbolbounds;
mod symboledit;
mod symbolism_options;
mod symbolism_shift;
mod symbollib;
mod tangent_line;
mod targeting;
@@ -0,0 +1,696 @@
//! 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<NodeId> {
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);
}
/// 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() {
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::<f64>() / 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));
}
/// `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]
fn pen_pressure_is_the_intensity_with_use_pressure() {
let width = |points: Value, use_pressure: Option<bool>, 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\"",
);
// 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]]});
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<bool>| {
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<bool>, 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<Value> = (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<f64> = members(&s, set).iter().map(|id| angle(&s, *id)).collect();
let stroke: Vec<Value> = (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<Value> = (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::<Vec<_>>();
let middle = |c: &[Point]| Point::new(c.iter().map(|p| p.x).sum::<f64>() / 8.0, c.iter().map(|p| p.y).sum::<f64>() / 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<Value> = (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::<Vec<_>>();
let was = xs(&s);
let middle = was.iter().sum::<f64>() / 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 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<Value> = (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::<Vec<_>>();
let was = xs(&s);
let middle = was.iter().sum::<f64>() / 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() {
let mut s = session();
let row: Vec<Value> = (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<Point> = 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);
}
/// 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}");
}
+261
View File
@@ -0,0 +1,261 @@
//! 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<NodeId> {
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<NodeId>) {
let pts: Vec<Value> = (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<Point> = 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::<Vec<_>>(), 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}");
// 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}))
};
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:?}");
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);
}
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 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]
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() {
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);
}
}
+1
View File
@@ -1372,6 +1372,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)?;
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
+1 -1
View File
@@ -984,7 +984,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, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), 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, v Line truncated
"{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, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), 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 Line truncated
),
(
"ui.colorGuideOptions",
+23 -1
View File
@@ -23,7 +23,29 @@ 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",
],
),
// 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"]),
+373 -15
View File
@@ -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<Box<dyn Tool>> {
@@ -23,14 +25,37 @@ pub fn create(id: &str) -> Option<Box<dyn Tool>> {
})
}
/// 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 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"),
("spraySize", "size"),
("spraySpin", "spin"),
("sprayScreen", "screen"),
("sprayStain", "stain"),
("sprayStyle", "style"),
];
pub struct SymbolismTool {
id: &'static str,
points: Vec<Point>,
/// 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,
hover: Option<Point>,
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.
@@ -41,6 +66,55 @@ pub struct SymbolismTool {
pub symbol: Option<String>,
/// Graphic style for the Styler (None = the document's first non-default style).
pub style: Option<String>,
/// 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)
}
/// 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<String, Value>) -> 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 {
@@ -62,11 +136,18 @@ impl SymbolismTool {
active: false,
hover: None,
alt: false,
shift: false,
diameter: 80.0,
intensity: 5.0,
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 +167,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::<Vec<_>>());
let attributes: serde_json::Map<String, Value> =
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 +208,20 @@ 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);
}
if self.shift && matches!(tool, "shift" | "size" | "stain" | "style") {
v["shift"] = json!(true);
}
("symbol.adjust".into(), v)
}
}
@@ -140,12 +249,14 @@ impl Tool for SymbolismTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
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;
self.shift = ev.mods.shift;
let (c, v) = self.command(cx);
vec![Action::Begin(self.label().into()), Action::Preview(c, v)]
}
@@ -153,11 +264,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(p);
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();
@@ -193,9 +320,15 @@ impl Tool for SymbolismTool {
vec![]
}
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
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 +343,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 +367,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]);
}
}
}
}
}
@@ -379,6 +536,207 @@ 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}");
}
/// 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]
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]
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::<Vec<_>>()
};
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();
+308 -24
View File
@@ -1,12 +1,18 @@
//! 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 super::{DialogResult, DialogSpec, form, modal, run_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
@@ -14,56 +20,191 @@ 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<String, Value> = 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<String, Value> = 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 })
}
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
let unit = app.session.general_unit();
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));
}
});
}
// 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
}
/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges).
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).
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);
});
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"));
}
/// The selected symbol sets that can be edited (a locked or hidden one keeps its density).
fn selected_sets(app: &VectorcraftApp) -> Vec<u64> {
let Some(st) = app.session.active() else { return vec![] };
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
/// a new Symbol Set Density to the selected symbol sets.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
let values: Map<String, Value> = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values }))
// 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<String, Value> = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect();
values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))));
values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k)))));
// A tool or a value `tool.setOption` refuses changes no density either.
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": tool, "values": values }))
}
#[cfg(test)]
mod tests {
use super::*;
use egui_kittest::kittest::Queryable;
use vectorcraft_engine::Session;
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()))
}
/// 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 = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
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 +219,147 @@ 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<Value> = (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));
// 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));
// 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)),
("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));
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 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));
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));
}
}
+1 -1
View File
@@ -985,7 +985,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, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), 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, v Line truncated
"{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, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), 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 Line truncated
),
(
"ui.colorGuideOptions",
+20 -9
View File
@@ -2,13 +2,14 @@
//! (Small and Large List View), shown on a square or on type; a style with no fill and no stroke
//! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the
//! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from
//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one;
//! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it
//! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a
//! copy of it and of the styles highlighted with it at the end of the list; 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, applies it to the art it is
//! dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a copy of it and of
//! the styles highlighted with it at the end of the list; 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;
@@ -513,6 +514,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.
@@ -1460,15 +1465,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);
+64 -3
View File
@@ -2166,7 +2166,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
@@ -3494,6 +3494,58 @@ 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). 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`
`{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 (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.
- 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. 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?}`
names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the
@@ -11595,7 +11647,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).
@@ -11636,7 +11692,12 @@ options' counts and growth, without a `ringSeed`. The Artboard tool's are the ac
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 (dialog `graphType`, described below; 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.
+2
View File
@@ -1104,6 +1104,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`.
- **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged).
- **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`.
- **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`.
- **Symbolism tools 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`).