Skip to content

VectorCraft: An open-source, vector art tool written by scratch in pure Rust

Merge wp/D1

bflatastic721bb483c3b6
diff --cc crates/doc/src/node.rs
index ac658fd25,0a81fd3ea..9ed084cf6
--- a/crates/doc/src/node.rs
+++ b/crates/doc/src/node.rs
@@@ -520,51 -521,22 +525,55 @@@ impl Node
self.walk(&mut |_| n += 1);
n
}
-}
-
-fn transform_paints(ap: &mut Appearance, a: Affine) {
- use crate::appearance::AppearanceItem;
- use vectorcraft_color::Paint;
- for it in &mut ap.items {
- let p = match it {
- AppearanceItem::Fill(f) => &mut f.paint,
- AppearanceItem::Stroke(s) => &mut s.paint,
- };
- if let Paint::Gradient(g) = p
- && let Some(geom) = &mut g.geom
+ /// Fix this node's unplaced gradients to their fit on its current bounds (before a transform
+ /// or warp that refitting wouldn't reproduce). Descendants pin their own when transformed.
+ pub fn pin_gradients(&mut self) {
+ if self.appearance.has_unplaced_gradient()
+ && let Some(b) = self.geometric_bounds()
{
- geom.transform(a);
+ self.appearance.pin_gradients(b);
+ }
+ }
+ /// The paint behind the Fill (or Stroke) proxy, the map from its space to the document and
- /// the box (in that space) an unplaced gradient fits. Type objects paint their runs (the first
- /// run speaks for all) in text space, fitted to the layout bounds; everything else paints its
- /// top fill or stroke in the document, fitted to the geometric bounds. Strokes fit the box
- /// grown by half their weight.
- pub fn proxy_paint(&self, stroke: bool) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> {
- if let NodeKind::Text(t) = &self.kind {
++ /// the box (in that space) an unplaced gradient fits. `item` (the Appearance panel's active
++ /// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise
++ /// type objects paint their runs (the first run speaks for all) in text space, fitted to the
++ /// layout bounds; everything else paints its fill or stroke in the document, fitted to the
++ /// geometric bounds. Strokes fit the box grown by half their weight.
++ pub fn proxy_paint(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> {
++ let item = self.appearance.item_of_kind(item, !stroke);
++ if item.is_none()
++ && let NodeKind::Text(t) = &self.kind
++ {
+ let st = &t.runs.first()?.style;
+ let b = t.local_bounds();
+ return Some(if stroke { (&st.stroke, t.xf, crate::appearance::stroke_paint_bounds(b, st.stroke_width)) } else { (&st.fill, t.xf, b) });
+ }
+ let b = self.geometric_bounds()?;
+ if stroke {
- self.appearance.stroke().map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b)))
++ self.appearance.stroke_at(item).map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b)))
+ } else {
- self.appearance.fill().map(|f| (&f.paint, Affine::IDENTITY, b))
++ self.appearance.fill_at(item).map(|f| (&f.paint, Affine::IDENTITY, b))
}
}
+ /// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates
+ /// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits.
- pub fn proxy_gradient(&self, stroke: bool) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> {
- let (paint, to_doc, b) = self.proxy_paint(stroke)?;
++ pub fn proxy_gradient(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> {
++ let (paint, to_doc, b) = self.proxy_paint(stroke, item)?;
+ let vectorcraft_color::Paint::Gradient(g) = paint else { return None };
+ let mut geom = g.resolve(b);
+ if to_doc != Affine::IDENTITY {
+ geom.transform(to_doc, g.gradient.kind);
+ }
+ Some((g, geom))
+ }
+}
+
+/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
+fn keeps_gradient_fit(a: Affine) -> bool {
+ let [m0, m1, m2, m3, _, _] = a.as_coeffs();
+ let eps = 1e-12 * m0.abs().max(1.0);
+ m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
}
#[cfg(test)]
diff --cc crates/engine/src/cmd/appearance.rs
index f3e6f506b,7e794f70d..e3d041045
--- a/crates/engine/src/cmd/appearance.rs
+++ b/crates/engine/src/cmd/appearance.rs
@@@ -41,8 -98,177 +98,183 @@@ pub fn specs() -> Vec<CommandSpec>
]
}
- fn add_item(s: &mut Session, fill: bool) -> Result<Value> {
- let ids = paint_targets(s, &json!({}))?;
+ /// The Appearance panel's active row, remembered for the selection it was chosen in.
+ #[derive(Clone, Debug)]
+ pub(crate) struct ActiveItem {
+ doc: u64,
+ objects: Vec<NodeId>,
+ index: usize,
+ }
+
+ impl Session {
+ /// The Appearance panel's active fill/stroke: a paint-order index into the first selected
+ /// object's stack, while the selection it was chosen for is unchanged.
+ pub fn appearance_item(&self) -> Option<usize> {
+ let a = self.active_appearance_item.as_ref()?;
+ let st = self.active()?;
+ if st.uid != a.doc || st.selection.objects != a.objects {
+ return None;
+ }
+ let n = st.doc.node(*a.objects.first()?)?;
+ (a.index < n.appearance.items.len()).then_some(a.index)
+ }
+
+ /// Re-point the active item after an edit of `ids` changed its stack (`None` drops it). Edits
+ /// of other objects leave it alone.
+ fn remap_appearance_item(&mut self, ids: &[NodeId], f: impl FnOnce(usize) -> Option<usize>) {
+ if let Some(a) = &mut self.active_appearance_item
+ && a.objects.first().is_some_and(|o| ids.contains(o))
+ {
+ match f(a.index) {
+ Some(i) => a.index = i,
+ None => self.active_appearance_item = None,
+ }
+ }
+ }
+ }
+
+ /// Which fill or stroke of an appearance stack an edit changes (the `item` param).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub(crate) enum ItemTarget {
+ /// The topmost fill or stroke (for effects: the object-level effects).
+ Top,
+ /// Item `index`. `explicit`: named by the `item` param, so it must exist and be of the edited
+ /// kind; otherwise it is the panel's active item, which applies only where it fits.
+ Item { index: usize, explicit: bool },
+ }
+
+ /// Parse the `item` param of `cmd` (see the module docs).
+ pub(crate) fn item_target(s: &Session, p: &Value, cmd: &str) -> Result<ItemTarget> {
+ match p.get("item") {
+ Some(Value::Null) => Ok(ItemTarget::Top),
+ Some(v) => v
+ .as_u64()
+ .map(|i| ItemTarget::Item { index: i as usize, explicit: true })
+ .ok_or_else(|| bad(cmd, "`item` must be an appearance item index (paint order) or null")),
+ None if p.get("ids").is_some() || p.get("id").is_some() => Ok(ItemTarget::Top),
+ None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false })),
+ }
+ }
+
+ impl ItemTarget {
+ /// Objects a fill/stroke edit changes: the selected objects' own stacks when an item is
+ /// targeted, else the painted leaves ([`paint_targets`]).
+ pub(crate) fn targets(self, s: &Session, p: &Value) -> Result<Vec<NodeId>> {
+ match self {
+ ItemTarget::Top => paint_targets(s, p),
+ ItemTarget::Item { .. } => appearance_targets(s, p),
+ }
+ }
+
+ /// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits
+ /// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted
+ /// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
+ pub(crate) fn of_kind(self, s: &Session, fill: bool) -> Self {
+ let ItemTarget::Item { index, explicit: false } = self else { return self };
+ let fits = s.active().and_then(|st| st.doc.node(*st.selection.objects.first()?)?.appearance.items.get(index).map(|it| it.is_fill() == fill));
+ if fits == Some(true) { self } else { ItemTarget::Top }
+ }
+
+ /// The item of `ap` a fill (`fill`) or stroke edit changes; `None` = the topmost one.
+ pub(crate) fn resolve(self, ap: &Appearance, fill: bool, cmd: &str) -> Result<Option<usize>> {
+ match self {
+ ItemTarget::Top => Ok(None),
+ ItemTarget::Item { index, explicit } => match ap.item_of_kind(Some(index), fill) {
- None if explicit => Err(bad(cmd, format!("appearance item {index} is not a {}", if fill { "fill" } else { "stroke" }))),
++ None if explicit => Err(bad(
++ cmd,
++ match ap.items.get(index) {
++ None => format!("no appearance item {index}"),
++ Some(_) => format!("appearance item {index} is not a {}", if fill { "fill" } else { "stroke" }),
++ },
++ )),
+ found => Ok(found),
+ },
+ }
+ }
+
+ /// The item whose own effects an effect edit changes; `None` = the object-level effects.
+ pub(crate) fn effects_item(self, ap: &Appearance, cmd: &str) -> Result<Option<usize>> {
+ match self {
+ ItemTarget::Top => Ok(None),
+ ItemTarget::Item { index, .. } if index < ap.items.len() => Ok(Some(index)),
+ ItemTarget::Item { index, explicit: true } => Err(bad(cmd, format!("no appearance item {index}"))),
+ ItemTarget::Item { explicit: false, .. } => Ok(None),
+ }
+ }
+ }
+
+ /// Objects whose own appearance stack a command edits: `ids`/`id`, else the selected objects
+ /// (a selected compound-path member stands for its compound). Layers are skipped.
+ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
+ if p.get("ids").is_none() && p.get("id").is_none() {
+ return selected_roots(s);
+ }
+ let d = &s.doc()?.doc;
+ Ok(targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.is_layer())).collect())
+ }
+
+ /// One undo step (`label`) running `f` on each of `ids` with the item a fill (`fill`) or stroke
+ /// edit aimed at `item` changes there (`None`: the topmost one; text then edits its characters).
+ pub(crate) fn edit_items(
+ s: &mut Session,
+ ids: &[NodeId],
+ item: ItemTarget,
+ cmd: &str,
+ label: &str,
+ fill: bool,
+ mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
+ ) -> Result<()> {
+ if ids.is_empty() {
+ return Ok(());
+ }
+ s.edit(label, |d, _| {
+ for id in ids {
+ let Some(n) = d.node_mut(*id) else { continue };
+ let index = item.resolve(&n.appearance, fill, cmd)?;
+ f(n, index)?;
+ }
+ Ok(())
+ })
+ }
+
+ /// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the
+ /// targeted item (on the first target object), else `default`.
+ pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool) -> Result<bool> {
+ if let Some(b) = p.get("stroke").and_then(Value::as_bool) {
+ return Ok(b);
+ }
+ let ItemTarget::Item { index, .. } = item else { return Ok(default) };
+ let ids = appearance_targets(s, p)?;
+ let d = &s.doc()?.doc;
+ Ok(ids.first().and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
+ }
+
+ pub(crate) fn index_param(p: &Value, key: &str, cmd: &str) -> Result<usize> {
+ p.get(key).and_then(Value::as_u64).map(|i| i as usize).ok_or_else(|| bad(cmd, format!("missing integer `{key}`")))
+ }
+
+ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
+ const C: &str = "appearance.setActiveItem";
+ let index = match p.get("index") {
+ Some(Value::Null) => {
+ s.active_appearance_item = None;
+ return Ok(json!({ "index": Value::Null }));
+ }
+ Some(_) => index_param(p, "index", C)?,
+ None => return Err(bad(C, "missing `index` (an item index or null)")),
+ };
+ let st = s.doc()?;
+ let objects = st.selection.objects.clone();
+ let first = objects.first().and_then(|id| st.doc.node(*id)).ok_or_else(|| EngineError::Other("nothing selected".into()))?;
+ let fill = first.appearance.items.get(index).ok_or_else(|| bad(C, format!("no appearance item {index}")))?.is_fill();
+ let doc = st.uid;
+ s.fill_active = fill;
+ s.active_appearance_item = Some(ActiveItem { doc, objects, index });
+ Ok(json!({ "index": index }))
+ }
+
+ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
+ let ids = appearance_targets(s, p)?;
s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
diff --cc crates/engine/src/cmd/gradient.rs
index d31edd859,b3da66522..70e301d71
--- a/crates/engine/src/cmd/gradient.rs
+++ b/crates/engine/src/cmd/gradient.rs
@@@ -2,10 -2,9 +2,11 @@@
use serde_json::{Value, json};
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
-use vectorcraft_doc::NodeKind;
+use vectorcraft_doc::appearance::stroke_paint_bounds;
- use vectorcraft_doc::{AppearanceItem, NodeKind};
++use vectorcraft_doc::{Node, NodeKind};
+use vectorcraft_geom::{Affine, Point, Rect};
+ use super::appearance::{ItemTarget, edit_items, edits_stroke, item_target};
use super::edit::selected_roots;
use super::*;
use crate::EngineError;
@@@ -17,7 -16,7 +18,7 @@@ pub fn specs() -> Vec<CommandSpec>
"Gradient",
["Window", "Gradient"],
None,
- "{stroke?: bool (default: the active proxy), kind?: linear|radial|freeform, stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87}] (at least 2), angle?: deg, aspect?: %, reverse?: bool, ids?} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
- "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform, stops?: [{offset 0..1, color, opacity? 0..1, midpoint? 0..1}], angle?: deg, aspect?: %, reverse?: bool, item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
++ "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform, stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87}] (at least 2), angle?: deg, aspect?: %, reverse?: bool, item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
has_doc,
edit_gradient
),
@@@ -26,7 -25,7 +27,7 @@@
"Gradient Vector",
[],
None,
- "{start: [x,y], end: [x,y] (document coordinates), ids?, stroke?: bool (default: the active proxy), index?: appearance item index (as appearance.setItem; targets that fill or stroke instead of the top one)} set the gradient vector (solid paints become the default gradient; type objects set it on their runs, in text space; the aspect ratio is kept)",
- "{start: [x,y], end: [x,y], ids?, stroke?: bool (default: the targeted item's kind, else the fill), item?: fill/stroke item index|null} set the gradient vector (solid paints become the default gradient)",
++ "{start: [x,y], end: [x,y] (document coordinates), ids?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind)} set the gradient vector (solid paints become the default gradient; type objects set it on their runs, in text space; the aspect ratio is kept)",
has_doc,
set_gradient_geom
),
@@@ -42,164 -32,8 +43,166 @@@
]
}
+/// The gradient behind the active proxy: the first selected object's (see
- /// `Node::proxy_paint`), else the default paint for new art.
++/// `Node::proxy_paint`; the Appearance panel's active item when it is of the proxy's kind), else
++/// the default paint for new art.
+pub(crate) fn active_gradient(s: &Session) -> Option<GradientPaint> {
+ let stroke = !s.fill_active;
+ let first = s.active().and_then(|d| d.selection.objects.first().and_then(|id| d.doc.node(*id)));
+ let paint = match first {
- Some(n) => n.proxy_paint(stroke).map(|(p, ..)| p.clone()),
++ Some(n) => n.proxy_paint(stroke, s.appearance_item()).map(|(p, ..)| p.clone()),
+ None => Some(if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() }),
+ };
+ match paint {
+ Some(Paint::Gradient(g)) => Some(*g),
+ _ => None,
+ }
+}
+
+fn select_stop(s: &mut Session, p: &Value) -> Result<Value> {
+ const C: &str = "gradient.selectStop";
+ let index = match p.get("index") {
+ None => return Err(bad(C, "missing `index` (a stop 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 n = active_gradient(s).ok_or_else(|| bad(C, "the active paint is not a gradient"))?.gradient.stops.len();
+ if i >= n {
+ return Err(bad(C, format!("no stop {i} (the gradient has {n})")));
+ }
+ Some(i)
+ }
+ };
+ s.gradient_stop = index.map(|i| (i, StopOwner::of(s)));
+ Ok(json!({ "index": index }))
+}
+
+/// Whose gradient a selected stop belongs to: the active document, its first selected object
- /// (None: the default paint) and the proxy in front. Selecting other art or toggling the proxy
- /// leaves no stop selected.
++/// (None: the default paint), the proxy in front and the Appearance panel's active item.
++/// Selecting other art, toggling the proxy or picking another item leaves no stop selected.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct StopOwner {
+ doc: Option<usize>,
+ object: Option<NodeId>,
+ fill: bool,
++ item: Option<usize>,
+}
+
+impl StopOwner {
+ fn of(s: &Session) -> Self {
- Self { doc: s.active, object: s.active().and_then(|d| d.selection.objects.first().copied()), fill: s.fill_active }
++ Self { doc: s.active, object: s.active().and_then(|d| d.selection.objects.first().copied()), fill: s.fill_active, item: s.appearance_item() }
+ }
+}
+
+impl Session {
+ /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on
+ /// is still the one behind the active proxy. Callers check it against the stop count (an undo
+ /// can remove stops).
+ pub fn selected_stop(&self) -> Option<usize> {
+ self.gradient_stop.filter(|(_, owner)| *owner == StopOwner::of(self)).map(|(i, _)| i)
+ }
+}
+
+type Parsed<T> = std::result::Result<T, String>;
+
+/// Parse a kind name.
+fn parse_kind(k: &str) -> Parsed<GradientKind> {
+ GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, freeform)"))
+}
+
+/// Parse `stops` params: at least two, each with a numeric `offset` (clamped to 0..1) and a valid
+/// `color`; `opacity` is 0..1 (values above 1 are percentages) and `midpoint` is clamped to the
+/// diamond's range. The result is sorted by offset.
+pub(crate) fn parse_stops(v: &Value) -> Parsed<Vec<GradientStop>> {
+ let arr = v.as_array().ok_or("`stops` must be an array")?;
+ if arr.len() < 2 {
+ return Err("a gradient needs at least two stops".into());
+ }
+ let mut out = arr
+ .iter()
+ .enumerate()
+ .map(|(i, st)| {
+ let num = |k: &str| st.get(k).map(|v| v.as_f64().ok_or_else(|| format!("stop {i}: `{k}` must be a number"))).transpose();
+ let offset = num("offset")?.ok_or_else(|| format!("stop {i} needs `offset`"))?;
+ let color = st.get("color").and_then(color_value).ok_or_else(|| format!("stop {i} needs a valid `color`"))?;
+ let opacity = num("opacity")?.map(|o| if o > 1.0 { o / 100.0 } else { o }).unwrap_or(1.0);
+ Ok(GradientStop {
+ offset: offset.clamp(0.0, 1.0) as f32,
+ color,
+ opacity: opacity.clamp(0.0, 1.0) as f32,
+ midpoint: num("midpoint")?.unwrap_or(0.5).clamp(0.13, 0.87) as f32,
+ })
+ })
+ .collect::<Parsed<Vec<_>>>()?;
+ out.sort_by(|a, b| a.offset.total_cmp(&b.offset));
+ Ok(out)
+}
+
+/// Parse a gradient paint object (the `gradient` param of `paint.setFill`). Lossless for everything
+/// `vectorcraft_tools::params::gradient_params` writes.
+pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
+ if !g.is_object() {
+ return Err("`gradient` must be an object".into());
+ }
+ let kind = str_param(g, "kind").map(parse_kind).transpose()?.unwrap_or_default();
+ let stops = g.get("stops").map(parse_stops).transpose()?.unwrap_or_else(|| Gradient::default().stops);
+ let mut gp = GradientPaint::new(Gradient { kind, stops });
+ gp.angle = f64_or(g, "angle", 0.0);
+ gp.swatch = str_param(g, "swatch").map(str::to_string);
+ let aspect = aspect_param(g)?;
+ let point = |k: &str| g.get(k).map(|_| point_param(g, k).ok_or_else(|| format!("`{k}` must be [x, y]"))).transpose();
+ match (point("start")?, point("end")?) {
+ (Some(start), Some(end)) => {
+ let geom = GradientGeom { start, end, aspect: aspect.unwrap_or(1.0) };
+ gp.angle = geom.angle_deg();
+ gp.geom = Some(geom);
+ }
+ (None, None) => {}
+ _ => return Err("give both `start` and `end` (or neither)".into()),
+ }
+ Ok(gp)
+}
+
+/// The `aspect` param (a percentage) as a ratio.
+fn aspect_param(p: &Value) -> Parsed<Option<f64>> {
+ p.get("aspect")
+ .map(|v| v.as_f64().map(|a| (a / 100.0).clamp(0.005, 327.67)).ok_or_else(|| "`aspect` must be a number (%)".to_string()))
+ .transpose()
+}
+
+/// `paint` without the placement it had on the art it came from (a swatch, or the default paint
+/// for new art): a placed gradient keeps its angle and fits each object it lands on.
+pub(crate) fn unplaced(paint: &Paint) -> Paint {
+ match paint {
+ Paint::Gradient(g) if g.geom.is_some() => Paint::Gradient(Box::new(GradientPaint { geom: None, ..(**g).clone() })),
+ _ => paint.clone(),
+ }
+}
+
+/// Is `p` applying a swatch (whose gradient placement belongs to the art it was saved from)?
+fn applies_swatch(p: &Value) -> bool {
+ p.get("swatch").is_some()
+}
+
+/// `paint` as applied to an object with `bounds`: a gradient given an `aspect` but no vector is
+/// placed on the bounds so the aspect sticks, and a gradient swatch fits the object (keeping its
+/// aspect) instead of the art it was saved from.
+pub(crate) fn place_paint(paint: &Paint, p: &Value, bounds: Option<Rect>) -> Paint {
+ let Paint::Gradient(g) = paint else { return paint.clone() };
+ let aspect = match g.geom {
+ Some(geom) if applies_swatch(p) => (geom.aspect != 1.0).then(|| json!(geom.aspect * 100.0)),
+ None => p.get("gradient").and_then(|g| g.get("aspect")).cloned(),
+ Some(_) => return paint.clone(),
+ };
+ let fitted = unplaced(paint);
+ match aspect {
+ Some(a) => apply_gradient_edit(&fitted, &json!({ "aspect": a }), bounds).unwrap_or(fitted),
+ None => fitted,
+ }
+}
+
/// Apply the gradient edits in `p` to `paint` (pure; unit-tested).
-pub(crate) fn apply_gradient_edit(paint: &Paint, p: &Value, bounds: Option<vectorcraft_geom::Rect>) -> std::result::Result<Paint, String> {
+pub(crate) fn apply_gradient_edit(paint: &Paint, p: &Value, bounds: Option<Rect>) -> std::result::Result<Paint, String> {
let mut gp = match paint {
Paint::Gradient(g) => (**g).clone(),
_ => GradientPaint::new(Gradient::default()),
@@@ -260,47 -120,20 +265,21 @@@ fn edit_gradient(s: &mut Session, p: &V
// Validate against the defaults first so bad params fail without touching the document.
let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() };
let new_default = apply_gradient_edit(&default_paint, p, None).map_err(|e| bad(C, e))?;
- if ids.is_empty() {
- if stroke {
- s.paint.stroke = new_default;
- } else {
- s.paint.fill = new_default;
- }
- return Ok(json!({"ids": []}));
- }
- let mut err = None;
- s.edit("Gradient", |d, _| {
- for id in &ids {
- let Some(n) = d.node_mut(*id) else { continue };
- if let NodeKind::Text(t) = &mut n.kind {
- let lb = t.local_bounds();
- for r in &mut t.runs {
- let (cur, b) = run_paint_mut(r, stroke, lb);
- match apply_gradient_edit(cur, p, Some(b)) {
- Ok(np) => *cur = np,
- Err(e) => err = Some(e),
- }
- }
- continue;
- }
- let b = n.geometric_bounds();
- let ap = &mut n.appearance;
- let (cur, b) = if stroke { (ap.stroke_paint(), b.zip(ap.stroke()).map(|(b, st)| st.paint_bounds(b))) } else { (ap.fill_paint(), b) };
- match apply_gradient_edit(&cur, p, b) {
- Ok(np) => {
- if stroke {
- ap.set_stroke(np)
- } else {
- ap.set_fill(np)
- }
- }
- Err(e) => err = Some(e),
+ edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
+ if index.is_none()
+ && let NodeKind::Text(t) = &mut n.kind
+ {
++ let lb = t.local_bounds();
+ for r in &mut t.runs {
- let cur = if stroke { &mut r.style.stroke } else { &mut r.style.fill };
- *cur = apply_gradient_edit(cur, p, None).map_err(|e| bad(C, e))?;
++ let (cur, b) = run_paint_mut(r, stroke, lb);
++ *cur = apply_gradient_edit(cur, p, Some(b)).map_err(|e| bad(C, e))?;
}
+ return Ok(());
}
- match err.take() {
- Some(e) => Err(bad(C, e)),
- None => Ok(()),
- }
- let b = n.geometric_bounds();
++ let b = item_paint_bounds(n, index, !stroke);
+ let np = apply_gradient_edit(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), p, b).map_err(|e| bad(C, e))?;
+ n.appearance.set_paint_at(index, !stroke, np);
+ Ok(())
})?;
if stroke {
s.paint.stroke = new_default;
@@@ -310,124 -143,34 +289,109 @@@
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
}
+/// A type run's fill or stroke paint and the box (text space) an unplaced gradient on it fits:
+/// the layout bounds `lb`, grown by half the run's stroke weight for strokes.
+pub(crate) fn run_paint_mut(r: &mut vectorcraft_doc::TextRun, stroke: bool, lb: Rect) -> (&mut Paint, Rect) {
+ if stroke {
+ let b = stroke_paint_bounds(lb, r.style.stroke_width);
+ (&mut r.style.stroke, b)
+ } else {
+ (&mut r.style.fill, lb)
+ }
+}
+
++/// The box an unplaced gradient on fill or stroke `index` of `n` fits (`None`: the topmost): the
++/// geometric bounds, grown by half the weight for a stroke (`None` without that stroke).
++pub(crate) fn item_paint_bounds(n: &Node, index: Option<usize>, fill: bool) -> Option<Rect> {
++ let b = n.geometric_bounds()?;
++ if fill { Some(b) } else { n.appearance.stroke_at(index).map(|st| st.paint_bounds(b)) }
++}
++
+/// `paint` as applied to a type run whose text space `xf` maps to the document: a vector given in
+/// document coordinates moves into text space, and an aspect without a vector places the gradient
+/// on the run's `bounds` (text space).
+pub(crate) fn place_run_paint(paint: &Paint, p: &Value, xf: Affine, bounds: Rect) -> Paint {
+ let mut out = place_paint(paint, p, Some(bounds));
+ if let (Paint::Gradient(src), Paint::Gradient(g)) = (paint, &mut out)
+ && src.geom.is_some()
+ && !applies_swatch(p)
+ && let Some(inv) = invert(xf)
+ {
+ g.transform(inv);
+ g.angle = g.geom.map_or(g.angle, |geom| geom.angle_deg());
+ }
+ out
+}
+
+/// The inverse of `a`, if it has one.
+fn invert(a: Affine) -> Option<Affine> {
+ (a.determinant().abs() > 1e-12).then(|| a.inverse())
+}
+
+/// `cur` as a gradient whose vector runs from `start` to `end` in the document. `to_doc` maps the
+/// paint's space (text space for type runs) to the document and `bounds` (in that space) fits an
+/// unplaced gradient, so the aspect ratio the document shows carries over.
+fn vector_paint(cur: &Paint, start: Point, end: Point, to_doc: Affine, bounds: Option<Rect>) -> Option<Paint> {
+ let from_doc = invert(to_doc)?;
+ let mut gp = match cur {
+ Paint::Gradient(g) => (**g).clone(),
+ _ => GradientPaint::new(Gradient::default()),
+ };
+ let kind = gp.gradient.kind;
+ let map = |mut g: GradientGeom, a: Affine| {
+ if a != Affine::IDENTITY {
+ g.transform(a, kind);
+ }
+ g
+ };
+ let aspect = gp.geom.or_else(|| bounds.map(|b| gp.resolve(b))).map_or(1.0, |g| map(g, to_doc).aspect);
+ let geom = map(GradientGeom { start, end, aspect }, from_doc);
+ gp.angle = geom.angle_deg();
+ gp.geom = Some(geom);
+ Some(Paint::Gradient(Box::new(gp)))
+}
+
fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "paint.setGradientGeom";
let start = point_param(p, "start").ok_or_else(|| bad(C, "missing start [x,y]"))?;
let end = point_param(p, "end").ok_or_else(|| bad(C, "missing end [x,y]"))?;
- let stroke = p.get("stroke").and_then(Value::as_bool).unwrap_or(!s.fill_active);
- let index = p.get("index").map(|v| v.as_u64().map(|i| i as usize).ok_or_else(|| bad(C, "`index` must be a whole number"))).transpose()?;
- let ids = match ids_param(p, "ids") {
- Some(v) => v,
- None => selected_roots(s)?,
++ // `index` is an alias of `item`.
++ let mut p = p.clone();
++ if let (None, Some(i)) = (p.get("item"), p.get("index").cloned()) {
++ p["item"] = i;
++ }
++ let p = &p;
+ let item = item_target(s, p, C)?;
- let stroke = edits_stroke(s, p, item, false)?;
++ let stroke = edits_stroke(s, p, item, !s.fill_active)?;
+ let item = item.of_kind(s, !stroke);
+ let targets = match item {
+ ItemTarget::Top => leaf_targets(s, &ids_param(p, "ids").map_or_else(|| selected_roots(s), Ok)?)?,
+ _ => item.targets(s, p)?,
};
- let targets = leaf_targets(s, &ids)?;
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
}
- s.edit("Gradient", |d, _| {
- let mut hit = false;
- for id in &targets {
- let Some(n) = d.node_mut(*id) else { continue };
- let b = n.geometric_bounds();
- if let Some(i) = index {
- let Some(item) = n.appearance.items.get_mut(i) else { continue };
- let (paint, b) = match item {
- AppearanceItem::Fill(f) => (&mut f.paint, b),
- AppearanceItem::Stroke(st) => {
- let b = b.map(|b| st.paint_bounds(b));
- (&mut st.paint, b)
- }
- };
- if let Some(np) = vector_paint(paint, start, end, Affine::IDENTITY, b) {
- *paint = np;
- hit = true;
- }
- continue;
- }
- if let NodeKind::Text(t) = &mut n.kind {
- let (xf, lb) = (t.xf, t.local_bounds());
- for r in &mut t.runs {
- if stroke && r.style.stroke_width == 0.0 {
- r.style.stroke_width = 1.0;
- }
- let (paint, b) = run_paint_mut(r, stroke, lb);
- if let Some(np) = vector_paint(paint, start, end, xf, Some(b)) {
- *paint = np;
- hit = true;
- }
- let geom = GradientGeom { start, end, aspect: 1.0 };
+ edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| {
- if matches!(n.kind, NodeKind::Text(_)) {
++ if index.is_none()
++ && let NodeKind::Text(t) = &mut n.kind
++ {
++ let (xf, lb) = (t.xf, t.local_bounds());
++ for r in &mut t.runs {
++ if stroke && r.style.stroke_width == 0.0 {
++ r.style.stroke_width = 1.0;
+ }
- continue;
- }
- let ap = &mut n.appearance;
- let (cur, b) = if stroke { (ap.stroke_paint(), b.zip(ap.stroke()).map(|(b, st)| st.paint_bounds(b))) } else { (ap.fill_paint(), b) };
- if let Some(np) = vector_paint(&cur, start, end, Affine::IDENTITY, b) {
- if stroke {
- ap.set_stroke(np);
- } else {
- ap.set_fill(np);
++ let (paint, b) = run_paint_mut(r, stroke, lb);
++ if let Some(np) = vector_paint(paint, start, end, xf, Some(b)) {
++ *paint = np;
+ }
- hit = true;
+ }
+ return Ok(());
}
- match (hit, index) {
- (false, Some(i)) => Err(bad(C, format!("no appearance item at index {i}"))),
- _ => Ok(()),
- let mut gp = match n.appearance.paint_at(index, !stroke) {
- Some(Paint::Gradient(g)) => (**g).clone(),
- _ => GradientPaint::new(Gradient::default()),
- };
- let aspect = gp.geom.map(|g| g.aspect).unwrap_or(1.0);
- gp.geom = Some(GradientGeom { aspect, ..geom });
- gp.angle = geom.angle_deg();
- n.appearance.set_paint_at(index, !stroke, Paint::Gradient(Box::new(gp)));
++ let b = item_paint_bounds(n, index, !stroke);
++ if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), start, end, Affine::IDENTITY, b) {
++ n.appearance.set_paint_at(index, !stroke, np);
+ }
+ Ok(())
})?;
Ok(json!({ "ids": targets.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
diff --cc crates/engine/src/cmd/paint.rs
index 6d21a4543,b1ce6c748..4da442fa8
--- a/crates/engine/src/cmd/paint.rs
+++ b/crates/engine/src/cmd/paint.rs
@@@ -1,10 -1,10 +1,11 @@@
//! Fill and stroke paint (the toolbar proxies and their defaults) and the Transparency panel.
use serde_json::{Value, json};
- use vectorcraft_color::{Color, Paint};
-use vectorcraft_color::{BlendMode, Color, Gradient, GradientKind, GradientPaint, Paint};
++use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, NodeKind};
- use super::gradient::{place_paint, place_run_paint, run_paint_mut, unplaced};
+ use super::appearance::{ItemTarget, appearance_targets, edit_items, item_target};
++use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, unplaced};
use super::*;
use crate::EngineError;
@@@ -15,7 -15,7 +16,7 @@@ pub fn specs() -> Vec<CommandSpec>
"Fill",
[],
None,
- "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}, none?: true, swatch?: name (a gradient swatch fits each object, keeping its aspect), gradient?: {kind?: linear|radial|freeform, stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), swatch?: linked gradient swatch name}, ids?} sets selection fill and the default (new art fits a gradient to itself)",
- "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}, none?: true, swatch?: name, gradient?: {kind, stops:[{offset,color}], angle?}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?} sets the selection's fill and the default",
++ "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}, none?: true, swatch?: name (a gradient swatch fits each object, keeping its aspect), gradient?: {kind?: linear|radial|freeform, stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?} sets the selection's fill and the default (new art fits a gradient to itself)",
has_doc,
|s, p| set_paint(s, p, true)
),
@@@ -74,42 -96,33 +77,38 @@@ pub(crate) fn paint_from(s: &Session, p
}
fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
- let paint = paint_from(s, p)?.ok_or_else(|| bad("paint.setFill", "give color, none, swatch or gradient"))?;
+ let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
+ let paint = paint_from(s, p)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?;
+ // New art gets the paint fitted to itself, not placed where this one is.
if fill {
- s.paint.fill = paint.clone();
+ s.paint.fill = unplaced(&paint);
} else {
- s.paint.stroke = paint.clone();
+ s.paint.stroke = unplaced(&paint);
}
s.fill_active = fill;
- let ids = paint_targets(s, p)?;
- if ids.is_empty() {
- return ok();
- }
- s.edit(if fill { "Fill Color" } else { "Stroke Color" }, |d, _| {
- for id in &ids {
- let Some(n) = d.node_mut(*id) else { continue };
- if let NodeKind::Text(t) = &mut n.kind {
- let (xf, lb) = (t.xf, t.local_bounds());
- for r in &mut t.runs {
- if !fill && r.style.stroke_width == 0.0 {
- r.style.stroke_width = 1.0;
- }
- let (cur, b) = run_paint_mut(r, !fill, lb);
- *cur = place_run_paint(&paint, p, xf, b);
- }
- continue;
- }
- let b = n.geometric_bounds();
- if fill {
- n.appearance.set_fill(place_paint(&paint, p, b));
- } else {
- n.appearance.set_stroke(paint.clone());
- if let Some(st) = n.appearance.stroke_mut() {
- st.paint = place_paint(&paint, p, b.map(|b| st.paint_bounds(b)));
+ let item = item_target(s, p, cmd)?.of_kind(s, fill);
+ let ids = item.targets(s, p)?;
+ edit_items(s, &ids, item, cmd, if fill { "Fill Color" } else { "Stroke Color" }, fill, |n, index| {
+ if index.is_none()
+ && let NodeKind::Text(t) = &mut n.kind
+ {
++ let (xf, lb) = (t.xf, t.local_bounds());
+ for r in &mut t.runs {
- if fill {
- r.style.fill = paint.clone();
- } else {
- r.style.stroke = paint.clone();
- if r.style.stroke_width == 0.0 {
- r.style.stroke_width = 1.0;
- }
++ if !fill && r.style.stroke_width == 0.0 {
++ r.style.stroke_width = 1.0;
}
++ let (cur, b) = run_paint_mut(r, !fill, lb);
++ *cur = place_run_paint(&paint, p, xf, b);
}
- } else {
- n.appearance.set_paint_at(index, fill, paint.clone());
++ return Ok(());
+ }
++ // A missing top fill or stroke is created first: a new stroke's weight sizes the box its
++ // gradient fits.
++ if n.appearance.paint_at(index, fill).is_none() {
++ n.appearance.set_paint_at(index, fill, Paint::None);
+ }
++ let placed = place_paint(&paint, p, item_paint_bounds(n, index, fill));
++ n.appearance.set_paint_at(index, fill, placed);
Ok(())
})?;
ok()
diff --cc crates/engine/src/cmd/stroke.rs
index 2f89ef7cd,e78b621f2..1e2c7e919
--- a/crates/engine/src/cmd/stroke.rs
+++ b/crates/engine/src/cmd/stroke.rs
@@@ -2,8 -2,9 +2,9 @@@
use serde_json::Value;
use vectorcraft_color::{Color, Paint};
- use vectorcraft_doc::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign, StrokeLayer, WidthProfile};
-use vectorcraft_doc::{Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
++use vectorcraft_doc::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign, WidthProfile};
+ use super::appearance::{edit_items, item_target};
use super::*;
pub fn specs() -> Vec<CommandSpec> {
@@@ -13,7 -14,7 +14,7 @@@
"Stroke Options",
["Window", "Stroke"],
None,
- "{weight?, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares), dashOffset?, alignDashes?, startArrow?, endArrow?: Arrow|ArrowOpen|Triangle|TriangleOpen|Circle|CircleOpen|Square|SquareOpen|Diamond|Bar|null, arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\", ids?}",
- "{weight?, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null, dashOffset?, alignDashes?, startArrow?, endArrow?: name|null, profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\", item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?}",
++ "{weight?, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares), dashOffset?, alignDashes?, startArrow?, endArrow?: Arrow|ArrowOpen|Triangle|TriangleOpen|Circle|CircleOpen|Square|SquareOpen|Diamond|Bar|null, arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\", item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?}",
has_doc,
stroke_set
),
@@@ -48,72 -46,59 +46,69 @@@ fn stroke_set(s: &mut Session, p: &Valu
}
};
let (sa, ea) = (arrow("startArrow")?, arrow("endArrow")?);
+ let arrow_align = match str_param(p, "arrowAlign") {
+ None => None,
+ Some("extend") => Some(ArrowAlign::Extend),
+ Some("tip") => Some(ArrowAlign::Tip),
- Some(o) => return Err(bad("stroke.set", format!("arrowAlign must be extend|tip, got {o}"))),
++ Some(o) => return Err(bad(C, format!("arrowAlign must be extend|tip, got {o}"))),
+ };
+ let profile = match str_param(p, "profile") {
+ None => None,
+ Some("uniform") => Some(None),
- Some(id) => Some(Some(WidthProfile::preset(id).ok_or_else(|| bad("stroke.set", format!("unknown profile {id}")))?)),
++ Some(id) => Some(Some(WidthProfile::preset(id).ok_or_else(|| bad(C, format!("unknown profile {id}")))?)),
+ };
- s.edit("Stroke", |d, _| {
- for id in &ids {
- let Some(n) = d.node_mut(*id) else { continue };
- if n.appearance.stroke().is_none() {
- n.appearance.set_stroke(Paint::solid(Color::BLACK));
- }
- let st: &mut StrokeLayer = n.appearance.stroke_mut().unwrap();
- if let Some(w) = p.get("weight").and_then(Value::as_f64) {
- st.width = w.max(0.0);
- }
- match str_param(p, "cap") {
- Some("round") => st.cap = LineCap::Round,
- Some("square") | Some("projecting") => st.cap = LineCap::Square,
- Some("butt") => st.cap = LineCap::Butt,
- _ => {}
- }
- match str_param(p, "join") {
- Some("round") => st.join = LineJoin::Round,
- Some("bevel") => st.join = LineJoin::Bevel,
- Some("miter") => st.join = LineJoin::Miter,
- _ => {}
- }
- if let Some(m) = p.get("miterLimit").and_then(Value::as_f64) {
- st.miter_limit = m.clamp(1.0, 500.0);
- }
- match str_param(p, "align") {
- Some("inside") => st.align = StrokeAlign::Inside,
- Some("outside") => st.align = StrokeAlign::Outside,
- Some("center") => st.align = StrokeAlign::Center,
- _ => {}
- }
- match p.get("dash") {
- Some(Value::Null) => st.dash = None,
- Some(Value::Array(a)) => {
- let pattern: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
- st.dash = if pattern.is_empty() {
- None
- } else {
- Some(Dash { pattern, offset: f64_or(p, "dashOffset", 0.0), align_corners: bool_or(p, "alignDashes", false) })
- };
- }
- _ => {}
- }
- if let Some(a) = sa {
- st.start_arrow = a;
- }
- if let Some(a) = ea {
- st.end_arrow = a;
- }
- if let Some(a) = arrow_align {
- st.arrow_align = a;
- }
- if let Some(pr) = &profile {
- st.profile = pr.clone();
- }
+ edit_items(s, &ids, item, C, "Stroke", false, |n, index| {
+ if index.is_none() && n.appearance.stroke().is_none() {
+ n.appearance.set_stroke(Paint::solid(Color::BLACK));
+ }
+ let Some(st) = n.appearance.stroke_at_mut(index) else { return Ok(()) };
+ if let Some(w) = p.get("weight").and_then(Value::as_f64) {
+ st.width = w.max(0.0);
+ }
+ match str_param(p, "cap") {
+ Some("round") => st.cap = LineCap::Round,
+ Some("square") | Some("projecting") => st.cap = LineCap::Square,
+ Some("butt") => st.cap = LineCap::Butt,
+ _ => {}
+ }
+ match str_param(p, "join") {
+ Some("round") => st.join = LineJoin::Round,
+ Some("bevel") => st.join = LineJoin::Bevel,
+ Some("miter") => st.join = LineJoin::Miter,
+ _ => {}
+ }
+ if let Some(m) = p.get("miterLimit").and_then(Value::as_f64) {
+ st.miter_limit = m.clamp(1.0, 500.0);
+ }
+ match str_param(p, "align") {
+ Some("inside") => st.align = StrokeAlign::Inside,
+ Some("outside") => st.align = StrokeAlign::Outside,
+ Some("center") => st.align = StrokeAlign::Center,
+ _ => {}
+ }
+ match p.get("dash") {
+ Some(Value::Null) => st.dash = None,
+ Some(Value::Array(a)) => {
+ let pattern: Vec<f64> = a.iter().filter_map(Value::as_f64).collect();
+ st.dash = if pattern.is_empty() {
+ None
+ } else {
+ Some(Dash { pattern, offset: f64_or(p, "dashOffset", 0.0), align_corners: bool_or(p, "alignDashes", false) })
+ };
+ }
+ _ => {}
+ }
+ if let Some(a) = sa {
+ st.start_arrow = a;
+ }
+ if let Some(a) = ea {
+ st.end_arrow = a;
+ }
- match str_param(p, "profile") {
- Some("uniform") => st.profile = None,
- Some("lens") => st.profile = Some(vectorcraft_doc::WidthProfile::lens()),
- Some("taperStart") => st.profile = Some(vectorcraft_doc::WidthProfile::taper_start()),
- Some("taperEnd") => st.profile = Some(vectorcraft_doc::WidthProfile::taper_end()),
- _ => {}
++ if let Some(a) = arrow_align {
++ st.arrow_align = a;
++ }
++ if let Some(pr) = &profile {
++ st.profile = pr.clone();
}
Ok(())
})?;
diff --cc crates/engine/src/lib.rs
index 7b325cf6d,8b32f2d7e..1e8b17bfe
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -443,10 -443,9 +443,13 @@@ pub struct Session
untitled_counter: u32,
/// Session-level state of the menu commands (saved selections, guide lock).
pub(crate) menu: cmd::menucmds::MenuState,
+ /// The selected gradient stop (`gradient.selectStop`) and whose gradient it was selected on,
+ /// shared by the Gradient tool's annotator, the Gradient and Color panels and agents: read it
+ /// with [`Session::selected_stop`].
+ pub(crate) gradient_stop: Option<(usize, cmd::gradient::StopOwner)>,
+ /// The Appearance panel's active fill/stroke row (`appearance.setActiveItem`); not saved. Read
+ /// it through [`Session::appearance_item`], which drops it once the selection changes.
+ pub(crate) active_appearance_item: Option<cmd::appearance::ActiveItem>,
}
impl Default for Session {
@@@ -472,7 -471,7 +475,8 @@@ impl Session
draw_inside: None,
untitled_counter: 0,
menu: Default::default(),
+ gradient_stop: None,
+ active_appearance_item: None,
}
}
@@@ -740,10 -740,6 +747,10 @@@ mod tests_pattern
#[cfg(test)]
mod tests_prefs;
#[cfg(test)]
- mod tests_swatches;
- #[cfg(test)]
+mod tests_strokegeom;
+#[cfg(test)]
++mod tests_swatches;
++#[cfg(test)]
mod tests_textedit;
#[cfg(test)]
mod tests_xform;
diff --cc crates/engine/src/tests_gradient.rs
index 5db0f87b9,000000000..6fadaa417
mode 100644,000000..100644
--- a/crates/engine/src/tests_gradient.rs
+++ b/crates/engine/src/tests_gradient.rs
@@@ -1,376 -1,0 +1,376 @@@
+//! Gradients through commands: lossless, validated params (M3.14), transforms (M3.15), the active
+//! proxy and type (M3.16) and the interactive annotator (M3.17).
+
+use serde_json::{Value, json};
+use vectorcraft_color::{Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
+use vectorcraft_geom::Point;
+use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
+
+use super::*;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
+ s
+}
+
+fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
+ let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
+ NodeId(r["id"].as_u64().unwrap())
+}
+
+fn node(s: &Session, id: NodeId) -> &vectorcraft_doc::Node {
+ s.doc().unwrap().doc.node(id).unwrap()
+}
+
+fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint {
+ match node(s, id).appearance.fill_paint() {
+ Paint::Gradient(g) => *g,
+ p => panic!("expected a gradient fill, got {p:?}"),
+ }
+}
+
+/// A three-stop freeform gradient with a 0.3 midpoint, partial opacity and a placed vector.
+fn three_stops() -> GradientPaint {
+ let stop = |offset, color, opacity, midpoint| GradientStop { offset, color, opacity, midpoint };
+ let mut g = GradientPaint::new(Gradient {
+ kind: GradientKind::Freeform,
+ stops: vec![
+ stop(0.0, Color::rgb(1.0, 0.0, 0.0), 1.0, 0.3),
+ stop(0.4, Color::cmyk(0.1, 0.2, 0.3, 0.4), 0.5, 0.5),
+ stop(1.0, Color::gray(0.25), 0.75, 0.5),
+ ],
+ });
+ g.geom = Some(GradientGeom { start: Point::new(10.0, 20.0), end: Point::new(110.0, 70.0), aspect: 0.5 });
+ g.angle = g.geom.unwrap().angle_deg();
+ g
+}
+
+fn gradient_param(g: &GradientPaint) -> Value {
+ json!({ "gradient": vectorcraft_tools::params::gradient_params(g) })
+}
+
+#[test]
+fn gradient_params_round_trip_through_fill_and_swatches() {
+ let mut s = session();
+ let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ let g = three_stops();
+ s.execute("paint.setFill", &gradient_param(&g)).unwrap();
+ let got = fill_gradient(&s, id);
+ assert_eq!(got.gradient.kind, GradientKind::Freeform);
+ assert_eq!(got.gradient.stops, g.gradient.stops);
+ let (a, b) = (got.geom.unwrap(), g.geom.unwrap());
+ assert!(a.start.distance(b.start) < 1e-9 && a.end.distance(b.end) < 1e-9 && (a.aspect - b.aspect).abs() < 1e-9, "{a:?}");
+ // The default for new art keeps all but the placement (new art fits it to itself), and saving
+ // it as a swatch is lossless.
+ assert_eq!(s.paint.fill, Paint::Gradient(Box::new(GradientPaint { geom: None, ..got.clone() })));
+ let mut q = gradient_param(&g);
+ q["name"] = json!("Three");
+ s.execute("swatch.new", &q).unwrap();
+ assert_eq!(s.doc().unwrap().doc.swatch("Three").unwrap().paint, Paint::Gradient(Box::new(got)));
+}
+
+#[test]
+fn bad_gradients_are_rejected_without_editing() {
+ let mut s = session();
+ let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ let before = node(&s, id).appearance.clone();
+ let undo = s.doc().unwrap().history.undo.len();
+ for bad in [
+ json!({"stops": [{"offset": 0, "color": "#ff0000"}]}),
+ json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1}]}),
+ json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"color": "#000000"}]}),
+ json!({"stops": [{"offset": "a", "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]}),
+ json!({"stops": "red"}),
+ json!({"kind": "conic"}),
+ json!({"start": [0, 0]}),
+ json!({"aspect": "wide"}),
+ ] {
+ assert!(s.execute("paint.setFill", &json!({ "gradient": bad })).is_err(), "accepted {bad}");
+ // `start` isn't a paint.editGradient param (it would just apply the gradient).
+ if bad.get("start").is_none() {
+ assert!(s.execute("paint.editGradient", &bad).is_err(), "editGradient accepted {bad}");
+ }
+ }
+ assert_eq!(node(&s, id).appearance, before);
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+}
+
+#[test]
+fn stop_opacity_and_offsets_are_normalised() {
+ let mut s = session();
+ let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ s.execute(
+ "paint.setFill",
+ &json!({"gradient": {"stops": [{"offset": 1.5, "color": "#000000", "opacity": 50}, {"offset": -1, "color": "#ffffff", "opacity": 0.25, "midpoint": 0.99}]}}),
+ )
+ .unwrap();
+ let g = fill_gradient(&s, id);
+ // Sorted, offsets clamped, 0..100 opacity normalised, midpoint clamped to the diamond's range.
+ let st = &g.gradient.stops;
+ assert_eq!((st[0].offset, st[0].opacity, st[0].midpoint), (0.0, 0.25, 0.87));
+ assert_eq!((st[1].offset, st[1].opacity), (1.0, 0.5));
+ assert!(g.geom.is_none());
+}
+
+#[test]
+fn geometry_and_aspect_in_one_call() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
+ s.execute("paint.setFill", &json!({"gradient": {"kind": "radial", "start": [200, 150], "end": [260, 150], "aspect": 40}})).unwrap();
+ let geom = fill_gradient(&s, id).geom.unwrap();
+ assert_eq!((geom.start, geom.end), (Point::new(200.0, 150.0), Point::new(260.0, 150.0)));
+ assert!((geom.aspect - 0.4).abs() < 1e-9);
+ // An aspect without a vector places the gradient on the object's bounds so the aspect sticks.
+ s.execute("paint.setStroke", &json!({"gradient": {"kind": "radial", "aspect": 25}})).unwrap();
+ let Paint::Gradient(sg) = node(&s, id).appearance.stroke_paint() else { panic!() };
+ let geom = sg.geom.unwrap();
+ assert_eq!(geom.start, Point::new(200.0, 150.0));
+ assert!((geom.aspect - 0.25).abs() < 1e-9 && (geom.length() - 100.5).abs() < 1e-9, "fits the stroke-inflated bounds: {geom:?}");
+ // appearance.setItem takes the same gradient object.
+ let g = three_stops();
+ let mut q = gradient_param(&g);
+ q["index"] = json!(0);
+ s.execute("appearance.setItem", &q).unwrap();
+ assert_eq!(fill_gradient(&s, id).gradient, g.gradient);
+}
+
+// ---------- M3.15: gradients follow every transform ----------
+
+fn fill_geom(s: &Session, id: NodeId) -> GradientGeom {
+ fill_gradient(s, id).geom.expect("placed")
+}
+
+#[test]
+fn rotate_reflect_and_scale_carry_unplaced_gradients() {
+ let mut s = session();
+ let id = rect(&mut s, 0.0, 0.0, 100.0, 50.0);
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ s.execute("object.move", &json!({"dx": 10, "dy": 0})).unwrap();
+ assert!(fill_gradient(&s, id).geom.is_none(), "a move keeps refitting");
+ s.execute("object.rotate", &json!({"angle": 90})).unwrap();
+ let g = fill_geom(&s, id);
+ assert!((g.end.x - g.start.x).abs() < 1e-9 && (g.length() - 100.0).abs() < 1e-9, "vertical after a 90° turn: {g:?}");
+ s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
+ let r = fill_geom(&s, id);
+ // The vertical vector is centred on the object, so the reflection swaps its ends.
+ assert!(r.start.distance(g.end) < 1e-9 && r.end.distance(g.start) < 1e-9, "{g:?} → {r:?}");
+
+ // A circle's radial gradient becomes an ellipse under a non-uniform scale.
+ let c = s.execute("shape.ellipse", &json!({"x": 300, "y": 300, "width": 100, "height": 100})).unwrap();
+ let c = NodeId(c["id"].as_u64().unwrap());
+ s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}})).unwrap();
+ s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
+ let e = fill_geom(&s, c);
+ assert!((e.aspect - 0.5).abs() < 1e-9 && (e.length() - 100.0).abs() < 1e-9, "{e:?}");
+}
+
+#[test]
+fn free_distort_maps_gradients_once() {
+ let mut s = session();
+ let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ // An affine distort (a sheared parallelogram) maps the gradient exactly like object.transform.
+ s.execute("object.distort", &json!({"corners": [[20, 0], [120, 0], [100, 100], [0, 100]]})).unwrap();
+ let g = fill_geom(&s, id);
+ let mut want = GradientGeom::fit(GradientKind::Linear, vectorcraft_geom::Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
+ want.transform(vectorcraft_geom::Affine::new([1.0, 0.0, -0.2, 1.0, 20.0, 0.0]), GradientKind::Linear);
+ assert!(g.start.distance(want.start) < 1e-6 && g.end.distance(want.end) < 1e-6, "{g:?} vs {want:?}");
+}
+
+// ---------- M3.16: the active proxy and type objects ----------
+
+fn text(s: &mut Session, x: f64, y: f64) -> NodeId {
+ let r = s.execute("text.create", &json!({"x": x, "y": y, "text": "Gradient", "size": 40})).unwrap();
+ NodeId(r["id"].as_u64().unwrap())
+}
+
+fn text_obj(s: &Session, id: NodeId) -> &vectorcraft_doc::TextObject {
+ match &node(s, id).kind {
+ vectorcraft_doc::NodeKind::Text(t) => t,
+ k => panic!("not text: {k:?}"),
+ }
+}
+
+fn run_gradient(p: &Paint) -> &GradientPaint {
+ match p {
+ Paint::Gradient(g) => g,
+ p => panic!("expected a gradient, got {p:?}"),
+ }
+}
+
+#[test]
+fn gradient_vector_follows_the_active_proxy_or_an_item_index() {
+ let mut s = session();
+ let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ s.execute("paint.toggleActive", &json!({})).unwrap();
+ s.execute("paint.setGradientGeom", &json!({"start": [0, 50], "end": [100, 50]})).unwrap();
+ let ap = &node(&s, id).appearance;
+ assert!(matches!(ap.fill_paint(), Paint::Solid { .. }), "the fill stays solid");
+ let Paint::Gradient(g) = ap.stroke_paint() else { panic!("the stroke proxy is in front") };
+ assert_eq!(g.geom.map(|g| (g.start, g.end)), Some((Point::new(0.0, 50.0), Point::new(100.0, 50.0))));
+ // `index` targets one appearance item (item 0 is the fill), whichever proxy is in front.
+ s.execute("paint.setGradientGeom", &json!({"start": [50, 0], "end": [50, 100], "index": 0})).unwrap();
+ assert_eq!(fill_geom(&s, id).start, Point::new(50.0, 0.0));
+ let err = s.execute("paint.setGradientGeom", &json!({"start": [0, 0], "end": [1, 1], "index": 7})).unwrap_err();
- assert!(err.to_string().contains("index 7"), "{err}");
++ assert!(err.to_string().contains("item 7"), "{err}");
+}
+
+#[test]
+fn type_objects_take_the_vector_on_their_runs_in_text_space() {
+ let mut s = session();
+ let id = text(&mut s, 100.0, 200.0);
+ s.execute("paint.setGradientGeom", &json!({"start": [100, 190], "end": [300, 190]})).unwrap();
+ let t = text_obj(&s, id);
+ let geom = run_gradient(&t.runs[0].style.fill).geom.unwrap();
+ // Text space starts at the first baseline (100, 200).
+ assert!(geom.start.distance(Point::new(0.0, -10.0)) < 1e-9 && geom.end.distance(Point::new(200.0, -10.0)) < 1e-9, "{geom:?}");
+ // The annotator reads it back in document coordinates, and it turns with the text.
- let (_, doc) = node(&s, id).proxy_gradient(false).unwrap();
++ let (_, doc) = node(&s, id).proxy_gradient(false, None).unwrap();
+ assert!(doc.start.distance(Point::new(100.0, 190.0)) < 1e-9, "{doc:?}");
+ s.execute("object.rotate", &json!({"angle": 90, "origin": [100, 200]})).unwrap();
- let (_, doc) = node(&s, id).proxy_gradient(false).unwrap();
++ let (_, doc) = node(&s, id).proxy_gradient(false, None).unwrap();
+ assert!(doc.start.distance(Point::new(90.0, 200.0)) < 1e-9 && doc.end.distance(Point::new(90.0, 0.0)) < 1e-9, "{doc:?}");
+ // paint.setFill's vector is in document coordinates too.
+ s.execute("paint.setFill", &json!({"gradient": {"start": [90, 200], "end": [90, 100]}})).unwrap();
- let (_, doc) = node(&s, id).proxy_gradient(false).unwrap();
++ let (_, doc) = node(&s, id).proxy_gradient(false, None).unwrap();
+ assert!(doc.end.distance(Point::new(90.0, 100.0)) < 1e-9, "{doc:?}");
+}
+
+#[test]
+fn aspect_works_on_type_and_run_strokes_fit_the_inflated_box() {
+ let mut s = session();
+ let id = text(&mut s, 100.0, 200.0);
+ s.execute("paint.editGradient", &json!({"kind": "radial", "aspect": 50, "stroke": false})).unwrap();
+ let t = text_obj(&s, id);
+ let lb = t.local_bounds();
+ let geom = run_gradient(&t.runs[0].style.fill).geom.expect("an aspect places the gradient");
+ assert!((geom.aspect - 0.5).abs() < 1e-9 && geom.start.distance(lb.center()) < 1e-9, "{geom:?} on {lb:?}");
+ // A stroke gradient fits the layout box grown by half the run's stroke weight.
+ s.execute("paint.setStroke", &json!({"gradient": {}})).unwrap();
+ s.execute("paint.editGradient", &json!({"kind": "radial", "aspect": 200, "stroke": true})).unwrap();
+ let t = text_obj(&s, id);
+ let w = t.runs[0].style.stroke_width;
+ let geom = run_gradient(&t.runs[0].style.stroke).geom.unwrap();
+ assert!((geom.length() - (lb.width().max(lb.height()) + w) / 2.0).abs() < 1e-9, "{geom:?}");
+ // The Stroke proxy's vector lands on the runs' strokes.
+ s.execute("paint.setGradientGeom", &json!({"start": [100, 190], "end": [150, 190], "stroke": true})).unwrap();
- let (g, doc) = node(&s, id).proxy_gradient(true).unwrap();
++ let (g, doc) = node(&s, id).proxy_gradient(true, None).unwrap();
+ assert!(doc.end.distance(Point::new(150.0, 190.0)) < 1e-9 && (doc.aspect - 2.0).abs() < 1e-9, "aspect kept: {doc:?}");
+ assert_eq!(g.gradient.kind, GradientKind::Radial);
+}
+
+// ---------- M3.17: the interactive annotator ----------
+
+/// A 100 × 100 rectangle at (100, 100) with a horizontal fill gradient across it, and the
+/// Gradient tool.
+fn annotated() -> (Session, NodeId) {
+ let mut s = session();
+ let id = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"gradient": {"start": [100, 150], "end": [200, 150]}})).unwrap();
+ s.select_tool("gradient", crate::ViewInfo::default()).unwrap();
+ (s, id)
+}
+
+fn gesture(s: &mut Session, events: &[(PointerKind, f64, f64)]) {
+ for (k, x, y) in events {
+ s.pointer(&PointerEvent::new(*k, *x, *y), crate::ViewInfo::default()).unwrap();
+ }
+}
+
+fn stop_count(s: &Session, id: NodeId) -> usize {
+ fill_gradient(s, id).gradient.stops.len()
+}
+
+#[test]
+fn select_stop_is_validated_and_shared() {
+ let (mut s, _) = annotated();
+ assert_eq!(s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(), json!({"index": 1}));
+ assert_eq!(s.selected_stop(), Some(1));
+ assert!(s.execute("gradient.selectStop", &json!({"index": 2})).is_err(), "two stops");
+ assert!(s.execute("gradient.selectStop", &json!({"index": "a"})).is_err());
+ assert!(s.execute("gradient.selectStop", &json!({})).is_err());
+ s.execute("gradient.selectStop", &json!({"index": null})).unwrap();
+ assert_eq!(s.selected_stop(), None);
+ // The stroke proxy's paint is solid: nothing to select there.
+ s.execute("paint.toggleActive", &json!({})).unwrap();
+ assert!(s.execute("gradient.selectStop", &json!({"index": 0})).is_err());
+}
+
+#[test]
+fn annotator_gestures_edit_the_gradient_as_single_undo_steps() {
+ let (mut s, id) = annotated();
+ // A click on the bar adds a stop there and selects it.
+ gesture(&mut s, &[(PointerKind::Down, 130.0, 150.0), (PointerKind::Up, 130.0, 150.0)]);
+ let stops = fill_gradient(&s, id).gradient.stops;
+ assert_eq!(stops.len(), 3);
+ assert!((stops[1].offset - 0.3).abs() < 1e-6);
+ assert_eq!(s.selected_stop(), Some(1));
+ // Dragging the end handle changes only the end, as one undo step.
+ let undo = s.doc().unwrap().history.undo.len();
+ gesture(
+ &mut s,
+ &[(PointerKind::Down, 200.0, 150.0), (PointerKind::Drag, 210.0, 160.0), (PointerKind::Drag, 220.0, 170.0), (PointerKind::Up, 220.0, 170.0)],
+ );
+ let g = fill_geom(&s, id);
+ assert_eq!((g.start, g.end), (Point::new(100.0, 150.0), Point::new(220.0, 170.0)));
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
+ s.execute("edit.undo", &json!({})).unwrap();
+ // The selected stop takes Delete ahead of edit.clear; the object stays.
+ let view = crate::ViewInfo::default();
+ assert!(s.tool_claims_key(ToolKey::Delete, view));
+ s.tool_key(ToolKey::Delete, Mods::default(), view).unwrap();
+ assert_eq!(stop_count(&s, id), 2);
+ assert_eq!(s.selected_stop(), Some(1));
+ // Never below two stops.
+ s.tool_key(ToolKey::Backspace, Mods::default(), view).unwrap();
+ assert_eq!(stop_count(&s, id), 2);
+ assert!(s.doc().unwrap().doc.node(id).is_some());
+}
+
+#[test]
+fn the_selected_stop_belongs_to_its_gradient() {
+ let (mut s, a) = annotated();
+ let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
+ s.execute("gradient.selectStop", &json!({"index": 1})).unwrap();
+ let view = crate::ViewInfo::default();
+ assert!(s.tool_claims_key(ToolKey::Delete, view));
+ // Other art selected: no stop is selected there, so Delete is not the tool's.
+ s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
+ assert_eq!(s.selected_stop(), None);
+ assert!(!s.tool_claims_key(ToolKey::Delete, view));
+ // Back on the art it was selected on, it is selected again; the other proxy has none.
+ s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
+ assert_eq!(s.selected_stop(), Some(1));
+ s.execute("paint.toggleActive", &json!({})).unwrap();
+ assert_eq!(s.selected_stop(), None);
+}
+
+#[test]
+fn swatches_and_new_art_fit_a_placed_gradient_to_themselves() {
+ let mut s = session();
+ rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ let mut g = three_stops();
+ g.gradient.kind = GradientKind::Radial;
+ let mut q = gradient_param(&g);
+ s.execute("paint.setFill", &q).unwrap();
+ q["name"] = json!("Placed");
+ s.execute("swatch.new", &q).unwrap();
+ // New art drawn elsewhere fits the gradient to itself rather than to the first rectangle.
+ let b = rect(&mut s, 500.0, 300.0, 100.0, 100.0);
+ assert_eq!(fill_gradient(&s, b).geom, None);
+ // Applying the swatch fits its gradient to each object, keeping the aspect it was saved with.
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.execute("paint.setFill", &json!({"swatch": "Placed"})).unwrap();
+ let geom = fill_geom(&s, b);
+ assert_eq!(geom.start, Point::new(550.0, 350.0));
+ assert!((geom.aspect - 0.5).abs() < 1e-9 && (geom.length() - 50.0).abs() < 1e-9, "{geom:?}");
+ // On type, in text space.
+ let t = text(&mut s, 100.0, 400.0);
+ s.execute("paint.setFill", &json!({"swatch": "Placed"})).unwrap();
- let (_, doc) = node(&s, t).proxy_gradient(false).unwrap();
++ let (_, doc) = node(&s, t).proxy_gradient(false, None).unwrap();
+ let tb = node(&s, t).geometric_bounds().unwrap();
+ assert!(doc.start.distance(tb.center()) < 1e-9 && (doc.aspect - 0.5).abs() < 1e-9, "{doc:?} on {tb:?}");
+}
diff --cc crates/engine/src/tooling.rs
index d0ca84df6,2ea533d72..9f040abc9
--- a/crates/engine/src/tooling.rs
+++ b/crates/engine/src/tooling.rs
@@@ -78,8 -78,7 +78,9 @@@ impl Session
snap_to_pixel: view.snap_to_pixel,
snap_to_point: view.snap_to_point,
corner_widgets: view.corner_widgets,
+ fill_active: self.fill_active,
+ gradient_stop: self.selected_stop(),
+ appearance_item: self.appearance_item(),
};
f(self.tool.as_mut(), &cx)
}
diff --cc crates/render/src/lib.rs
index 19579ef7b,874581271..9538d6236
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@@ -805,7 -811,7 +811,7 @@@ impl Renderer
ctx.set_fill_rule(peniko::Fill::NonZero);
ctx.fill_path(&all);
}
- AppearanceItem::Stroke(st) if st.visible && st.width > 0.0 && paint::set_paint(ctx, &st.paint, st.paint_bounds(tb), f.doc) => {
- AppearanceItem::Stroke(st) if st.width > 0.0 && paint::set_paint(ctx, &st.paint, tb, f.doc) => {
++ AppearanceItem::Stroke(st) if st.width > 0.0 && paint::set_paint(ctx, &st.paint, st.paint_bounds(tb), f.doc) => {
ctx.set_stroke(kurbo::Stroke::new(st.width));
ctx.stroke_path(&all);
}
diff --cc crates/tools/src/lib.rs
index f0f6c0a1c,0dd321781..605403fe0
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@@ -156,10 -155,9 +156,13 @@@ pub struct ToolContext<'a>
pub snap_to_point: bool,
/// View → Show Corner Widget: live rectangles show draggable Live Corners widgets.
pub corner_widgets: bool,
+ /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits.
+ pub fill_active: bool,
+ /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator.
+ pub gradient_stop: Option<usize>,
+ /// The Appearance panel's active fill/stroke (paint-order index into the first selected
+ /// object's stack); paint tools show and edit that item.
+ pub appearance_item: Option<usize>,
}
impl ToolContext<'_> {
@@@ -340,8 -327,7 +343,9 @@@ pub(crate) mod testutil
snap_to_pixel: false,
snap_to_point: true,
corner_widgets: true,
+ fill_active: true,
+ gradient_stop: None,
+ appearance_item: None,
}
}
}
diff --cc crates/tools/src/xform/eyedropper.rs
index 71891418e,8c4bca488..ef6d7e84c
--- a/crates/tools/src/xform/eyedropper.rs
+++ b/crates/tools/src/xform/eyedropper.rs
@@@ -42,11 -45,15 +42,11 @@@ impl Tool for EyedropperTool
let src = paint_owner(cx.doc, h.leaf);
let Some(n) = cx.doc.node(src) else { return vec![] };
if ev.mods.shift {
- let fill_none = n.proxy_paint(false).is_none_or(|(p, ..)| p.is_none());
- let Some((paint, to_doc, bounds)) = n.proxy_paint(h.kind == HitKind::Stroke || fill_none) else { return vec![] };
- let (fill, stroke) = match &n.kind {
- vectorcraft_doc::NodeKind::Text(t) => {
- let st = t.runs.first().map(|r| r.style.clone());
- (st.as_ref().map(|s| s.fill.clone()).unwrap_or_default(), st.map(|s| s.stroke).unwrap_or_default())
- }
- _ => (n.appearance.fill_paint(), n.appearance.stroke_paint()),
- };
- let paint = if h.kind == HitKind::Stroke || fill.is_none() { stroke } else { fill };
- return match paint_color_at(&paint, n.geometric_bounds(), ev.pos) {
++ let fill_none = n.proxy_paint(false, None).is_none_or(|(p, ..)| p.is_none());
++ let Some((paint, to_doc, bounds)) = n.proxy_paint(h.kind == HitKind::Stroke || fill_none, None) else { return vec![] };
+ // Sample in the paint's own space (text space for type runs) and box.
+ let p = if to_doc.determinant().abs() > 1e-12 { to_doc.inverse() * ev.pos } else { ev.pos };
+ return match paint_color_at(paint, Some(bounds), p) {
Some(c) => vec![Action::Exec("paint.sampleColor".into(), json!({ "color": c.to_hex() }))],
None => vec![],
};
diff --cc crates/tools/src/xform/gradient.rs
index 8c4cc1888,af6cfb98b..2c823f0f8
--- a/crates/tools/src/xform/gradient.rs
+++ b/crates/tools/src/xform/gradient.rs
@@@ -26,325 -16,85 +26,329 @@@ use crate::{Action, Cursor, Mods, Overl
const BAR: [u8; 3] = [0x20, 0x20, 0x20];
const LIGHT: [u8; 3] = [0xf0, 0xf0, 0xf0];
-#[derive(Default)]
-pub struct GradientTool {
- drag: Option<(Point, Point, bool)>,
+// Annotator layout and hit radii, in screen pixels.
+/// Start and end handles.
+const HANDLE: f64 = 5.0;
+/// The rotate zone reaches this far past the end handle.
+const ROTATE: f64 = 14.0;
+/// Stop chips sit this far below the bar.
+const STOP_GAP: f64 = 10.0;
+const STOP_HIT: f64 = 6.0;
+/// Midpoint diamonds sit this far above the bar.
+const MID_GAP: f64 = 7.0;
+const MID_HIT: f64 = 5.0;
+/// The bar (where a click adds a stop) reaches this far above it, and down through the stop row.
+const BAR_HIT: f64 = 4.0;
+/// A stop dragged farther than this from the bar is deleted on release.
+const OFF_BAR: f64 = 24.0;
+/// A press becomes a drag after this much movement.
+const DRAG_START: f64 = 3.0;
+/// Arrow-key nudges of the selected stop (Shift: the big step).
+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.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Annotator {
+ pub geom: GradientGeom,
+ pub gradient: Gradient,
}
-/// Start/end/stop offsets of the gradient annotator for the first selected object with a gradient
-/// in the Appearance panel's active item (when it is one), else in its fill.
-pub fn annotator(cx: &ToolContext) -> Option<(Point, Point, Vec<f32>)> {
- cx.selection.objects.iter().find_map(|id| {
- let n = cx.doc.node(*id)?;
- let paint = match cx.appearance_item.and_then(|i| n.appearance.items.get(i)) {
- Some(item) => item.paint(),
- None => &n.appearance.fill()?.paint,
- };
- let Paint::Gradient(g) = paint else { return None };
- let geom = g.resolve(n.geometric_bounds()?);
- Some((geom.start, geom.end, g.gradient.stops.iter().map(|s| s.offset).collect()))
- })
+/// A part of the annotator.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Part {
+ Stop(usize),
+ /// The midpoint diamond after stop `i`.
+ Mid(usize),
+ Start,
+ End,
+ /// Just past the end: rotates the vector about the start.
+ Rotate,
+ /// The bar at an offset (0..1): a click adds a stop there.
+ Bar(f32),
+}
+
+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)?;
++ let (g, geom) = cx.doc.node(*id)?.proxy_gradient(!cx.fill_active, cx.appearance_item)?;
+ Some(Self { geom, gradient: g.gradient.clone() })
+ })
+ }
+ /// An annotator showing `stops` on `geom` (the state a drag started from).
+ fn with(geom: GradientGeom, stops: &[GradientStop]) -> Self {
+ Self { geom, gradient: Gradient { kind: GradientKind::Linear, stops: stops.to_vec() } }
+ }
+ fn vector(&self) -> Vec2 {
+ self.geom.end - self.geom.start
+ }
+ /// The point at offset `t` along the bar.
+ pub fn at(&self, t: f64) -> Point {
+ self.geom.start + self.vector() * t
+ }
+ /// Unit normal to the bar, towards the stop row.
+ fn normal(&self) -> Vec2 {
+ let v = self.vector();
+ let len = v.hypot();
+ if len < 1e-12 { Vec2::new(0.0, 1.0) } else { Vec2::new(-v.y, v.x) / len }
+ }
+ /// Where stop `i`'s chip sits.
+ pub fn stop_point(&self, cx: &ToolContext, i: usize) -> Option<Point> {
+ let s = self.gradient.stops.get(i)?;
+ Some(self.at(s.offset as f64) + self.normal() * cx.tol(STOP_GAP))
+ }
+ /// Where the midpoint diamond after stop `i` sits.
+ pub fn mid_point(&self, cx: &ToolContext, i: usize) -> Option<Point> {
+ Some(self.at(midpoint_pos(&self.gradient.stops, i)? as f64) - self.normal() * cx.tol(MID_GAP))
+ }
+ /// `p` as (offset along the bar, signed distance from it towards the stop row).
+ fn project(&self, p: Point) -> (f64, f64) {
+ let v = self.vector();
+ let l2 = v.hypot2();
+ let d = p - self.geom.start;
+ if l2 < 1e-18 {
+ return (0.0, d.hypot());
+ }
+ (d.dot(v) / l2, d.dot(self.normal()))
+ }
+ /// The part under `p`: stops, then midpoints, the handles, the rotate zone and the bar.
+ pub fn hit(&self, cx: &ToolContext, p: Point) -> Option<Part> {
+ let near = |q: Option<Point>, r: f64| q.is_some_and(|q| q.distance(p) <= cx.tol(r));
+ let n = self.gradient.stops.len();
+ // The topmost (last drawn) chip wins where chips overlap.
+ if let Some(i) = (0..n).rev().find(|i| near(self.stop_point(cx, *i), STOP_HIT)) {
+ return Some(Part::Stop(i));
+ }
+ if let Some(i) = (0..n.saturating_sub(1)).find(|i| near(self.mid_point(cx, *i), MID_HIT)) {
+ return Some(Part::Mid(i));
+ }
+ if near(Some(self.geom.end), HANDLE) {
+ return Some(Part::End);
+ }
+ if near(Some(self.geom.start), HANDLE) {
+ return Some(Part::Start);
+ }
+ let (t, d) = self.project(p);
+ if t > 1.0 && near(Some(self.geom.end), ROTATE) {
+ return Some(Part::Rotate);
+ }
+ let across = -cx.tol(BAR_HIT)..=cx.tol(STOP_GAP + STOP_HIT);
+ if self.vector().hypot() > 1e-12 && (0.0..=1.0).contains(&t) && across.contains(&d) {
+ return Some(Part::Bar(t as f32));
+ }
+ None
+ }
+}
+
+/// What a press grabbed.
+#[derive(Clone, Debug, PartialEq)]
+enum Grab {
+ /// The art (or empty canvas): a click applies the gradient from there, a drag draws a vector.
+ Art,
+ /// The start handle or the bar: a drag moves the gradient (a click on the bar adds a stop).
+ Move {
+ geom: GradientGeom,
+ bar: Option<f32>,
+ },
+ End(GradientGeom),
+ Rotate(GradientGeom),
+ Stop {
+ index: usize,
+ from: Annotator,
+ copy: bool,
+ },
+ Mid {
+ index: usize,
+ from: Annotator,
+ },
}
-fn annotator_overlays(cx: &ToolContext, a: Point, b: Point, stops: &[f32]) -> Vec<Overlay> {
+#[derive(Clone, Debug, PartialEq)]
+struct Gesture {
+ grab: Grab,
+ /// Where the press happened.
+ at: Point,
+ /// Moved past the drag threshold (an interaction is open).
+ began: bool,
+ /// The vector drawn so far (Art drags).
+ vector: Option<(Point, Point)>,
+ /// Where a dragged stop ends up (selected on release): its index, or None while it is dragged
+ /// off the bar.
+ stop: Option<Option<usize>>,
+}
+
+#[derive(Default)]
+pub struct GradientTool {
+ gesture: Option<Gesture>,
+}
+
+/// Overlays of an annotator: the bar, the handles, the midpoint diamonds and a chip per stop.
+fn annotator_overlays(cx: &ToolContext, a: &Annotator) -> Vec<Overlay> {
+ let (s, e) = (a.geom.start, a.geom.end);
+ let shade = Vec2::new(0.0, cx.tol(1.0));
let mut o = vec![
- Overlay::Line { a, b, color: BAR, dashed: false },
- Overlay::Line { a: a + Vec2::new(0.0, cx.tol(1.0)), b: b + Vec2::new(0.0, cx.tol(1.0)), color: LIGHT, dashed: false },
- Overlay::Handle { p: a, color: BAR },
- Overlay::Anchor { p: b, color: BAR, filled: true, size: 7.0 },
+ Overlay::Line { a: s, b: e, color: BAR, dashed: false },
+ Overlay::Line { a: s + shade, b: e + shade, color: LIGHT, dashed: false },
+ Overlay::Handle { p: s, color: BAR },
+ Overlay::Anchor { p: e, color: BAR, filled: true, size: 7.0 },
];
- let v = b - a;
- let len = v.hypot();
- if len > 1e-9 {
- let n = Vec2::new(-v.y, v.x) / len * cx.tol(6.0);
- for s in stops {
- let p = a + v * *s as f64;
- o.push(Overlay::Line { a: p, b: p + n, color: BAR, dashed: false });
- }
+ let len = a.vector().hypot();
+ if len < 1e-12 {
+ return o;
+ }
+ let r = cx.tol(4.0);
+ let (along, across) = (a.vector() / len * r, a.normal() * r);
+ for i in 0..a.gradient.stops.len().saturating_sub(1) {
+ let Some(c) = a.mid_point(cx, i) else { continue };
+ let path = super::polygon(&[c - along, c - across, c + along, c + across], true);
+ o.push(Overlay::Path { path, color: BAR, width: 1.0, dashed: false });
+ }
+ for (i, st) in a.gradient.stops.iter().enumerate() {
+ let Some(p) = a.stop_point(cx, i) else { continue };
+ o.push(Overlay::Line { a: a.at(st.offset as f64), b: p, color: BAR, dashed: false });
+ o.push(Overlay::Swatch { p, color: st.color.to_rgba8(st.opacity), selected: cx.gradient_stop == Some(i) });
}
o
}
-impl Tool for GradientTool {
- fn id(&self) -> &'static str {
- "gradient"
+/// The vector a click applies to `id`: its current gradient's, else the default fit on its box.
+fn click_vector(cx: &ToolContext, id: NodeId) -> Option<Vec2> {
+ let stroke = !cx.fill_active;
+ let n = cx.doc.node(id)?;
- if let Some((_, g)) = n.proxy_gradient(stroke) {
++ if let Some((_, g)) = n.proxy_gradient(stroke, cx.appearance_item) {
+ return Some(g.end - g.start);
}
- let (to_doc, b) = match n.proxy_paint(stroke) {
++ let (to_doc, b) = match n.proxy_paint(stroke, cx.appearance_item) {
+ Some((_, a, b)) => (a, b),
+ None => (Affine::IDENTITY, n.geometric_bounds()?),
+ };
+ let mut g = GradientGeom::fit(GradientKind::Linear, b, 0.0);
+ g.transform(to_doc, GradientKind::Linear);
+ Some(g.end - g.start)
+}
- fn busy(&self) -> bool {
- self.drag.is_some_and(|d| d.2)
+impl GradientTool {
+ fn geom_params(cx: &ToolContext, start: Point, end: Point) -> Value {
+ json!({ "start": [start.x, start.y], "end": [end.x, end.y], "stroke": !cx.fill_active })
+ }
+ fn stops_params(cx: &ToolContext, stops: &[GradientStop]) -> Value {
+ json!({ "stops": crate::params::stops_json(stops), "stroke": !cx.fill_active })
+ }
+ fn select_stop(i: usize) -> Action {
+ Action::Exec("gradient.selectStop".into(), json!({ "index": i }))
}
- fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
- let p = ev.pos;
- match ev.kind {
- PointerKind::Down => {
- let mut out = vec![];
+ fn press(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {
+ let annotator = Annotator::of(cx);
+ let mut out = vec![];
+ let grab = match annotator.as_ref().and_then(|a| a.hit(cx, p).map(|part| (a, part))) {
+ Some((a, Part::Stop(index))) => {
+ out.push(Self::select_stop(index));
+ Grab::Stop { index, from: a.clone(), copy: mods.alt }
+ }
+ Some((a, Part::Mid(index))) => Grab::Mid { index, from: a.clone() },
+ Some((a, Part::Start)) => Grab::Move { geom: a.geom, bar: None },
+ Some((a, Part::Bar(t))) => Grab::Move { geom: a.geom, bar: Some(t) },
+ Some((a, Part::End)) => Grab::End(a.geom),
+ Some((a, Part::Rotate)) => Grab::Rotate(a.geom),
+ None => {
if cx.selection.is_empty() {
let Some(h) = hit_test(cx.doc, p, cx.hit_options()) else { return out };
- let id = paint_owner(cx.doc, h.leaf);
- out.push(Action::Exec("select.set".into(), json!({ "ids": [id.0] })));
+ out.push(Action::Exec("select.set".into(), json!({ "ids": [paint_owner(cx.doc, h.leaf).0] })));
}
- self.drag = Some((p, p, false));
- out
+ Grab::Art
}
- PointerKind::Drag => {
- let Some((start, _, began)) = self.drag else { return vec![] };
- let mut out = vec![];
- if !began {
- if p.distance(start) < cx.tol(3.0) {
- return out;
+ };
+ self.gesture = Some(Gesture { grab, at: p, began: false, vector: None, stop: None });
+ out
+ }
+
+ fn drag(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> Vec<Action> {
+ let Some(g) = &mut self.gesture 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()));
+ }
+ let snap = |from: Point, to: Point| if mods.shift { from + vectorcraft_geom::constrain_angle(to - from, 45.0) } else { to };
+ let (cmd, params) = match &g.grab {
+ Grab::Art => {
+ let end = snap(g.at, p);
+ g.vector = Some((g.at, end));
+ ("paint.setGradientGeom", Self::geom_params(cx, g.at, end))
+ }
+ Grab::Move { geom, .. } => {
+ let d = p - g.at;
+ ("paint.setGradientGeom", Self::geom_params(cx, geom.start + d, geom.end + d))
+ }
+ Grab::End(geom) => ("paint.setGradientGeom", Self::geom_params(cx, geom.start, snap(geom.start, p))),
+ Grab::Rotate(geom) => {
+ let dir = snap(geom.start, p) - geom.start;
+ let len = dir.hypot();
+ let end = if len < 1e-12 { geom.end } else { geom.start + dir * (geom.length() / len) };
+ ("paint.setGradientGeom", Self::geom_params(cx, geom.start, end))
+ }
+ Grab::Stop { index, from, copy } => {
+ let (t, d) = from.project(p);
+ let t = t.clamp(0.0, 1.0) as f32;
+ let stops = &from.gradient.stops;
+ let removed = (!copy && d.abs() > cx.tol(OFF_BAR)).then(|| remove_stop(stops, *index)).flatten();
+ let (stops, at) = match removed {
+ Some(v) => (v, None),
+ None => {
+ let (v, i) = if *copy { duplicate_stop(stops, *index, t) } else { move_stop(stops, *index, t) };
+ (v, Some(i))
}
- out.push(Action::Begin("Gradient".into()));
+ };
+ g.stop = Some(at);
+ ("paint.editGradient", Self::stops_params(cx, &stops))
+ }
+ Grab::Mid { index, from } => {
+ let stops = &from.gradient.stops;
+ let m = midpoint_from_pos(stops, *index, from.project(p).0.clamp(0.0, 1.0) as f32).unwrap_or(0.5);
+ ("paint.editGradient", Self::stops_params(cx, &set_midpoint(stops, *index, m)))
+ }
+ };
+ out.push(Action::Preview(cmd.into(), params));
+ out
+ }
+
+ fn release(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
+ let Some(g) = self.gesture.take() else { return vec![] };
+ if g.began {
+ let mut out = vec![Action::Commit];
+ match (g.grab, g.stop) {
+ (Grab::Stop { .. }, Some(Some(i))) => out.push(Self::select_stop(i)),
+ // Dragged off the bar: the stop that slid into its place is selected.
+ (Grab::Stop { index, from, .. }, Some(None)) => out.push(Self::select_stop(index.min(from.gradient.stops.len() - 2))),
+ _ => {}
+ }
+ return out;
+ }
+ match g.grab {
+ // A click on the bar adds a stop there.
+ Grab::Move { bar: Some(t), .. } => {
+ let Some(a) = Annotator::of(cx) else { return vec![] };
+ let (stops, i) = insert_stop(&a.gradient, t);
+ vec![Action::Exec("paint.editGradient".into(), Self::stops_params(cx, &stops)), Self::select_stop(i)]
+ }
+ // A click inside selected art applies the gradient from that point.
+ Grab::Art => {
+ let Some(h) = hit_test(cx.doc, p, cx.hit_options()) else { return vec![] };
+ let id = paint_owner(cx.doc, h.leaf);
+ let Some(v) = cx.selection.objects.contains(&id).then(|| click_vector(cx, id)).flatten() else { return vec![] };
+ let mut params = Self::geom_params(cx, p, p + v);
+ params["ids"] = json!([id.0]);
++ // With `ids` the engine edits the topmost fill or stroke unless an item is named.
++ if let Some(i) = cx.doc.node(id).and_then(|n| n.appearance.item_of_kind(cx.appearance_item, cx.fill_active)) {
++ params["item"] = json!(i);
+ }
- let end = if ev.mods.shift { start + vectorcraft_geom::constrain_angle(p - start, 45.0) } else { p };
- self.drag = Some((start, end, true));
- out.push(Action::Preview("paint.setGradientGeom".into(), json!({ "start": [start.x, start.y], "end": [end.x, end.y] })));
- out
+ vec![Action::Exec("paint.setGradientGeom".into(), params)]
}
- PointerKind::Up => match self.drag.take() {
- Some((_, _, true)) => vec![Action::Commit],
- _ => vec![],
- },
_ => vec![],
}
}
@@@ -548,155 -162,21 +552,180 @@@ mod tests
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 450.0, 450.0)).is_empty());
}
+ #[test]
+ fn the_end_handle_changes_only_the_end_and_the_start_moves_both() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let mut t = GradientTool::default();
+ t.pointer(&cx, &ev(PointerKind::Down, Point::new(200.0, 150.0)));
+ let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(220.0, 170.0)))).clone();
+ assert_eq!((point(&v["start"]), point(&v["end"])), (Point::new(100.0, 150.0), Point::new(220.0, 170.0)));
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, Point::new(220.0, 170.0))), vec![Action::Commit]);
+ // The start handle moves the whole vector.
+ t.pointer(&cx, &ev(PointerKind::Down, Point::new(100.0, 150.0)));
+ let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(110.0, 140.0)))).clone();
+ assert_eq!((point(&v["start"]), point(&v["end"])), (Point::new(110.0, 140.0), Point::new(210.0, 140.0)));
+ }
+
+ #[test]
+ fn past_the_end_rotates_and_shift_snaps() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let mut t = GradientTool::default();
+ assert_eq!(t.cursor(&cx, Point::new(210.0, 151.0), Mods::default()), Cursor::Rotate);
+ t.pointer(&cx, &ev(PointerKind::Down, Point::new(210.0, 151.0)));
+ let end = point(&preview(&t.pointer(&cx, &with(SHIFT, ev(PointerKind::Drag, Point::new(103.0, 60.0)))))["end"]);
+ // Snapped to straight up, keeping the 100 pt length.
+ assert!(end.distance(Point::new(100.0, 50.0)) < 1e-9, "{end:?}");
+ }
+
+ #[test]
+ fn a_bar_click_adds_a_stop_and_selects_it() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let mut t = GradientTool::default();
+ assert_eq!(t.cursor(&cx, Point::new(130.0, 150.0), Mods::default()), Cursor::AddStop);
+ assert!(t.pointer(&cx, &ev(PointerKind::Down, Point::new(130.0, 150.0))).is_empty());
+ let a = t.pointer(&cx, &ev(PointerKind::Up, Point::new(130.0, 150.0)));
+ let (c, v) = exec(&a[0]);
+ assert_eq!((c, offsets(v)), ("paint.editGradient", vec![0.0, 30.0, 100.0]));
+ assert_eq!(a[1], GradientTool::select_stop(1));
+ }
+
+ #[test]
+ fn stops_drag_along_the_bar_off_it_to_delete_and_alt_copies() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let chip = Annotator::of(&cx).unwrap().stop_point(&cx, 0).unwrap();
+ let mut t = GradientTool::default();
+ // Pressing a stop selects it; dragging moves it.
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, chip)), vec![GradientTool::select_stop(0)]);
+ assert_eq!(offsets(preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(140.0, chip.y))))), vec![40.0, 100.0]);
+ assert_eq!(t.cursor(&cx, chip, Mods::default()), Cursor::Move);
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, Point::new(140.0, chip.y))), vec![Action::Commit, GradientTool::select_stop(0)]);
+ // Two stops never lose one: dragged off the bar, the stop stays.
+ t.pointer(&cx, &ev(PointerKind::Down, chip));
+ assert_eq!(offsets(preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(100.0, 260.0))))), vec![0.0, 100.0]);
+ t.pointer(&cx, &ev(PointerKind::Up, Point::new(100.0, 260.0)));
+ // Alt-drag leaves the original and drags a copy.
+ t.pointer(&cx, &with(ALT, ev(PointerKind::Down, chip)));
+ assert_eq!(offsets(preview(&t.pointer(&cx, &with(ALT, ev(PointerKind::Drag, Point::new(150.0, chip.y)))))), vec![0.0, 50.0, 100.0]);
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, Point::new(150.0, chip.y))), vec![Action::Commit, GradientTool::select_stop(1)]);
+
+ // With three stops, dragging the middle one off the bar deletes it.
+ let (d, s) = graded(three());
+ let cx = crate::testutil::cx(&d, &s, &p);
+ let chip = Annotator::of(&cx).unwrap().stop_point(&cx, 1).unwrap();
+ t.pointer(&cx, &ev(PointerKind::Down, chip));
+ assert_eq!(offsets(preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(150.0, 200.0))))), vec![0.0, 100.0]);
+ assert_eq!(t.cursor(&cx, Point::new(150.0, 200.0), Mods::default()), Cursor::RemoveStop);
+ assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, Point::new(150.0, 200.0))), vec![Action::Commit, GradientTool::select_stop(1)]);
+ }
+
+ #[test]
+ fn diamonds_move_midpoints() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let diamond = Annotator::of(&cx).unwrap().mid_point(&cx, 0).unwrap();
+ let mut t = GradientTool::default();
+ t.pointer(&cx, &ev(PointerKind::Down, diamond));
+ let v = preview(&t.pointer(&cx, &ev(PointerKind::Drag, Point::new(130.0, diamond.y)))).clone();
+ assert!((v["stops"][0]["midpoint"].as_f64().unwrap() - 0.3).abs() < 1e-6, "{v}");
+ }
+
+ #[test]
+ fn delete_and_arrows_act_on_the_selected_stop() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let mut cx = cx(&d, &s, &p);
+ let mut t = GradientTool::default();
+ assert!(!t.claims_key(&cx, ToolKey::Delete), "no stop selected");
+ cx.gradient_stop = Some(1);
+ assert!(t.claims_key(&cx, ToolKey::Delete) && t.claims_key(&cx, ToolKey::Backspace) && !t.claims_key(&cx, ToolKey::Enter));
+ // Two stops: Delete is claimed but does nothing.
+ assert!(t.key(&cx, ToolKey::Delete, Mods::default()).is_empty());
+ let a = t.key(&cx, ToolKey::Left, SHIFT);
+ let (c, v) = exec(&a[0]);
+ assert_eq!((c, offsets(v)), ("paint.editGradient", vec![0.0, 90.0]));
+ assert_eq!(a[1], GradientTool::select_stop(1));
+ // With three stops Delete removes the selected one and selects its successor.
+ let (d, s) = graded(three());
+ let mut cx = crate::testutil::cx(&d, &s, &p);
+ cx.gradient_stop = Some(1);
+ let a = t.key(&cx, ToolKey::Backspace, Mods::default());
+ assert_eq!(offsets(exec(&a[0]).1), vec![0.0, 100.0]);
+ assert_eq!(a[1], GradientTool::select_stop(1));
+ }
+
+ #[test]
+ fn a_click_inside_the_art_applies_the_gradient_from_there() {
+ let (d, id) = doc_with_rect();
+ let mut s = Selection::default();
+ s.add(id);
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let mut t = GradientTool::default();
+ t.pointer(&cx, &ev(PointerKind::Down, Point::new(150.0, 120.0)));
+ let a = t.pointer(&cx, &ev(PointerKind::Up, Point::new(150.0, 120.0)));
+ let (c, v) = exec(&a[0]);
+ assert_eq!(c, "paint.setGradientGeom");
+ // The default fit's 100 pt horizontal vector, starting at the click.
+ assert_eq!((point(&v["start"]), point(&v["end"]), &v["ids"]), (Point::new(150.0, 120.0), Point::new(250.0, 120.0), &json!([id.0])));
+ // Outside the art a click does nothing.
+ t.pointer(&cx, &ev(PointerKind::Down, Point::new(400.0, 400.0)));
+ assert!(t.pointer(&cx, &ev(PointerKind::Up, Point::new(400.0, 400.0))).is_empty());
+ }
+
+ #[test]
+ fn double_click_on_a_stop_opens_its_popover() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let cx = cx(&d, &s, &p);
+ let chip = Annotator::of(&cx).unwrap().stop_point(&cx, 1).unwrap();
+ let a = GradientTool::default().pointer(&cx, &ev(PointerKind::DoubleClick, chip));
+ assert_eq!(a[0], GradientTool::select_stop(1));
+ assert_eq!(a[1], Action::Dialog("gradientStop".into(), json!({"index": 1, "x": chip.x, "y": chip.y})));
+ }
+
+ #[test]
+ fn overlays_draw_a_chip_per_stop_marking_the_selected_one() {
+ let (d, s) = graded(two());
+ let p = paint();
+ let mut cx = cx(&d, &s, &p);
+ cx.gradient_stop = Some(1);
+ let o = GradientTool::default().overlays(&cx);
+ let chips: Vec<bool> = o.iter().filter_map(|o| if let Overlay::Swatch { selected, .. } = o { Some(*selected) } else { None }).collect();
+ assert_eq!(chips, vec![false, true]);
+ assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Path { .. })).count(), 1, "one midpoint diamond");
+ }
++
+ #[test]
+ fn annotator_follows_the_active_appearance_item() {
+ let (mut d, id) = doc_with_rect();
- let geom = vectorcraft_color::GradientGeom { start: Point::new(100.0, 120.0), end: Point::new(200.0, 120.0), aspect: 1.0 };
- let mut gp = vectorcraft_color::GradientPaint::new(Default::default());
++ let geom = GradientGeom { start: Point::new(100.0, 120.0), end: Point::new(200.0, 120.0), aspect: 1.0 };
++ let mut gp = GradientPaint::new(Default::default());
+ gp.geom = Some(geom);
+ d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().paint = Paint::Gradient(Box::new(gp));
+ let mut s = Selection::default();
+ s.add(id);
+ let p = paint();
+ let mut cx = cx(&d, &s, &p);
- // The fill is solid: no annotator until the stroke row (item 1) is the active item.
- assert!(annotator(&cx).is_none());
++ // The fill is solid: no annotator until the stroke row (item 1) is the active item, which
++ // brings the Stroke proxy forward.
++ assert!(Annotator::of(&cx).is_none());
+ cx.appearance_item = Some(1);
- let (a, b, _) = annotator(&cx).unwrap();
- assert_eq!((a, b), (geom.start, geom.end));
++ assert!(Annotator::of(&cx).is_none(), "a stroke row does not stand in for the fill");
++ cx.fill_active = false;
++ assert_eq!(Annotator::of(&cx).unwrap().geom, geom);
++ // A click inside the art edits that item.
++ let mut t = GradientTool::default();
++ t.pointer(&cx, &ev(PointerKind::Down, Point::new(150.0, 180.0)));
++ let a = t.pointer(&cx, &ev(PointerKind::Up, Point::new(150.0, 180.0)));
++ assert_eq!(exec(&a[0]).1["item"], 1);
+ }
}
diff --cc crates/ui-egui/src/panels/mod.rs
index f5772de16,db6a3eade..20b4807a1
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -311,7 -348,7 +338,9 @@@ mod tests
let p = paint_params(&g);
assert_eq!(p["gradient"]["kind"], "linear");
assert_eq!(p["gradient"]["stops"].as_array().unwrap().len(), 2);
+ assert_eq!(paint_params(&vectorcraft_doc::pattern::pattern_paint("Dots")), json!({"pattern": "Dots"}));
+ assert_eq!(p["gradient"]["stops"][0]["midpoint"], json!(0.5));
}
}
+ #[cfg(test)]
+ mod tests_appearance;
diff --cc crates/ui-egui/src/panels/stroke.rs
index e9a466d03,eea0d5ecf..542ee3337
--- a/crates/ui-egui/src/panels/stroke.rs
+++ b/crates/ui-egui/src/panels/stroke.rs
@@@ -3,9 -3,9 +3,9 @@@
use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use serde_json::{Value, json};
-use vectorcraft_doc::{Arrowhead, LineCap, LineJoin, StrokeAlign, Unit, WidthProfile};
+use vectorcraft_doc::{ArrowAlign, Arrowhead, LineCap, LineJoin, ProfilePreset, StrokeAlign, StrokeLayer, Unit, WidthProfile};
- use super::{first_selected, pstate, set_pstate};
+ use super::{current_stroke, pstate, set_pstate};
use crate::theme::Tokens;
use crate::widgets::{self, menu_item};
use crate::{VectorcraftApp, icons};
@@@ -401,51 -400,11 +397,51 @@@ mod tests
}
#[test]
- fn profile_ids() {
- assert_eq!(profile_id(None), "uniform");
- assert_eq!(profile_id(Some(&WidthProfile::lens())), "lens");
- assert_eq!(profile_id(Some(&WidthProfile::taper_end())), "taperEnd");
- assert_eq!(profile_id(Some(&WidthProfile { points: vec![(0.0, 0.3, 0.3)] })), "custom");
+ fn profile_silhouettes_and_arrow_labels() {
+ assert!(profile_of("uniform").is_none());
+ assert_eq!(profile_of("lens"), Some(WidthProfile::lens()));
+ assert!(profile_of("custom").is_none());
assert_eq!(arrow_label(Some(Arrowhead::CircleOpen)), "Circle (open)");
}
+
+ #[test]
+ fn arrow_align_buttons_need_a_head() {
+ let mut st = StrokeLayer::new(vectorcraft_color::Paint::None, 1.0);
+ assert_eq!(arrow_align_state(None), (ArrowAlign::Extend, false));
+ assert_eq!(arrow_align_state(Some(&st)), (ArrowAlign::Extend, false));
+ st.start_arrow = Some(Arrowhead::Bar);
+ st.arrow_align = ArrowAlign::Tip;
+ assert_eq!(arrow_align_state(Some(&st)), (ArrowAlign::Tip, true));
+ for (_, _, icon, _) in ARROW_ALIGN {
+ assert!(icons::exists(icon), "{icon}");
+ }
+ }
+
+ /// Run the panel and its ≡ menu for one headless frame.
+ fn frame(app: &mut VectorcraftApp) {
+ let ctx = egui::Context::default();
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
+ show(app, ui);
+ menu(app, ui);
+ });
+ out.textures_delta.clear();
+ }
+
+ #[test]
+ fn panel_draws_for_lines_with_and_without_heads() {
+ use vectorcraft_engine::Session;
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ let r = |app: &mut VectorcraftApp, id: &str, p: Value| app.session.execute(id, &p).unwrap();
+ r(&mut app, "file.new", json!({"width": 100, "height": 100}));
+ frame(&mut app);
+ r(&mut app, "shape.line", json!({"x1": 10, "y1": 50, "x2": 90, "y2": 50}));
+ frame(&mut app);
+ for p in [json!({"endArrow": "ArrowOpen", "arrowAlign": "tip"}), json!({"profile": "lens"}), json!({"dash": [0, 6], "cap": "round"})] {
+ r(&mut app, "stroke.set", p);
+ frame(&mut app);
+ }
- let st = stroke_now(&app).unwrap();
++ let st = current_stroke(&app).unwrap();
+ assert_eq!((st.end_arrow, st.arrow_align), (Some(Arrowhead::ArrowOpen), ArrowAlign::Tip));
+ assert_eq!(WidthProfile::id_of(st.profile.as_ref()), "lens");
+ }
}