VectorCraft: An open-source, vector art tool written by scratch in pure Rust
M3.82: freeform point and line commands, Gradient tool and Gradient panel freeform section
bflatasticed308d61f7de
diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rsindex 966324965..7c99e8240 100644--- a/crates/engine/src/cmd/freeform.rs+++ b/crates/engine/src/cmd/freeform.rs@@ -1,13 +1,116 @@-//! Freeform gradients: parsing their points (the `freeform` param of a gradient paint) and the-//! shape test their first points are placed with.+//! Freeform gradients: the points and lines of the freeform gradient behind the active proxy (the+//! Gradient panel's freeform section, the Color panel and the Gradient tool edit them through+//! these). Points are given in document coordinates; type runs keep them in text space.-use serde_json::Value;-use vectorcraft_color::{Freeform, FreeformMode, FreeformPoint};-use vectorcraft_doc::Node;-use vectorcraft_geom::Affine;+use serde_json::{Value, json};+use vectorcraft_color::freeform::spread_scale;+use vectorcraft_color::{Freeform, FreeformMode, FreeformPoint, GradientKind, Paint};+use vectorcraft_doc::{Node, NodeKind};+use vectorcraft_geom::{Affine, Rect};+use super::appearance::{edit_items, edits_stroke, index_param, item_target};+use super::gradient::{StopOwner, item_paint_bounds, run_paint_mut};use super::*;+pub fn specs() -> Vec<CommandSpec> {+ vec![+ cmd!(+ "paint.freeform.addPoint",+ "Add Freeform Point",+ [],+ None,+ "{at: [x,y] (document coordinates), color? (default: the gradient's colour there), opacity? 0..1 (or 0..100), spread? 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind)} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}",+ has_doc,+ add_point+ ),+ cmd!(+ "paint.freeform.setPoint",+ "Edit Freeform Point",+ [],+ None,+ "{index? (default: the selected point), at?: [x,y] (document coordinates), color?, opacity? 0..1 (or 0..100), spread? 0..1 (or 0..100 %), ids?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind)} move or recolour a point of the freeform gradient → {index}",+ has_doc,+ set_point+ ),+ cmd!(+ "paint.freeform.deletePoint",+ "Delete Freeform Point",+ [],+ None,+ "{index? (default: the selected point), ids?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind)} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",+ has_doc,+ delete_point+ ),+ cmd!(+ "paint.freeform.addLine",+ "Add Freeform Line",+ [],+ None,+ "{points: [index, …] (at least two), ids?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind)} join points with a smooth line through them, in order → {line}",+ has_doc,+ add_line+ ),+ cmd!(+ "paint.freeform.splitLine",+ "Split Freeform Line",+ [],+ None,+ "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind)} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",+ has_doc,+ split_line+ ),+ cmd!(+ "paint.freeform.selectPoint",+ "Select Freeform Point",+ [],+ None,+ "{index: point index | null to clear} select a point of the freeform gradient behind the active proxy (the first selected object's): the point the Gradient tool, the Gradient and Color panels and Delete act on → {index}",+ has_doc,+ select_point+ ),+ cmd!(+ query "paint.freeform.get",+ "Freeform Gradient",+ [],+ None,+ "{stroke?: bool (default: the active proxy)} the freeform gradient behind the proxy of the first selected object → {mode: points|lines, points: [{at: [x,y] (document coordinates), color, opacity, spread}], lines: [[index, …]], selected: index|null}",+ has_doc,+ get+ ),+ ]+}++const NOT_FREEFORM: &str = "the paint is not a freeform gradient (apply one with paint.editGradient {kind: \"freeform\"})";++impl Session {+ /// The selected freeform point (`paint.freeform.selectPoint`), while the gradient it was+ /// selected on is still the one behind the active proxy. Callers check it against the point+ /// count (an undo can remove points).+ pub fn selected_freeform_point(&self) -> Option<usize> {+ self.freeform_point.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i)+ }++ /// The freeform gradient behind the Fill (`stroke` false) or Stroke proxy, its points in+ /// document coordinates, and the length its spreads are fractions of there (see+ /// [`Node::proxy_freeform`]).+ pub fn proxy_freeform(&self, stroke: bool) -> Option<(Freeform, f64)> {+ let (n, item) = self.proxy_source(stroke)?;+ n.proxy_freeform(stroke, item)+ }++ fn select_freeform_point(&mut self, i: Option<usize>) {+ self.freeform_point = i.map(|i| (i, StopOwner::of(self)));+ }+}++/// Where an edited paint lives: the map from the document to its space and the length its spreads+/// are fractions of.+#[derive(Clone, Copy)]+struct Space {+ to_paint: Affine,+ scale: f64,+}+/// The `opacity` / `spread` convention: 0..1, or a percentage above 1.fn fraction(v: &Value, key: &str) -> std::result::Result<f32, String> {let x = v.as_f64().ok_or_else(|| format!("`{key}` must be a number"))?;@@ -59,6 +162,168 @@ pub(crate) fn parse_mode(m: &str) -> std::result::Result<FreeformMode, String> {FreeformMode::parse(m).ok_or_else(|| format!("unknown freeform mode `{m}` (points, lines)"))}+/// Run `f` on the freeform gradient behind the proxy of each target (the selection, or `ids`),+/// as one undo step; returns what it returned for the first. An unplaced gradient gets the+/// automatic points it shows first, and the stops follow the points' colours.+fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freeform, Space) -> std::result::Result<R, String>) -> Result<R> {+ let item = item_target(s, p, cmd)?;+ let stroke = edits_stroke(s, p, item, !s.fill_active)?;+ let item = item.of_kind(s, !stroke);+ let ids = item.targets(s, p)?;+ if ids.is_empty() {+ return Err(bad(cmd, "select an object with a freeform gradient"));+ }+ let mut first = None;+ let mut apply = |paint: &mut Paint, b: Rect, to_doc: Affine| -> Result<()> {+ let Paint::Gradient(g) = paint else { return Err(bad(cmd, NOT_FREEFORM)) };+ if g.gradient.kind != GradientKind::Freeform {+ return Err(bad(cmd, NOT_FREEFORM));+ }+ let to_paint = if to_doc == Affine::IDENTITY { to_doc } else { to_doc.inverse() };+ let mut ff = g.freeform_on(b).into_owned();+ let r = f(&mut ff, Space { to_paint, scale: spread_scale(b) }).map_err(|e| bad(cmd, e))?;+ g.set_freeform(ff);+ g.swatch = None;+ first.get_or_insert(r);+ Ok(())+ };+ edit_items(s, &ids, item, cmd, "Gradient", !stroke, |n, index| {+ if index.is_none()+ && let NodeKind::Text(t) = &mut n.kind+ {+ let (xf, lb) = (t.xf, t.local_bounds());+ if xf.determinant().abs() < 1e-12 {+ return Err(bad(cmd, "the type object is flattened to nothing"));+ }+ for r in &mut t.runs {+ let (paint, b) = run_paint_mut(r, stroke, lb);+ apply(paint, b, xf)?;+ }+ return Ok(());+ }+ let b = item_paint_bounds(n, index, !stroke).ok_or_else(|| bad(cmd, NOT_FREEFORM))?;+ let paint =+ if stroke { n.appearance.stroke_at_mut(index).map(|l| &mut l.paint) } else { n.appearance.fill_at_mut(index).map(|l| &mut l.paint) };+ apply(paint.ok_or_else(|| bad(cmd, NOT_FREEFORM))?, b, Affine::IDENTITY)+ })?;+ let r = first.ok_or_else(|| bad(cmd, NOT_FREEFORM))?;+ // The edited gradient is the last one used (`paint.lastGradient`).+ let shown = s.doc()?.doc.node(ids[0]).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()));+ if let Some(p) = shown {+ s.remember_paint(&p);+ }+ Ok(r)+}++/// The `index` param, else the selected point.+fn point_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {+ match p.get("index") {+ Some(v) => v.as_u64().map(|i| i as usize).ok_or_else(|| bad(cmd, "`index` must be a point index")),+ None => s.selected_freeform_point().ok_or_else(|| bad(cmd, "no point selected (give `index`)")),+ }+}++fn check_index(f: &Freeform, i: usize) -> std::result::Result<(), String> {+ if i < f.points.len() { Ok(()) } else { Err(format!("no point {i} (the gradient has {})", f.points.len())) }+}++fn add_point(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.addPoint";+ let at = point_param(p, "at").ok_or_else(|| bad(C, "missing `at` [x, y]"))?;+ let join = match p.get("line") {+ None | Some(Value::Bool(false)) => None,+ Some(Value::Bool(true)) => s.selected_freeform_point(),+ Some(_) => return Err(bad(C, "`line` must be true or false")),+ };+ let index = edit(s, p, C, |f, sp| {+ let q = sp.to_paint * at;+ let (color, opacity) = f.sample(q, sp.scale);+ let mut pt = FreeformPoint { opacity, ..FreeformPoint::new(q, color) };+ point_fields(p, &mut pt, sp.to_paint)?;+ let i = f.add_point(pt);+ if let Some(from) = join {+ f.connect(from, i);+ }+ Ok(i)+ })?;+ s.select_freeform_point(Some(index));+ Ok(json!({ "index": index }))+}++fn set_point(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.setPoint";+ let i = point_index(s, p, C)?;+ edit(s, p, C, |f, sp| {+ check_index(f, i)?;+ point_fields(p, &mut f.points[i], sp.to_paint)+ })?;+ Ok(json!({ "index": i }))+}++fn delete_point(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.deletePoint";+ let i = point_index(s, p, C)?;+ edit(s, p, C, |f, _| {+ check_index(f, i)?;+ if f.remove_point(i) { Ok(()) } else { Err("a freeform gradient keeps at least one point".into()) }+ })?;+ // The points after it moved down one.+ let sel = s.selected_freeform_point().and_then(|j| match j.cmp(&i) {+ std::cmp::Ordering::Less => Some(j),+ std::cmp::Ordering::Equal => None,+ std::cmp::Ordering::Greater => Some(j - 1),+ });+ s.select_freeform_point(sel);+ Ok(json!({ "index": i }))+}++fn add_line(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.addLine";+ let points: Vec<usize> = p+ .get("points")+ .and_then(Value::as_array)+ .and_then(|a| a.iter().map(|v| v.as_u64().map(|i| i as usize)).collect())+ .ok_or_else(|| bad(C, "`points` must be an array of point indices"))?;+ let line = edit(s, p, C, |f, _| f.add_line(points.clone()))?;+ Ok(json!({ "line": line }))+}++fn split_line(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.splitLine";+ let line = index_param(p, "line", C)?;+ let segment = index_param(p, "segment", C)?;+ let t = f64_or(p, "t", 0.5);+ let index = edit(s, p, C, |f, _| f.split_line(line, segment, t).ok_or_else(|| format!("no segment {segment} on line {line}")))?;+ s.select_freeform_point(Some(index));+ Ok(json!({ "index": index }))+}++fn select_point(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.selectPoint";+ let index = match p.get("index") {+ None => return Err(bad(C, "missing `index` (a point index, or null to clear)")),+ Some(Value::Null) => None,+ Some(v) => {+ let i = v.as_u64().ok_or_else(|| bad(C, "`index` must be a whole number or null"))? as usize;+ let (f, _) = s.proxy_freeform(!s.fill_active).ok_or_else(|| bad(C, NOT_FREEFORM))?;+ check_index(&f, i).map_err(|e| bad(C, e))?;+ Some(i)+ }+ };+ s.select_freeform_point(index);+ Ok(json!({ "index": index }))+}++fn get(s: &mut Session, p: &Value) -> Result<Value> {+ const C: &str = "paint.freeform.get";+ let stroke = bool_or(p, "stroke", !s.fill_active);+ let (f, _) = s.proxy_freeform(stroke).ok_or_else(|| bad(C, NOT_FREEFORM))?;+ let selected = if stroke != s.fill_active { s.selected_freeform_point().filter(|i| *i < f.points.len()) } else { None };+ let mut v = vectorcraft_tools::params::freeform_json(&f);+ v["selected"] = json!(selected);+ Ok(v)+}+/// Whether `n`'s shape contains `p` (its filled regions; true for objects without them, such as/// type, whose boxes stand in).pub(crate) fn inside_fn(n: &Node) -> impl Fn(vectorcraft_geom::Point) -> bool + use<> {diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rsindex 4bfa98a41..b42474ef9 100644--- a/crates/engine/src/cmd/gradient.rs+++ b/crates/engine/src/cmd/gradient.rs@@ -82,7 +82,7 @@ pub(crate) struct StopOwner {}impl StopOwner {- fn of(s: &Session) -> Self {+ pub(crate) fn of(s: &Session) -> Self {Self { doc: s.active, object: s.active().and_then(|d| d.selection.objects.first().copied()), fill: s.fill_active, item: s.appearance_item() }}}diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 8c1d4faf8..f997e181e 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -197,6 +197,7 @@ pub fn command_specs() -> &'static [CommandSpec] {v.extend(paint::proxy_specs());v.extend(overprint::specs());v.extend(swatchlib::specs());+ v.extend(freeform::specs());v})}diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rsindex 3763c20f2..85268d36c 100644--- a/crates/engine/src/cmd/paint.rs+++ b/crates/engine/src/cmd/paint.rs@@ -1,7 +1,7 @@//! Fill and stroke paint (the toolbar proxies and their defaults) and the Transparency panel.use serde_json::{Value, json};-use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};+use vectorcraft_color::{BlendMode, Color, Paint};use vectorcraft_doc::{Appearance, CharStyle, Node, NodeId, NodeKind};use super::appearance::{ItemTarget, appearance_targets, edit_items, item_target};@@ -102,7 +102,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {"{stroke?: bool (default: the active proxy), ids?} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default",has_doc,|s, p| {- let paint = Paint::Gradient(Box::new(GradientPaint { geom: None, ..s.last_gradient.clone() }));+ let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));apply_to_proxy(s, p, paint)}),@@ -153,18 +153,26 @@ impl Session {/// object's (a group's first painted object's; type: its first run's), else the defaults for/// new art.pub fn proxy_paints(&self) -> (Paint, Paint) {- let default = |stroke: bool| if stroke { self.paint.stroke.clone() } else { self.paint.fill.clone() };- let Some(first) = self.active().and_then(|st| st.selection.objects.first().and_then(|id| st.doc.node(*id))) else {- return (default(false), default(true));+ let show = |stroke: bool| match self.proxy_source(stroke) {+ Some((n, item)) => proxy_paint(n, stroke, item),+ None if stroke => self.paint.stroke.clone(),+ None => self.paint.fill.clone(),};+ (show(false), show(true))+ }++ /// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item+ /// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art.+ pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(&Node, Option<usize>)> {+ let st = self.active()?;+ let first = st.doc.node(*st.selection.objects.first()?)?;let item = self.appearance_item();+ if first.appearance.item_of_kind(item, !stroke).is_some() {+ return Some((first, item));+ }let mut nodes = vec![];painted(first, true, &mut nodes);- let show = |stroke: bool| match first.appearance.item_of_kind(item, !stroke) {- Some(_) => proxy_paint(first, stroke, item),- None => nodes.first().map_or_else(|| default(stroke), |n| proxy_paint(n, stroke, None)),- };- (show(false), show(true))+ nodes.first().map(|n| (*n, None))}pub(crate) fn remember_paint_now(&mut self, p: &Paint) {diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 1a497b77f..fd59c012b 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -464,6 +464,9 @@ pub struct Session {pub eyedropper: EyedropperOptions,/// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved.pub swatch_libraries: cmd::swatchlib::Libraries,+ /// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it+ /// was selected on: read it with [`Session::selected_freeform_point`].+ pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>,}impl Default for Session {@@ -497,6 +500,7 @@ impl Session {pending_paint: None,eyedropper: Default::default(),swatch_libraries: Default::default(),+ freeform_point: None,}}diff --git a/crates/engine/src/tests_freeform.rs b/crates/engine/src/tests_freeform.rsindex d331b39b1..cc01aada3 100644--- a/crates/engine/src/tests_freeform.rs+++ b/crates/engine/src/tests_freeform.rs@@ -1,7 +1,8 @@-//! Freeform gradients through commands: the first application, transforms and warps (M3.81).+//! Freeform gradients through commands: the first application (M3.81), transforms and warps, and+//! the point and line commands (M3.82).use serde_json::{Value, json};-use vectorcraft_color::{Freeform, GradientKind, GradientPaint, Paint};+use vectorcraft_color::{Color, Freeform, GradientKind, GradientPaint, Paint};use vectorcraft_geom::Point;use super::*;@@ -99,8 +100,7 @@ fn transforms_and_warps_move_the_points() {}// A perspective distort maps each point exactly: a point on a corner stays on it.let (mut s, id) = freeform_rect();- let corner = json!({"kind": "freeform", "freeform": {"points": [{"at": [200, 200], "color": "#ff0000"}]}});- run(&mut s, "paint.setFill", json!({ "gradient": corner }));+ run(&mut s, "paint.freeform.addPoint", json!({"at": [200, 200]}));run(&mut s, "object.distort", json!({"corners": [[100, 100], [200, 100], [260, 240], [100, 200]]}));let f = points(&s, id);assert!(close(f.points.last().unwrap().at, Point::new(260.0, 240.0)), "{:?}", f.points.last());@@ -110,10 +110,7 @@ fn transforms_and_warps_move_the_points() {fn freeform_paints_survive_saving_and_old_files_load() {let (mut s, id) = freeform_rect();run(&mut s, "paint.editGradient", json!({"mode": "lines"}));- let mut g = fill_gradient(&s, id);- g.freeform.as_mut().unwrap().add_line(vec![0, 1, 2]).unwrap();- run(&mut s, "paint.setFill", json!({"gradient": vectorcraft_tools::params::gradient_params(&g)}));- assert_eq!(points(&s, id).lines, vec![vec![0, 1, 2]]);+ run(&mut s, "paint.freeform.addLine", json!({"points": [0, 1, 2]}));vectorcraft_testkit::invariants::check_native_roundtrip_exact(&s.doc().unwrap().doc).unwrap();// A gradient saved before freeform points existed has none.let old: GradientPaint = serde_json::from_value(json!({"gradient": {"kind": "Freeform", "stops": []}, "angle": 0.0})).unwrap();@@ -124,3 +121,120 @@ fn freeform_paints_survive_saving_and_old_files_load() {run(&mut s, "paint.setFill", json!({"gradient": vectorcraft_tools::params::gradient_params(&g), "ids": [other.0]}));assert_eq!(fill_gradient(&s, other), g);}++#[test]+fn reapplied_gradients_place_their_points_afresh() {+ let (mut s, id) = freeform_rect();+ run(&mut s, "paint.freeform.setPoint", json!({"index": 0, "color": "#ff0000"}));+ // The last gradient (`.`) on other art: points inside it, coloured like the first object's.+ let other = shape(&mut s, "shape.rectangle", 400.0, 300.0, 100.0, 100.0);+ run(&mut s, "paint.lastGradient", json!({}));+ let (a, (b, _)) = (points(&s, id), node(&s, other).proxy_freeform(false, None).unwrap());+ assert!(b.points.iter().all(|p| p.at.x >= 400.0 && p.at.y >= 300.0), "{:?}", b.points);+ assert_eq!(a.points.iter().map(|p| p.color.to_hex()).collect::<Vec<_>>(), b.points.iter().map(|p| p.color.to_hex()).collect::<Vec<_>>());+}++// ---------- M3.82: points and lines ----------++#[test]+fn add_set_and_delete_points() {+ let (mut s, id) = freeform_rect();+ let n = points(&s, id).points.len();+ let field = points(&s, id);+ let r = run(&mut s, "paint.freeform.addPoint", json!({"at": [150, 150]}));+ assert_eq!(r["index"], json!(n));+ assert_eq!(s.selected_freeform_point(), Some(n), "the new point is selected");+ let p = points(&s, id).points[n];+ // Without a colour it takes the gradient's colour there.+ let (want, _) = field.sample(Point::new(150.0, 150.0), 50.0);+ assert!(close(p.at, Point::new(150.0, 150.0)) && p.color.to_hex() == want.to_hex(), "{p:?} vs {want:?}");+ // The selected point takes edits without an index; opacity and spread take 0..1 or percentages.+ run(&mut s, "paint.freeform.setPoint", json!({"color": "#00ff00", "opacity": 50, "spread": 0.4, "at": [160, 170]}));+ let p = points(&s, id).points[n];+ assert_eq!((p.color.to_hex().as_str(), p.opacity, p.spread, p.at), ("#00ff00", 0.5, 0.4, Point::new(160.0, 170.0)));+ assert_eq!(fill_gradient(&s, id).gradient.stops[n].color.to_hex(), "#00ff00", "the stops follow");+ // One undo step per command.+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(points(&s, id).points[n].color.to_hex(), want.to_hex());+ run(&mut s, "edit.redo", json!({}));+ run(&mut s, "paint.freeform.deletePoint", json!({}));+ assert_eq!(points(&s, id).points.len(), n);+ assert_eq!(s.selected_freeform_point(), None);+ for i in (1..n).rev() {+ run(&mut s, "paint.freeform.deletePoint", json!({"index": i}));+ }+ let e = s.execute("paint.freeform.deletePoint", &json!({"index": 0})).unwrap_err().to_string();+ assert!(e.contains("at least one"), "{e}");+ let e = s.execute("paint.freeform.setPoint", &json!({"index": 5, "color": "#000000"})).unwrap_err().to_string();+ assert!(e.contains("no point 5"), "{e}");+}++#[test]+fn lines_join_split_and_follow_the_selection() {+ let (mut s, id) = freeform_rect();+ assert_eq!(run(&mut s, "paint.freeform.addLine", json!({"points": [0, 1]}))["line"], json!(0));+ run(&mut s, "paint.freeform.selectPoint", json!({"index": 1}));+ // Adding a point with `line` extends the line ending at the selected point.+ let i = run(&mut s, "paint.freeform.addPoint", json!({"at": [190, 190], "line": true}))["index"].as_u64().unwrap() as usize;+ assert_eq!(points(&s, id).lines, vec![vec![0, 1, i]]);+ let j = run(&mut s, "paint.freeform.splitLine", json!({"line": 0, "segment": 1}))["index"].as_u64().unwrap() as usize;+ assert_eq!((points(&s, id).lines[0].clone(), s.selected_freeform_point()), (vec![0, 1, j, i], Some(j)));+ assert!(s.execute("paint.freeform.splitLine", &json!({"line": 0, "segment": 3})).is_err());+ assert!(s.execute("paint.freeform.addLine", &json!({"points": [0, 99]})).is_err());+ // The query reports points in document coordinates, the lines and the selection.+ let g = run(&mut s, "paint.freeform.get", json!({}));+ assert_eq!((g["lines"].clone(), g["selected"].clone(), g["mode"].clone()), (json!([[0, 1, j, i]]), json!(j), json!("points")));+ assert_eq!(g["points"][i]["at"], json!([190.0, 190.0]));+}++#[test]+fn point_commands_need_a_freeform_gradient() {+ let mut s = session();+ shape(&mut s, "shape.rectangle", 0.0, 0.0, 50.0, 50.0);+ for paint in [json!({"color": "#ff0000"}), json!({"gradient": {"kind": "radial"}})] {+ run(&mut s, "paint.setFill", paint);+ for (cmd, p) in [+ ("paint.freeform.addPoint", json!({"at": [10, 10]})),+ ("paint.freeform.setPoint", json!({"index": 0, "color": "#000000"})),+ ("paint.freeform.deletePoint", json!({"index": 0})),+ ("paint.freeform.addLine", json!({"points": [0, 1]})),+ ("paint.freeform.splitLine", json!({"line": 0, "segment": 0})),+ ("paint.freeform.selectPoint", json!({"index": 0})),+ ("paint.freeform.get", json!({})),+ ] {+ let e = s.execute(cmd, &p).unwrap_err().to_string();+ assert!(e.contains("not a freeform gradient"), "{cmd}: {e}");+ }+ }+ // Nothing selected: nothing to edit.+ run(&mut s, "select.none", json!({}));+ assert!(s.execute("paint.freeform.addPoint", &json!({"at": [1, 1]})).is_err());+}++#[test]+fn selection_follows_the_object_and_the_proxy() {+ let (mut s, id) = freeform_rect();+ run(&mut s, "paint.freeform.selectPoint", json!({"index": 2}));+ assert_eq!(s.selected_freeform_point(), Some(2));+ run(&mut s, "paint.toggleActive", json!({}));+ assert_eq!(s.selected_freeform_point(), None, "the Stroke proxy has its own paint");+ run(&mut s, "paint.toggleActive", json!({}));+ assert_eq!(s.selected_freeform_point(), Some(2));+ run(&mut s, "select.none", json!({}));+ run(&mut s, "select.set", json!({"ids": [id.0]}));+ assert_eq!(s.selected_freeform_point(), Some(2), "same object, same proxy");+ assert!(s.execute("paint.freeform.selectPoint", &json!({"index": 99})).is_err());+}++#[test]+fn type_objects_keep_points_in_text_space() {+ let mut s = session();+ let r = run(&mut s, "text.create", json!({"x": 100, "y": 200, "text": "Freeform", "size": 40}));+ let id = NodeId(r["id"].as_u64().unwrap());+ run(&mut s, "paint.editGradient", json!({"kind": "freeform"}));+ run(&mut s, "object.rotate", json!({"angle": 90, "origin": [100, 200]}));+ let i = run(&mut s, "paint.freeform.addPoint", json!({"at": [90, 150], "color": "#ff00ff"}))["index"].as_u64().unwrap() as usize;+ let (f, _) = node(&s, id).proxy_freeform(false, None).unwrap();+ assert!(close(f.points[i].at, Point::new(90.0, 150.0)), "back in document coordinates: {:?}", f.points[i].at);+ assert_eq!(f.points[i].color, Color::rgb(1.0, 0.0, 1.0));+}diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rsindex 54129edc9..7bf354164 100644--- a/crates/engine/src/tooling.rs+++ b/crates/engine/src/tooling.rs@@ -82,6 +82,7 @@ impl Session {gradient_stop: self.selected_stop(),appearance_item: self.appearance_item(),constrain_angle: self.prefs.constrain_angle,+ freeform_point: self.selected_freeform_point(),};f(self.tool.as_mut(), &cx)}diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rsindex b26b9289e..ebfa48082 100644--- a/crates/tools/src/lib.rs+++ b/crates/tools/src/lib.rs@@ -165,6 +165,9 @@ pub struct ToolContext<'a> {pub appearance_item: Option<usize>,/// General → Constrain Angle (degrees): Shift constrains drags to 45° steps from it.pub constrain_angle: f64,+ /// The selected freeform gradient point (`paint.freeform.selectPoint`), marked on the+ /// freeform annotator.+ pub freeform_point: Option<usize>,}impl ToolContext<'_> {@@ -349,6 +352,7 @@ pub(crate) mod testutil {gradient_stop: None,appearance_item: None,constrain_angle: 0.0,+ freeform_point: None,}}}diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rsindex b978116e3..6c52ae151 100644--- a/crates/tools/src/xform.rs+++ b/crates/tools/src/xform.rs@@ -7,6 +7,7 @@mod artboard;mod eyedropper;mod free;+mod freeform;mod gradient;mod measure;mod transform;diff --git a/crates/tools/src/xform/freeform.rs b/crates/tools/src/xform/freeform.rsnew file mode 100644index 000000000..5ecff9d37--- /dev/null+++ b/crates/tools/src/xform/freeform.rs@@ -0,0 +1,264 @@+//! The Gradient tool on a freeform gradient.+//!+//! The annotator shows each point as a colour chip, the lines through them and, around the+//! selected point, its spread. Click a point to select it (`paint.freeform.selectPoint`; the+//! Gradient and Color panels edit the selected point) and drag it to move it. Click inside the+//! selected art to add a point there, coloured as the gradient is there; in Lines mode (the+//! Gradient panel's Draw toggle) the new point joins the selected one by a line. Click a line to add+//! a point on it. Delete or Backspace removes the selected point.++use serde_json::{Value, json};+use vectorcraft_color::freeform::LineHit;+use vectorcraft_color::{Freeform, FreeformMode};+use vectorcraft_doc::hit::hit_test;+use vectorcraft_geom::{Point, Shape};++use super::paint_owner;+use crate::{Action, Cursor, Overlay, ToolContext, ToolKey};++const LINE: [u8; 3] = [0x20, 0x20, 0x20];+/// Hit radius of a point's chip and of a line, screen pixels.+const POINT_HIT: f64 = 7.0;+const LINE_HIT: f64 = 4.0;+/// A press becomes a drag after this much movement, screen pixels.+const DRAG_START: f64 = 3.0;++/// The freeform gradient behind the active proxy of the first selected object that has one: its+/// points in document coordinates and the length spreads are fractions of there.+pub(super) struct Annotator {+ pub freeform: Freeform,+ pub scale: f64,+}++impl Annotator {+ pub fn of(cx: &ToolContext) -> Option<Self> {+ cx.selection.objects.iter().find_map(|id| {+ let (freeform, scale) = cx.doc.node(*id)?.proxy_freeform(!cx.fill_active, cx.appearance_item)?;+ Some(Self { freeform, scale })+ })+ }++ /// The point under `p` (the topmost chip where chips overlap).+ fn point_at(&self, cx: &ToolContext, p: Point) -> Option<usize> {+ (0..self.freeform.points.len()).rev().find(|i| self.freeform.points[*i].at.distance(p) <= cx.tol(POINT_HIT))+ }++ /// The spot on a line under `p`.+ fn line_at(&self, cx: &ToolContext, p: Point) -> Option<LineHit> {+ self.freeform.nearest_on_lines(p).filter(|h| h.distance <= cx.tol(LINE_HIT))+ }++ /// The selected point, if it exists.+ fn selected(&self, cx: &ToolContext) -> Option<usize> {+ cx.freeform_point.filter(|i| *i < self.freeform.points.len())+ }++ pub fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {+ let f = &self.freeform;+ let mut o: Vec<Overlay> =+ (0..f.lines.len()).map(|l| Overlay::Path { path: f.line_path(l), color: LINE, width: 1.0, dashed: false }).collect();+ if let Some(i) = self.selected(cx) {+ let pt = &f.points[i];+ let r = pt.spread as f64 * self.scale;+ if r > 0.0 {+ let path = vectorcraft_geom::kurbo::Circle::new(pt.at, r).to_path(cx.tol(0.25));+ o.push(Overlay::Path { path, color: LINE, width: 1.0, dashed: true });+ }+ }+ o.extend(f.points.iter().enumerate().map(|(i, pt)| Overlay::Swatch {+ p: pt.at,+ color: pt.color.to_rgba8(pt.opacity),+ selected: cx.freeform_point == Some(i),+ }));+ o+ }+}++/// What a press on a freeform annotator does.+#[derive(Clone, Debug, PartialEq)]+pub(super) enum Grab {+ /// A point: a drag moves it.+ Point(usize),+ /// A line: a click adds a point there.+ Line(LineHit),+ /// Inside selected art: a click adds a point there.+ Add,+ /// Elsewhere: a click leaves no point selected.+ Clear,+}++#[derive(Clone, Debug, PartialEq)]+pub(super) struct Gesture {+ grab: Grab,+ at: Point,+ began: bool,+}++impl Gesture {+ /// Has the press become a drag (an interaction is open)?+ pub fn began(&self) -> bool {+ self.began+ }+}++/// `params` aimed at the paint behind the active proxy.+fn on_proxy(cx: &ToolContext, mut params: Value) -> Value {+ params["stroke"] = json!(!cx.fill_active);+ params+}++fn select(i: Option<usize>) -> Action {+ Action::Exec("paint.freeform.selectPoint".into(), json!({ "index": i }))+}++pub(super) fn press(cx: &ToolContext, a: &Annotator, p: Point) -> (Vec<Action>, Gesture) {+ let mut out = vec![];+ let grab = if let Some(i) = a.point_at(cx, p) {+ if cx.freeform_point != Some(i) {+ out.push(select(Some(i)));+ }+ Grab::Point(i)+ } else if let Some(h) = a.line_at(cx, p) {+ Grab::Line(h)+ } else if hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| cx.selection.objects.contains(&paint_owner(cx.doc, h.leaf))) {+ Grab::Add+ } else {+ Grab::Clear+ };+ (out, Gesture { grab, at: p, began: false })+}++pub(super) fn drag(cx: &ToolContext, g: &mut Gesture, p: Point) -> Vec<Action> {+ let Grab::Point(index) = g.grab else { return vec![] };+ let mut out = vec![];+ if !g.began {+ if p.distance(g.at) < cx.tol(DRAG_START) {+ return out;+ }+ g.began = true;+ out.push(Action::Begin("Gradient".into()));+ }+ out.push(Action::Preview("paint.freeform.setPoint".into(), on_proxy(cx, json!({ "index": index, "at": [p.x, p.y] }))));+ out+}++pub(super) fn release(cx: &ToolContext, a: Option<&Annotator>, g: Gesture) -> Vec<Action> {+ if g.began {+ return vec![Action::Commit];+ }+ match g.grab {+ Grab::Point(_) => vec![],+ Grab::Line(h) => {+ vec![Action::Exec("paint.freeform.splitLine".into(), on_proxy(cx, json!({ "line": h.line, "segment": h.segment, "t": h.t })))]+ }+ Grab::Add => {+ let lines = a.is_some_and(|a| a.freeform.mode == FreeformMode::Lines);+ vec![Action::Exec("paint.freeform.addPoint".into(), on_proxy(cx, json!({ "at": [g.at.x, g.at.y], "line": lines })))]+ }+ Grab::Clear if cx.freeform_point.is_some() => vec![select(None)],+ Grab::Clear => vec![],+ }+}++/// Delete / Backspace remove the selected point (never the last one).+pub(super) fn claims_key(cx: &ToolContext, a: &Annotator, key: ToolKey) -> bool {+ matches!(key, ToolKey::Delete | ToolKey::Backspace) && a.selected(cx).is_some() && a.freeform.points.len() > 1+}++pub(super) fn key(cx: &ToolContext, a: &Annotator, key: ToolKey) -> Vec<Action> {+ if !claims_key(cx, a, key) {+ return vec![];+ }+ vec![Action::Exec("paint.freeform.deletePoint".into(), on_proxy(cx, json!({ "index": a.selected(cx) })))]+}++pub(super) fn cursor(cx: &ToolContext, a: &Annotator, g: Option<&Gesture>, p: Point) -> Cursor {+ if g.is_some_and(|g| g.began) || a.point_at(cx, p).is_some() {+ return Cursor::Move;+ }+ if a.line_at(cx, p).is_some()+ || hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| cx.selection.objects.contains(&paint_owner(cx.doc, h.leaf)))+ {+ return Cursor::AddStop;+ }+ Cursor::Crosshair+}++#[cfg(test)]+mod tests {+ use super::super::GradientTool;+ use super::*;+ use crate::testutil::*;+ use crate::{PointerEvent, PointerKind, Tool};+ use vectorcraft_color::{FreeformPoint, Gradient, GradientKind, GradientPaint, Paint};+ use vectorcraft_doc::{Document, Selection};++ /// The test rectangle (100..200) with three points; `lines` mode joins new ones.+ fn doc(mode: FreeformMode) -> (Document, Selection) {+ let (mut d, id) = doc_with_rect();+ let mut g = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Default::default() });+ let pt = |x, y| FreeformPoint { spread: 0.2, ..FreeformPoint::new(Point::new(x, y), vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)) };+ g.freeform = Some(Freeform { points: vec![pt(120.0, 120.0), pt(180.0, 120.0), pt(150.0, 180.0)], lines: vec![vec![0, 1]], mode });+ d.node_mut(id).unwrap().appearance.set_fill(Paint::Gradient(Box::new(g)));+ let mut s = Selection::default();+ s.add(id);+ (d, s)+ }++ fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent {+ PointerEvent::new(kind, x, y)+ }++ fn click(t: &mut GradientTool, cx: &ToolContext, x: f64, y: f64) -> Vec<Action> {+ let mut a = t.pointer(cx, &ev(PointerKind::Down, x, y));+ a.extend(t.pointer(cx, &ev(PointerKind::Up, x, y)));+ a+ }++ #[test]+ fn clicks_select_points_add_points_and_split_lines() {+ let (d, s) = doc(FreeformMode::Points);+ let p = paint();+ let mut cx = cx(&d, &s, &p);+ let mut t = GradientTool::default();+ assert_eq!(click(&mut t, &cx, 151.0, 181.0), vec![select(Some(2))]);+ cx.freeform_point = Some(2);+ // Inside the art: a point there (Points mode: not joined).+ let a = click(&mut t, &cx, 140.0, 150.0);+ assert_eq!(a, vec![Action::Exec("paint.freeform.addPoint".into(), json!({"at": [140.0, 150.0], "line": false, "stroke": false}))]);+ // On the line: a point on it.+ let a = click(&mut t, &cx, 150.0, 122.0);+ let Action::Exec(c, v) = &a[0] else { panic!("{a:?}") };+ assert_eq!((c.as_str(), &v["line"], &v["segment"]), ("paint.freeform.splitLine", &json!(0), &json!(0)));+ // Off the art: the point selection clears.+ assert_eq!(click(&mut t, &cx, 400.0, 400.0), vec![select(None)]);+ // The overlays: a chip per point (the selected one ringed), the line and the spread.+ let o = t.overlays(&cx);+ assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Swatch { .. })).count(), 3);+ assert!(o.iter().any(|o| matches!(o, Overlay::Swatch { selected: true, p, .. } if p == &Point::new(150.0, 180.0))));+ assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { dashed: true, .. })).count(), 1, "the spread circle");+ }++ #[test]+ fn lines_mode_joins_new_points_and_drags_move_points() {+ let (d, s) = doc(FreeformMode::Lines);+ let p = paint();+ let mut cx = cx(&d, &s, &p);+ cx.freeform_point = Some(1);+ let mut t = GradientTool::default();+ let a = click(&mut t, &cx, 190.0, 190.0);+ assert_eq!(a, vec![Action::Exec("paint.freeform.addPoint".into(), json!({"at": [190.0, 190.0], "line": true, "stroke": false}))]);+ t.pointer(&cx, &ev(PointerKind::Down, 120.0, 121.0));+ let a = t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 140.0));+ assert_eq!(a[0], Action::Begin("Gradient".into()));+ assert_eq!(a[1], Action::Preview("paint.freeform.setPoint".into(), json!({"index": 0, "at": [130.0, 140.0], "stroke": false})));+ assert_eq!(t.cursor(&cx, Point::new(130.0, 140.0), Default::default()), Cursor::Move);+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 140.0)), vec![Action::Commit]);+ // Delete removes the selected point.+ assert!(t.claims_key(&cx, ToolKey::Delete));+ assert_eq!(+ t.key(&cx, ToolKey::Delete, Default::default()),+ vec![Action::Exec("paint.freeform.deletePoint".into(), json!({"index": 1, "stroke": false}))]+ );+ }+}diff --git a/crates/tools/src/xform/gradient.rs b/crates/tools/src/xform/gradient.rsindex f854374de..b1996922d 100644--- a/crates/tools/src/xform/gradient.rs+++ b/crates/tools/src/xform/gradient.rs@@ -13,6 +13,8 @@//! diamond above the bar to move a midpoint. Double-clicking a stop opens its popover. The//! selected stop (`gradient.selectStop`) is shared with the Gradient and Color panels: Delete or//! Backspace removes it (never below two stops) and the arrow keys nudge it.+//!+//! On a freeform gradient the tool edits its points instead (see `freeform`).use serde_json::{Value, json};use vectorcraft_color::gradient::{duplicate_stop, insert_stop, midpoint_from_pos, midpoint_pos, move_stop, remove_stop, set_midpoint};@@ -21,6 +23,7 @@ use vectorcraft_doc::NodeId;use vectorcraft_doc::hit::hit_test;use vectorcraft_geom::{Affine, Point, Vec2, constrain_angle_from};+use super::freeform::{self, Annotator as FreeformAnnotator};use super::paint_owner;use crate::guides::snap_draw;use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};@@ -49,8 +52,8 @@ const DRAG_START: f64 = 3.0;const NUDGE: f32 = 0.01;const NUDGE_BIG: f32 = 0.1;-/// The gradient annotator: the gradient behind the active proxy of the first selected object that-/// has one, placed in document coordinates.+/// The gradient annotator: the linear or radial gradient behind the active proxy of the first+/// selected object that has one, placed in document coordinates.#[derive(Clone, Debug, PartialEq)]pub struct Annotator {pub geom: GradientGeom,@@ -75,7 +78,7 @@ impl Annotator {pub fn of(cx: &ToolContext) -> Option<Self> {cx.selection.objects.iter().find_map(|id| {let (g, geom) = cx.doc.node(*id)?.proxy_gradient(!cx.fill_active, cx.appearance_item)?;- Some(Self { geom, gradient: g.gradient.clone() })+ (g.gradient.kind != GradientKind::Freeform).then(|| Self { geom, gradient: g.gradient.clone() })})}/// An annotator showing `stops` on `geom` (the state a drag started from).@@ -183,6 +186,8 @@ struct Gesture {#[derive(Default)]pub struct GradientTool {gesture: Option<Gesture>,+ /// A press on a freeform gradient's annotator.+ free: Option<freeform::Gesture>,/// Smart-guide feedback of the handle being dragged.guides: Vec<Overlay>,}@@ -381,10 +386,27 @@ impl Tool for GradientTool {}fn busy(&self) -> bool {- self.gesture.as_ref().is_some_and(|g| g.began)+ self.gesture.as_ref().is_some_and(|g| g.began) || self.free.as_ref().is_some_and(freeform::Gesture::began)}fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {+ // A freeform gradient: its points instead of the bar.+ match (ev.kind, &mut self.free) {+ (PointerKind::Down, _) => {+ if let Some(a) = FreeformAnnotator::of(cx) {+ let (out, g) = freeform::press(cx, &a, ev.pos);+ self.free = Some(g);+ return out;+ }+ }+ (PointerKind::Drag, Some(g)) => return freeform::drag(cx, g, ev.pos),+ (PointerKind::Up, Some(_)) => {+ let g = self.free.take().expect("checked");+ return freeform::release(cx, FreeformAnnotator::of(cx).as_ref(), g);+ }+ (PointerKind::DoubleClick, free) if free.is_some() || FreeformAnnotator::of(cx).is_some() => return vec![],+ _ => {}+ }match ev.kind {PointerKind::Down => self.press(cx, ev.pos, ev.mods),PointerKind::Drag => self.drag(cx, ev.pos, ev.mods),@@ -400,6 +422,9 @@ impl Tool for GradientTool {}fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {+ if let Some(a) = FreeformAnnotator::of(cx) {+ return freeform::claims_key(cx, &a, key);+ }matches!(key, ToolKey::Delete | ToolKey::Backspace | ToolKey::Left | ToolKey::Right)&& cx.gradient_stop.is_some_and(|i| Annotator::of(cx).is_some_and(|a| i < a.gradient.stops.len()))}@@ -407,12 +432,16 @@ impl Tool for GradientTool {fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec<Action> {if key == ToolKey::Escape && self.busy() {self.gesture = None;+ self.free = None;self.guides.clear();return vec![Action::Cancel];}if self.busy() || !self.claims_key(cx, key) {return vec![];}+ if let Some(a) = FreeformAnnotator::of(cx) {+ return freeform::key(cx, &a, key);+ }let (Some(a), Some(i)) = (Annotator::of(cx), cx.gradient_stop) else { return vec![] };let stops = &a.gradient.stops;let (new, sel) = match key {@@ -433,6 +462,9 @@ impl Tool for GradientTool {}fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {+ if let Some(a) = FreeformAnnotator::of(cx) {+ return a.overlays(cx);+ }let mut o = match (Annotator::of(cx), self.gesture.as_ref().and_then(|g| g.vector)) {(Some(a), _) => annotator_overlays(cx, &a),// A vector drawn on a paint that isn't a gradient yet.@@ -446,6 +478,9 @@ impl Tool for GradientTool {}fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {+ if let Some(a) = FreeformAnnotator::of(cx) {+ return freeform::cursor(cx, &a, self.free.as_ref(), p);+ }if let Some(g) = &self.gesture {return match (&g.grab, g.stop) {(Grab::Stop { .. }, Some(None)) => Cursor::RemoveStop,diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rsindex d997c004e..0c2f3bb90 100644--- a/crates/ui-egui/src/panels/color.rs+++ b/crates/ui-egui/src/panels/color.rs@@ -1,6 +1,7 @@//! Color panel: Grayscale / RGB / HSB / CMYK / Web Safe RGB sliders with colour-gradient tracks,//! value fields, hex field, None/Black/White chips, spectrum ramp and the Fill/Stroke proxy.-//! When the active paint is a gradient, the sliders edit the Gradient panel's selected stop.+//! When the active paint is a gradient, the sliders edit the Gradient panel's selected stop (on a+//! freeform gradient, its selected point).//!//! The mode follows the colour's own model (the last mode picked comes back for colours in its//! model). Alt-clicking the spectrum or a chip paints the inactive proxy; Shift-clicking the@@ -9,7 +10,7 @@use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, vec2};use serde_json::json;-use vectorcraft_color::{Color, Paint};+use vectorcraft_color::{Color, GradientKind, Paint};use super::{active_paint, color_json, live_run, pstate, set_pstate};use crate::theme::Tokens;@@ -258,17 +259,19 @@ fn to32(c: &Color) -> Color32 {super::c32(c)}-/// What the panel is editing: the active proxy's solid colour, or a selected gradient stop.+/// What the panel is editing: the active proxy's solid colour, a selected gradient stop or a+/// selected freeform point.enum Target {Paint(Option<Color>),Stop { paint: Paint, index: usize, color: Color },+ Point { index: usize, color: Color },}impl Target {fn color(&self) -> Option<Color> {match self {Target::Paint(c) => *c,- Target::Stop { color, .. } => Some(*color),+ Target::Stop { color, .. } | Target::Point { color, .. } => Some(*color),}}}@@ -280,6 +283,12 @@ fn target(app: &VectorcraftApp, ui: &Ui) -> Target {}let p = active_paint(app);match &p {+ Paint::Gradient(g) if g.gradient.kind == GradientKind::Freeform => {+ // Like stops: without a selected point, the first.+ let f = super::gradient::shown_points(g);+ let index = app.session.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);+ Target::Point { index, color: f.points.get(index).map_or(Color::BLACK, |p| p.color) }+ }Paint::Gradient(g) => {let i = app.session.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));let color = g.gradient.stops.get(i).map(|s| s.color).unwrap_or(Color::BLACK);@@ -301,6 +310,10 @@ fn apply(app: &mut VectorcraftApp, tgt: &Target, c: Color, phase: Live, behind:}super::gradient::set_stops(app, &stops, None, phase);}+ Target::Point { index, .. } if !behind => {+ let p = json!({"index": index, "color": color_json(&c), "stroke": !app.session.fill_active});+ live_run(app, "Color", "paint.freeform.setPoint", p, phase);+ }_ => {let cmd = super::proxy_cmd(app, behind);// The panel's sliders work in the model picked there, even in a CMYK document.@@ -507,7 +520,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {] {if menu_item(ui, label, recolor, false) {match (&tgt, color) {- (Target::Stop { .. }, Some(c)) => apply(app, &tgt, f(&c), Live::Released, false),+ (Target::Stop { .. } | Target::Point { .. }, Some(c)) => apply(app, &tgt, f(&c), Live::Released, false),_ => {app.run(cmd, json!({})).ok();}diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rsindex 84b1ed2e7..99bd38a03 100644--- a/crates/ui-egui/src/panels/gradient.rs+++ b/crates/ui-egui/src/panels/gradient.rs@@ -7,13 +7,17 @@//! for the stop popover, and drag a diamond to move a midpoint (a selected diamond's midpoint//! shows in Location). Dropping a colour swatch on the ramp adds a stop of that colour, or//! recolours the stop it lands on. Hide Options leaves the thumbnail, the proxy and the slider.+//!+//! A freeform gradient shows its section instead of the angle, aspect and slider: the Draw+//! toggle (Points or Lines: how the Gradient tool adds points) and the selected point's colour+//! (edited in the Color panel), opacity and spread, with Delete Point.use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};use serde_json::{Value, json};use vectorcraft_color::gradient::{MIN_STOPS, duplicate_stop, insert_stop, midpoint_from_pos, midpoint_pos, move_stop, remove_stop, set_midpoint, swap_stop_colors,};-use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};+use vectorcraft_color::{Color, Freeform, FreeformMode, Gradient, GradientKind, GradientPaint, GradientStop, Paint};use vectorcraft_doc::NodeId;use super::{active_paint, live_run, pstate, set_pstate};@@ -180,9 +184,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {}});});+ let freeform = is_grad && kind == GradientKind::Freeform;if hidden {- ui.add_space(6.0);- ramp(app, ui, &g.gradient, is_grad);+ if !freeform {+ ui.add_space(6.0);+ ramp(app, ui, &g.gradient, is_grad);+ }return;}ui.add_space(4.0);@@ -196,6 +203,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {widgets::icon_button_enabled(ui, icon, tip, icon == "dc-stroke-center" && !app.session.fill_active, false, 22.0);}});+ if freeform {+ freeform_section(app, ui, &g);+ return;+ }// The proxy beside the angle and aspect ratio fields.ui.horizontal(|ui| {super::proxy(app, ui, 36.0);@@ -231,6 +242,74 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {}}+/// The freeform points shown: the gradient's own, else (unplaced) as many as it places, coloured+/// along the stops.+pub(crate) fn shown_points(g: &GradientPaint) -> std::borrow::Cow<'_, Freeform> {+ g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0))+}++/// Run a `paint.freeform.*` command on the paint behind the active proxy.+fn edit_point(app: &mut VectorcraftApp, cmd: &str, mut params: Value) {+ params["stroke"] = json!(!app.session.fill_active);+ live_run(app, "Gradient", cmd, params, Live::Released);+}++/// The freeform section: the proxy beside the Draw toggle, then the selected point's colour,+/// opacity and spread, and Delete Point.+fn freeform_section(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint) {+ let f = shown_points(g);+ let mode = f.mode;+ ui.horizontal(|ui| {+ super::proxy(app, ui, 36.0);+ ui.add_space(4.0);+ widgets::dim_label(ui, "Draw:");+ for (m, icon, tip) in [+ (FreeformMode::Points, "circle", "Points: clicks add free points"),+ (FreeformMode::Lines, "spline", "Lines: clicks add points joined by a line"),+ ] {+ if widgets::icon_button(ui, icon, tip, mode == m, 24.0).clicked() && mode != m {+ edit(app, json!({ "mode": m.label().to_lowercase() }), Live::Released);+ }+ }+ });+ ui.add_space(6.0);+ let sel = app.session.selected_freeform_point().filter(|i| *i < f.points.len());+ let point = sel.map(|i| f.points[i]);+ ui.horizontal(|ui| {+ widgets::dim_label(ui, "Color:");+ let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover());+ let paint = point.map_or(Paint::None, |p| Paint::solid(p.color));+ widgets::swatch_tile(ui, r, &paint, false, resp.hovered());+ resp.on_hover_text("Edit the selected point's colour in the Color panel");+ if let Some(p) = point {+ widgets::dim_label(ui, &p.color.to_hex().to_uppercase());+ }+ });+ ui.horizontal(|ui| {+ ui.add_enabled_ui(sel.is_some(), |ui| {+ for (label, key, value) in [("Opacity:", "opacity", point.map(|p| p.opacity)), ("Spread:", "spread", point.map(|p| p.spread))] {+ widgets::dim_label(ui, label);+ // Blank while no point is selected.+ let shown = value.map(|v| (v as f64 * 1000.0).round() / 10.0);+ if let Some(v) = widgets::mixed_field(ui, ("freeform", key), shown, "%", 1, 54.0)+ && let Some(i) = sel+ {+ edit_point(app, "paint.freeform.setPoint", json!({ "index": i, key: v.clamp(0.0, 100.0) / 100.0 }));+ }+ }+ });+ let can_del = sel.is_some() && f.points.len() > 1;+ if widgets::icon_button_enabled(ui, "trash-2", "Delete Point", false, can_del, 22.0).clicked()+ && let Some(i) = sel+ {+ edit_point(app, "paint.freeform.deletePoint", json!({ "index": i }));+ }+ });+ if sel.is_none() {+ widgets::dim_label(ui, "Click the art with the Gradient tool to add or select points.");+ }+}+/// The gradient thumbnail (click: apply a gradient; drag: onto art) and its menu of gradient/// swatches with Save to Swatches.fn thumbnail(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: bool) {diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rsindex 343b8efd2..0593cce89 100644--- a/crates/ui-egui/src/panels/mod.rs+++ b/crates/ui-egui/src/panels/mod.rs@@ -380,6 +380,8 @@ mod tests_appearance;#[cfg(test)]mod tests_effectedit;#[cfg(test)]+mod tests_freeform;+#[cfg(test)]mod tests_stroke;#[cfg(test)]mod tests_strokeux;diff --git a/crates/ui-egui/src/panels/tests_freeform.rs b/crates/ui-egui/src/panels/tests_freeform.rsnew file mode 100644index 000000000..945cd854a--- /dev/null+++ b/crates/ui-egui/src/panels/tests_freeform.rs@@ -0,0 +1,118 @@+//! Headless frames of the Gradient panel's freeform section and the Color panel on a freeform+//! point.++use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect, vec2};+use serde_json::{Value, json};+use vectorcraft_color::{Freeform, FreeformMode, Paint};+use vectorcraft_engine::Session;++use super::*;++/// A selected rectangle with a freeform fill.+fn app() -> VectorcraftApp {+ let mut app = VectorcraftApp::new(Session::new(), Default::default());+ run(&mut app, "file.new", json!({"width": 300, "height": 300}));+ run(&mut app, "shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100}));+ run(&mut app, "paint.editGradient", json!({"kind": "freeform"}));+ app+}++fn run(app: &mut VectorcraftApp, id: &str, p: Value) -> Value {+ app.session.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))+}++fn freeform(app: &VectorcraftApp) -> Freeform {+ match current_paints(app).0 {+ Paint::Gradient(g) => g.freeform.expect("placed points"),+ p => panic!("expected a gradient fill, got {p:?}"),+ }+}++/// One frame of `f` with `events`: the texts drawn and their centres.+fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<Event>, f: fn(&mut VectorcraftApp, &mut egui::Ui)) -> Vec<(String, Pos2)> {+ fn texts(s: &egui::Shape, out: &mut Vec<(String, Pos2)>) {+ match s {+ egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.pos + t.galley.rect.center().to_vec2())),+ egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),+ _ => {}+ }+ }+ let input = egui::RawInput { events, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(260.0, 600.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| f(app, ui));+ out.textures_delta.clear();+ let mut v = vec![];+ out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));+ v+}++fn at(texts: &[(String, Pos2)], s: &str) -> Pos2 {+ texts.iter().find(|(t, _)| t == s).unwrap_or_else(|| panic!("`{s}` not drawn: {texts:?}")).1+}++fn click(ctx: &egui::Context, app: &mut VectorcraftApp, pos: Pos2, f: fn(&mut VectorcraftApp, &mut egui::Ui)) -> Vec<(String, Pos2)> {+ let b = |pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };+ frame(ctx, app, vec![Event::PointerMoved(pos), b(true)], f);+ frame(ctx, app, vec![b(false)], f);+ frame(ctx, app, vec![], f)+}++/// Click the field drawn at `pos`, replace its text with `text` and press Enter.+fn type_into(ctx: &egui::Context, app: &mut VectorcraftApp, pos: Pos2, text: &str, f: fn(&mut VectorcraftApp, &mut egui::Ui)) {+ click(ctx, app, pos, f);+ let key = |k, modifiers| Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers };+ frame(ctx, app, vec![key(Key::A, Modifiers::COMMAND), Event::Text(text.into())], f);+ frame(ctx, app, vec![key(Key::Enter, Modifiers::NONE)], f);+}++#[test]+fn the_freeform_section_replaces_the_slider_and_sets_the_draw_mode() {+ let mut app = app();+ let ctx = egui::Context::default();+ let texts = frame(&ctx, &mut app, vec![], gradient::show);+ assert!(texts.iter().any(|(t, _)| t == "Draw:" || t == "Spread:"), "{texts:?}");+ assert!(!texts.iter().any(|(t, _)| t == "Location:"), "no stop fields: {texts:?}");+ // The Draw toggle's Lines button sits right of the Points one.+ let draw = at(&texts, "Draw:");+ click(&ctx, &mut app, draw + vec2(60.0, 0.0), gradient::show);+ assert_eq!(freeform(&app).mode, FreeformMode::Lines);+ click(&ctx, &mut app, draw + vec2(32.0, 0.0), gradient::show);+ assert_eq!(freeform(&app).mode, FreeformMode::Points);+}++#[test]+fn the_selected_points_opacity_spread_and_delete() {+ let mut app = app();+ let n = freeform(&app).points.len();+ run(&mut app, "paint.freeform.selectPoint", json!({"index": 1}));+ let ctx = egui::Context::default();+ let texts = frame(&ctx, &mut app, vec![], gradient::show);+ let hex = freeform(&app).points[1].color.to_hex().to_uppercase();+ assert!(texts.iter().any(|(t, _)| *t == hex), "the point's colour: {texts:?}");+ let spread = at(&texts, "0%");+ type_into(&ctx, &mut app, spread, "40", gradient::show);+ assert!((freeform(&app).points[1].spread - 0.4).abs() < 1e-6, "{:?}", freeform(&app).points[1]);+ let opacity = at(&texts, "100%");+ type_into(&ctx, &mut app, opacity, "50", gradient::show);+ assert!((freeform(&app).points[1].opacity - 0.5).abs() < 1e-6);+ // Delete Point sits right of the Spread field (54 px wide, text left-aligned in it).+ let texts = frame(&ctx, &mut app, vec![], gradient::show);+ let trash = at(&texts, "40%") + vec2(57.0, 0.0);+ click(&ctx, &mut app, trash, gradient::show);+ assert_eq!(freeform(&app).points.len(), n - 1, "Delete Point");+ // Nothing selected: the hint.+ let texts = frame(&ctx, &mut app, vec![], gradient::show);+ assert!(texts.iter().any(|(t, _)| t.starts_with("Click the art")), "{texts:?}");+}++#[test]+fn the_color_panel_recolours_the_selected_point() {+ let mut app = app();+ run(&mut app, "paint.freeform.selectPoint", json!({"index": 2}));+ let ctx = egui::Context::default();+ let texts = frame(&ctx, &mut app, vec![], color::show);+ let hex = freeform(&app).points[2].color.to_hex()[1..].to_uppercase();+ let field = texts.iter().find(|(t, _)| t.eq_ignore_ascii_case(&hex)).unwrap_or_else(|| panic!("{hex} in {texts:?}")).1;+ type_into(&ctx, &mut app, field, "00FF00", color::show);+ assert_eq!(freeform(&app).points[2].color.to_hex(), "#00ff00");+ assert!(matches!(current_paints(&app).0, Paint::Gradient(_)), "still a gradient");+}diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 8c76851d4..34b93f1f5 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -975,10 +975,12 @@ pub struct SwatchRows {impl PanelDrag {/// `paint` dragged from a Fill/Stroke proxy or the Gradient panel's thumbnail. A gradient- /// carries no placement: it fits the art it lands on.+ /// carries no placement: it fits the art it lands on (freeform points are placed afresh there,+ /// coloured like the dragged ones).pub fn paint(mut paint: Paint) -> Self {if let Paint::Gradient(g) = &mut paint {g.geom = None;+ g.freeform = None;}Self::Paint { params: crate::panels::paint_params(&paint), paint, rows: None }}diff --git a/docs/mcp.md b/docs/mcp.mdindex 1896f9445..65c17038b 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -155,6 +155,21 @@ delete it, hold Alt to copy it), dragging the end handle changes the vector. The{"name":"press_key","arguments":{"key":"Delete"}}```+Freeform gradients: `paint.editGradient {kind: "freeform"}` places four or more colour points inside each selected+object (coloured along the stops; `mode: "points"|"lines"` is the Draw toggle). `paint.freeform.get` lists the points+(document coordinates), lines and the selected point; `paint.freeform.addPoint {at, color?, opacity?, spread?,+line?}`, `setPoint {index?, …}`, `deletePoint {index?}`, `addLine {points}`, `splitLine {line, segment, t?}` and+`selectPoint {index|null}` edit them (`index` defaults to the selected point; each edit is one undo step). With the+Gradient tool on a freeform gradient a click on a point selects it (drag to move it), a click on a line adds a point+on it, a click elsewhere on the art adds a point (in Lines mode joined to the selected one), and Delete removes the+selected point:++```json+{"name":"run_command","arguments":{"command":"paint.editGradient","params":{"kind":"freeform","mode":"lines"}}}+{"name":"run_command","arguments":{"command":"paint.freeform.addPoint","params":{"at":[150,150],"color":"#ff3366","spread":20}}}+{"name":"pointer_gesture","arguments":{"tool":"gradient","events":[{"kind":"down","x":180,"y":170},{"kind":"up","x":180,"y":170}]}}+```+Raw protocol (for debugging):```sh