Skip to content

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

Merge wp/I1

bflatastic6bd27a05dadd
diff --cc crates/engine/src/cmd/gradient.rs
index 70e301d71,5d9180901..0ce713bdd
--- a/crates/engine/src/cmd/gradient.rs
+++ b/crates/engine/src/cmd/gradient.rs
@@@ -43,166 -31,8 +43,159 @@@ pub fn specs() -> Vec<CommandSpec>
]
}
- /// The gradient behind the active proxy: the first selected object's (see
- /// `Node::proxy_paint`; the Appearance panel's active item when it is of the proxy's kind), else
- /// the default paint for new art.
++/// The gradient behind the active proxy ([`Session::proxy_paints`]).
+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, 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),
++ let (fill, stroke) = s.proxy_paints();
++ match if s.fill_active { fill } else { stroke } {
++ 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), 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, 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()),
@@@ -265,22 -117,52 +258,30 @@@ 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() {
- s.remember_paint(&new_default);
- 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 {
- for r in &mut t.runs {
- let cur = if stroke { &mut r.style.stroke } else { &mut r.style.fill };
- match apply_gradient_edit(cur, p, None) {
- Ok(np) => *cur = np,
- Err(e) => err = Some(e),
- }
- }
- continue;
- }
- let b = n.geometric_bounds();
- let ap = &mut n.appearance;
- let cur = if stroke { ap.stroke_paint() } else { ap.fill_paint() };
- 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, 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 = 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(())
})?;
- // The last gradient is the one the first object now shows.
- if let Some(shown) = s.doc()?.doc.node(ids[0]).map(|n| super::paint::proxy_paint(n, stroke)) {
++ // The last gradient is the one the first object now shows (the defaults' without objects).
++ let shown = match ids.first() {
++ Some(id) => s.doc()?.doc.node(*id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten())),
++ None => Some(new_default.clone()),
++ };
++ if let Some(shown) = shown {
+ s.remember_paint(&shown);
+ }
if stroke {
s.paint.stroke = new_default;
} else {
@@@ -289,107 -171,38 +290,114 @@@
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
}
++/// A painted stroke on a type run without a weight gets 1 pt.
++pub(crate) fn run_stroke_weight(style: &mut vectorcraft_doc::CharStyle) {
++ if style.stroke_width == 0.0 {
++ style.stroke_width = 1.0;
++ }
++}
++
+/// 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> {
- let start = point_param(p, "start").ok_or_else(|| bad("paint.setGradientGeom", "missing start [x,y]"))?;
- let end = point_param(p, "end").ok_or_else(|| bad("paint.setGradientGeom", "missing end [x,y]"))?;
- let stroke = bool_or(p, "stroke", false);
- let ids = match ids_param(p, "ids") {
- Some(v) => v,
- None => selected_roots(s)?,
+ 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]"))?;
+ // `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, !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, _| {
- for id in &targets {
- let Some(n) = d.node_mut(*id) else { continue };
- if matches!(n.kind, NodeKind::Text(_)) {
- continue;
- }
- let cur = if stroke { n.appearance.stroke_paint() } else { n.appearance.fill_paint() };
- let mut gp = match cur {
- Paint::Gradient(g) => *g,
- _ => GradientPaint::new(Gradient::default()),
- };
- let aspect = gp.geom.map(|g| g.aspect).unwrap_or(1.0);
- gp.geom = Some(GradientGeom { start, end, aspect });
- gp.angle = GradientGeom { start, end, aspect }.angle_deg();
- let paint = Paint::Gradient(Box::new(gp));
- if stroke {
- n.appearance.set_stroke(paint);
- } else {
- n.appearance.set_fill(paint);
+ edit_items(s, &targets, item, C, "Gradient", !stroke, |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 stroke && r.style.stroke_width == 0.0 {
- r.style.stroke_width = 1.0;
++ if stroke {
++ run_stroke_weight(&mut r.style);
+ }
+ let (paint, b) = run_paint_mut(r, stroke, lb);
+ if let Some(np) = vector_paint(paint, start, end, xf, Some(b)) {
+ *paint = np;
+ }
}
+ return Ok(());
+ }
+ 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(())
})?;
diff --cc crates/engine/src/cmd/paint.rs
index 7ad06d129,8a553d52a..a7e27132c
--- a/crates/engine/src/cmd/paint.rs
+++ b/crates/engine/src/cmd/paint.rs
@@@ -1,13 -1,11 +1,13 @@@
//! Fill and stroke paint (the toolbar proxies and their defaults) and the Transparency panel.
use serde_json::{Value, json};
- use vectorcraft_color::{BlendMode, Color, Paint};
- use vectorcraft_doc::{Appearance, NodeKind};
-use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, Paint};
++use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
+ use vectorcraft_doc::{Appearance, CharStyle, Node, NodeId, NodeKind};
+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::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
use super::*;
- use crate::EngineError;
+ use crate::{DocState, EngineError};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@@ -16,15 -14,29 +16,31 @@@
"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}, 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)",
- "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}, none?: true, swatch?: name, gradient?: {kind, stops:[{offset,color}], angle?}, ids?, focus?: true (false keeps the active proxy)} sets selection 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?, focus?: true (false keeps the active proxy)} sets the selection's fill and the default (new art fits a gradient to itself)",
has_doc,
|s, p| set_paint(s, p, true)
),
- cmd!("paint.setStroke", "Stroke", [], None, "same as paint.setFill, for the stroke", has_doc, |s, p| set_paint(s, p, false)),
+ cmd!("paint.setStroke", "Stroke", [], None, "same as paint.setFill, for the stroke (item?: the stroke item to set)", has_doc, |s, p| {
+ set_paint(s, p, false)
+ }),
- cmd!("paint.swap", "Swap Fill and Stroke", [], Some("Shift+X"), "{}", has_doc, swap),
- cmd!("paint.default", "Default Fill and Stroke", [], Some("D"), "{}", has_doc, default_paint),
+ cmd!(
+ "paint.swap",
+ "Swap Fill and Stroke",
+ [],
+ Some("Shift+X"),
+ "{ids?} swap the fill and stroke of the selection (type too) and of the defaults",
+ has_doc,
+ swap
+ ),
+ cmd!(
+ "paint.default",
+ "Default Fill and Stroke",
+ [],
+ Some("D"),
+ "{ids?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke",
+ has_doc,
+ default_paint
+ ),
cmd!("paint.toggleActive", "Toggle Fill/Stroke Focus", [], Some("X"), "{}", always, |s, _| {
s.fill_active = !s.fill_active;
Ok(json!({ "fillActive": s.fill_active }))
@@@ -45,6 -57,197 +61,206 @@@
]
}
+ /// Commands of the Fill/Stroke proxies, registered at the end of the command list.
+ pub fn proxy_specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "paint.invert",
+ "Invert",
+ [],
+ None,
+ "{stroke?: bool (default: the active proxy), ids?} invert the active proxy's colours of the selection (or ids; groups recolour their contents) keeping each colour's model, as edit.colors.invert does; with nothing selected, invert the default → {changed}",
+ has_doc,
+ |s, p| proxy_recolor(s, p, "Invert", &super::colorcmds::invert)
+ ),
+ cmd!(
+ "paint.complement",
+ "Complement",
+ [],
+ None,
+ "{stroke?: bool (default: the active proxy), ids?} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; with nothing selected, the default → {changed}",
+ has_doc,
+ |s, p| proxy_recolor(s, p, "Complement", &|c: Color| c.complement_keep_model())
+ ),
+ cmd!(
+ "paint.lastColor",
+ "Apply Last Color",
+ [],
+ Some(","),
+ "{stroke?: bool (default: the active proxy), ids?} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default",
+ has_doc,
+ |s, p| {
+ let paint = Paint::solid(s.last_solid);
+ apply_to_proxy(s, p, paint)
+ }
+ ),
+ cmd!(
+ "paint.lastGradient",
+ "Apply Last Gradient",
+ [],
+ Some("."),
+ "{stroke?: bool (default: the active proxy), ids?} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default",
+ has_doc,
+ |s, p| {
+ let paint = Paint::Gradient(Box::new(GradientPaint { geom: None, ..s.last_gradient.clone() }));
+ apply_to_proxy(s, p, paint)
+ }
+ ),
+ cmd!(
+ query "paint.recent",
+ "Recent Colors",
+ [],
+ None,
+ "{} → {colors: [{hex, color}] newest first (fed by every paint command and the eyedropper), lastColor: {hex, color}, lastGradient: gradient paint}",
+ always,
+ |s, _| {
+ let c = |c: &Color| json!({"hex": c.to_hex(), "color": c});
+ Ok(json!({
+ "colors": s.recent_colors.iter().map(c).collect::<Vec<_>>(),
+ "lastColor": c(&s.last_solid),
+ "lastGradient": s.last_gradient,
+ }))
+ }
+ ),
+ cmd!(
+ query "paint.proxies",
+ "Fill and Stroke",
+ [],
+ None,
- "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy}",
++ "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy}",
+ always,
+ proxies
+ ),
+ ]
+ }
+
+ impl Session {
+ /// How many colours the Recent Colors rows keep.
+ pub const RECENT_MAX: usize = 10;
+
+ /// Remember an applied paint: a solid colour becomes the last colour and the newest recent
+ /// colour, a gradient the last gradient. During a live preview this waits for the commit.
+ pub(crate) fn remember_paint(&mut self, p: &Paint) {
+ if self.in_interaction() {
+ self.pending_paint = Some(p.clone());
+ } else {
+ self.remember_paint_now(p);
+ }
+ }
+
- /// The fill and stroke the Fill/Stroke proxies show: the first selected object's (a group's
- /// first painted object's; type: its first run's), else the defaults for new art.
++ /// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the
++ /// first selected object's own stack) for the proxy of its kind, else the first selected
++ /// object's (a group's first painted object's; type: its first run's), else the defaults for
++ /// new art.
+ pub fn proxy_paints(&self) -> (Paint, Paint) {
++ let default = |stroke: bool| if stroke { self.paint.stroke.clone() } else { self.paint.fill.clone() };
++ let Some(first) = self.active().and_then(|st| st.selection.objects.first().and_then(|id| st.doc.node(*id))) else {
++ return (default(false), default(true));
++ };
++ let item = self.appearance_item();
+ let mut nodes = vec![];
- if let Some(n) = self.active().and_then(|st| st.selection.objects.first().and_then(|id| st.doc.node(*id))) {
- painted(n, true, &mut nodes);
- }
- match nodes.first() {
- Some(n) => (proxy_paint(n, false), proxy_paint(n, true)),
- None => (self.paint.fill.clone(), self.paint.stroke.clone()),
- }
++ painted(first, true, &mut nodes);
++ let show = |stroke: bool| match first.appearance.item_of_kind(item, !stroke) {
++ Some(_) => proxy_paint(first, stroke, item),
++ None => nodes.first().map_or_else(|| default(stroke), |n| proxy_paint(n, stroke, None)),
++ };
++ (show(false), show(true))
+ }
+
+ pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
+ match p {
+ Paint::Solid { color, .. } => {
+ self.last_solid = *color;
+ self.recent_colors.retain(|c| c != color);
+ self.recent_colors.insert(0, *color);
+ self.recent_colors.truncate(Self::RECENT_MAX);
+ }
+ Paint::Gradient(g) => self.last_gradient = (**g).clone(),
+ Paint::None | Paint::Pattern { .. } => {}
+ }
+ }
+ }
+
-/// The fill or stroke a proxy shows for `n` (type shows its first run's style, as
-/// `TextNode::first_style` does).
-pub(crate) fn proxy_paint(n: &Node, stroke: bool) -> Paint {
- let pick = |st: &CharStyle| if stroke { st.stroke.clone() } else { st.fill.clone() };
- match &n.kind {
- NodeKind::Text(t) => t.runs.first().map_or_else(|| pick(&CharStyle::default()), |r| pick(&r.style)),
- _ if stroke => n.appearance.stroke_paint(),
- _ => n.appearance.fill_paint(),
++/// The fill or stroke a proxy shows for `n` ([`Node::proxy_paint`]: fill or stroke `item` when it
++/// is of that kind, type's first run, else the topmost one).
++pub(crate) fn proxy_paint(n: &Node, stroke: bool, item: Option<usize>) -> Paint {
++ match n.proxy_paint(stroke, item) {
++ Some((p, ..)) => p.clone(),
++ // Type without runs shows the default character style.
++ None if matches!(n.kind, NodeKind::Text(_)) => {
++ let st = CharStyle::default();
++ if stroke { st.stroke } else { st.fill }
++ }
++ None => Paint::None,
+ }
+ }
+
+ /// Do two paints look the same in a proxy? Solid colours compare without their swatch link and
+ /// gradients without their per-object geometry.
+ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
+ match (a, b) {
+ (Paint::Solid { color: x, .. }, Paint::Solid { color: y, .. }) => x == y,
+ (Paint::Gradient(x), Paint::Gradient(y)) => x.gradient == y.gradient,
+ _ => a == b,
+ }
+ }
+
+ /// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
+ /// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
+ /// other containers inside them), a compound path for its parts.
+ fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
+ let expand = match n.kind {
+ NodeKind::Group { .. } | NodeKind::Layer { .. } => true,
+ NodeKind::Compound { .. } => false,
+ _ => !top && n.is_container(),
+ };
+ if expand {
+ n.children().into_iter().flatten().for_each(|c| painted(c, false, out));
+ } else {
+ out.push(n);
+ }
+ }
+
+ impl DocState {
+ /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
+ /// proxy; a group whose contents differ counts). One walk of the document, so callers that ask
+ /// every frame cache it by revision.
+ pub fn proxy_mixed(&self) -> (bool, bool) {
+ if self.selection.is_empty() {
+ return (false, false);
+ }
+ let ids: std::collections::HashSet<NodeId> = self.selection.objects.iter().copied().collect();
+ let mut nodes = vec![];
+ self.doc.walk(|n| {
+ if ids.contains(&n.id) {
+ painted(n, true, &mut nodes);
+ }
+ });
- let mut paints = nodes.iter().map(|n| (proxy_paint(n, false), proxy_paint(n, true)));
++ let mut paints = nodes.iter().map(|n| (proxy_paint(n, false, None), proxy_paint(n, true, None)));
+ let Some((f0, s0)) = paints.next() else { return (false, false) };
+ let mut mixed = (false, false);
+ for (f, s) in paints {
+ mixed.0 |= !same_in_proxy(&f0, &f);
+ mixed.1 |= !same_in_proxy(&s0, &s);
+ if mixed.0 && mixed.1 {
+ break;
+ }
+ }
+ mixed
+ }
+ }
+
+ fn proxies(s: &mut Session, _: &Value) -> Result<Value> {
+ let (fill, stroke) = s.proxy_paints();
+ let (fill_mixed, stroke_mixed) = s.active().map_or((false, false), DocState::proxy_mixed);
+ Ok(json!({"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed}))
+ }
+
+ /// `stroke` param, defaulting to the proxy that is in front.
+ fn stroke_param(s: &Session, p: &Value) -> bool {
+ p.get("stroke").and_then(Value::as_bool).unwrap_or(!s.fill_active)
+ }
+
/// Parse a paint from params (color / none / swatch / gradient). None = no paint keys given.
pub(crate) fn paint_from(s: &Session, p: &Value) -> Result<Option<Paint>> {
if bool_or(p, "none", false) {
@@@ -77,46 -300,71 +293,71 @@@
}
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"))?;
- if bool_or(p, "focus", true) {
- s.fill_active = fill;
- }
- let ids = paint_targets(s, p)?;
- apply_paint(s, &ids, paint, fill)
+ 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"))?;
++ apply_paint(s, p, paint, fill)
+ }
+
+ /// [`apply_paint`] on the proxy named by `stroke` (default: the active one), focusing it.
+ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint) -> Result<Value> {
+ let fill = !stroke_param(s, p);
- s.fill_active = fill;
- let ids = paint_targets(s, p)?;
- apply_paint(s, &ids, paint, fill)
++ apply_paint(s, p, paint, fill)
+ }
+
-/// Set the fill (or stroke) of `ids` and of the defaults for new art, and remember it.
-fn apply_paint(s: &mut Session, ids: &[NodeId], paint: Paint, fill: bool) -> Result<Value> {
++/// Set the fill (or stroke) of the targets of `p` (the `item` and `ids` params, see
++/// `paint.setFill`) and of the defaults for new art, focus its proxy unless `focus` is false, and
++/// remember the paint.
++fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result<Value> {
++ let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
+ // 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;
- if !ids.is_empty() {
- apply_to_nodes(s, ids, &paint, fill)?;
++ if bool_or(p, "focus", true) {
++ s.fill_active = fill;
+ }
- s.remember_paint(&paint);
- ok()
-}
-
-fn apply_to_nodes(s: &mut Session, ids: &[NodeId], paint: &Paint, fill: bool) -> Result<()> {
- 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 {
- for r in &mut t.runs {
- if fill {
- r.style.fill = paint.clone();
- } else {
- set_run_stroke(&mut r.style, paint.clone());
- }
+ 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.stroke_width == 0.0 {
- r.style.stroke_width = 1.0;
++ if !fill && !paint.is_none() {
++ run_stroke_weight(&mut r.style);
}
- continue;
- }
- if fill {
- n.appearance.set_fill(paint.clone());
- } else {
- n.appearance.set_stroke(paint.clone());
+ let (cur, b) = run_paint_mut(r, !fill, lb);
+ *cur = place_run_paint(&paint, p, xf, b);
}
+ 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(())
- })
+ })?;
++ s.remember_paint(&paint);
+ ok()
}
- fn swap(s: &mut Session, _: &Value) -> Result<Value> {
+ /// A type run's stroke; a painted stroke on a run without one gets 1 pt.
+ fn set_run_stroke(style: &mut CharStyle, paint: Paint) {
- if !paint.is_none() && style.stroke_width == 0.0 {
- style.stroke_width = 1.0;
++ if !paint.is_none() {
++ run_stroke_weight(style);
+ }
+ style.stroke = paint;
+ }
+
+ fn swap(s: &mut Session, p: &Value) -> Result<Value> {
std::mem::swap(&mut s.paint.fill, &mut s.paint.stroke);
- let ids = paint_targets(s, &json!({}))?;
+ let ids = paint_targets(s, p)?;
if !ids.is_empty() {
s.edit("Swap Fill and Stroke", |d, _| {
for id in &ids {
@@@ -153,43 -413,34 +406,67 @@@ fn default_paint(s: &mut Session, p: &V
ok()
}
+ /// Invert / Complement: recolour the active proxy of the targets (or the default when there are
+ /// none) and remember the first target's new paint.
+ fn proxy_recolor(s: &mut Session, p: &Value, label: &str, f: &dyn Fn(Color) -> Color) -> Result<Value> {
+ let stroke = stroke_param(s, p);
+ let ids = match ids_param(p, "ids") {
+ Some(ids) => ids,
+ None => super::edit::selected_roots(s)?,
+ };
+ if ids.is_empty() {
+ let def = if stroke { &mut s.paint.stroke } else { &mut s.paint.fill };
+ let changed = super::colorcmds::map_paint(def, f);
+ let shown = def.clone();
+ s.remember_paint(&shown);
+ return Ok(json!({ "changed": changed as usize }));
+ }
+ let q = json!({"fill": !stroke, "stroke": stroke, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
+ let r = super::colorcmds::recolor(s, &q, label, f)?;
- let first = leaf_targets(s, &ids)?.first().and_then(|id| s.doc().ok()?.doc.node(*id).map(|n| proxy_paint(n, stroke)));
++ let first = leaf_targets(s, &ids)?.first().and_then(|id| s.doc().ok()?.doc.node(*id).map(|n| proxy_paint(n, stroke, None)));
+ if let Some(shown) = first {
+ s.remember_paint(&shown);
+ }
+ Ok(r)
+ }
+
fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
- let mut q = p.clone();
- if let Some(o) = p.get("opacity").and_then(Value::as_f64) {
- q["opacity"] = json!(o / 100.0);
+ const C: &str = "transparency.set";
+ let ids = super::opacitymask::transparency_targets(s, p)?;
+ if ids.is_empty() {
+ return Err(bad(C, "select objects or give ids"));
+ }
+ // While an opacity mask is edited the selection is its art, so the Appearance panel's active
+ // item (a row of that art) doesn't stand for the masked object.
+ let editing_mask = p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.doc.mask_edit.is_some();
+ let item = if editing_mask && p.get("item").is_none() { ItemTarget::Top } else { item_target(s, p, C)? };
+ let mut q = p.as_object().cloned().unwrap_or_default();
+ q.remove("item");
+ q.remove("id");
+ q.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
+ let ItemTarget::Item { index, explicit } = item else {
+ return s.execute("object.setProps", &Value::Object(q));
+ };
+ // Opacity and blend belong to the targeted fill/stroke; isolate/knockout stay object-level.
+ let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? };
+ if explicit {
+ let d = &s.doc()?.doc;
+ if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
+ return Err(bad(C, format!("no appearance item {index}")));
+ }
+ }
+ let (opacity, blend) = (q.remove("opacity"), q.remove("blend"));
+ if let Some(b) = &blend
+ && b.as_str().and_then(BlendMode::parse).is_none()
+ {
+ return Err(bad(C, format!("unknown blend mode {b}")));
+ }
+ if opacity.is_some() || blend.is_some() {
+ let ids: Vec<u64> = item_ids.iter().map(|id| id.0).collect();
+ s.execute("appearance.setItem", &json!({ "index": index, "ids": ids, "opacity": opacity, "blend": blend }))?;
+ }
+ if q.keys().all(|k| k == "ids") {
+ return ok();
}
- s.execute("object.setProps", &q)
+ s.execute("object.setProps", &Value::Object(q))
}
diff --cc crates/engine/src/lib.rs
index ecdce7a66,e293a93a3..6ea09da73
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -443,13 -443,15 +443,22 @@@ 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>,
+ /// The last solid colour applied (the toolbar's Color button; `,` applies it again).
+ pub last_solid: Color,
+ /// The last gradient applied (the toolbar's Gradient button; `.` applies it again).
+ pub last_gradient: GradientPaint,
+ /// Recently applied solid colours, newest first (the Recent Colors rows), fed by every paint
+ /// command whichever frontend runs it.
+ pub recent_colors: Vec<Color>,
+ /// A paint applied by a live preview: remembered when the interaction commits.
+ pub(crate) pending_paint: Option<Paint>,
}
impl Default for Session {
@@@ -475,8 -477,10 +484,12 @@@ impl Session
draw_inside: None,
untitled_counter: 0,
menu: Default::default(),
+ gradient_stop: None,
+ active_appearance_item: None,
+ last_solid: Color::WHITE,
+ last_gradient: GradientPaint::new(Default::default()),
+ recent_colors: vec![],
+ pending_paint: None,
}
}
@@@ -741,8 -742,8 +758,10 @@@ mod tests_live
#[cfg(test)]
mod tests_menucmds;
#[cfg(test)]
+mod tests_opacitymask;
+#[cfg(test)]
+ mod tests_paintproxy;
+ #[cfg(test)]
mod tests_panelcmds;
#[cfg(test)]
mod tests_pathops;
diff --cc crates/engine/src/tests_appearance.rs
index c66a856ae,000000000..a48259058
mode 100644,000000..100644
--- a/crates/engine/src/tests_appearance.rs
+++ b/crates/engine/src/tests_appearance.rs
@@@ -1,408 -1,0 +1,411 @@@
+//! Appearance stacks: the active item that paint, stroke, gradient and transparency edits target
+//! (`appearance.setActiveItem`, the `item` param).
+
+use serde_json::{Value, json};
+use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
+use vectorcraft_doc::{AppearanceItem, Node};
+
+use super::*;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ s
+}
+
+/// A selected 100×100 rectangle with the default appearance `[Fill white, Stroke black]`.
+fn rect(s: &mut Session, x: f64) -> NodeId {
+ let r = s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 100, "height": 100})).unwrap();
+ let id = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ id
+}
+
+fn node(s: &Session, id: NodeId) -> Node {
+ s.doc().unwrap().doc.node(id).unwrap().clone()
+}
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+fn stroke(n: &Node, i: usize) -> &vectorcraft_doc::StrokeLayer {
+ n.appearance.stroke_at(Some(i)).unwrap_or_else(|| panic!("item {i} is not a stroke"))
+}
+
+fn fill_paint(n: &Node, i: usize) -> &Paint {
+ &n.appearance.fill_at(Some(i)).unwrap_or_else(|| panic!("item {i} is not a fill")).paint
+}
+
+#[test]
+fn stroke_set_with_item_changes_only_that_stroke() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Stroke]
+ run(&mut s, "stroke.set", json!({"item": 1, "dash": [4, 2], "weight": 6}));
+ let n = node(&s, id);
+ assert_eq!(stroke(&n, 1).dash.as_ref().unwrap().pattern, vec![4.0, 2.0]);
+ assert_eq!(stroke(&n, 1).width, 6.0);
+ assert!(stroke(&n, 2).dash.is_none());
+ assert_eq!(stroke(&n, 2).width, 1.0);
+ run(&mut s, "stroke.setAdvanced", json!({"item": 1, "arrowScale": [50, 200]}));
+ let n = node(&s, id);
+ assert_eq!((stroke(&n, 1).arrow_scale, stroke(&n, 2).arrow_scale), ((50.0, 200.0), (100.0, 100.0)));
+ // An explicit item must be a stroke; nothing changes when it is not.
+ assert!(s.execute("stroke.set", &json!({"item": 0, "weight": 9})).is_err());
+ assert!(s.execute("stroke.set", &json!({"item": 7, "weight": 9})).is_err());
+ assert!(s.execute("stroke.set", &json!({"item": "top", "weight": 9})).is_err());
+ assert_eq!(stroke(&node(&s, id), 2).width, 1.0);
+ // Without an item the top stroke changes.
+ run(&mut s, "stroke.set", json!({"weight": 3}));
+ let n = node(&s, id);
+ assert_eq!((stroke(&n, 1).width, stroke(&n, 2).width), (6.0, 3.0));
+}
+
+#[test]
+fn edit_gradient_on_the_lower_fill() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({})); // [Fill, Stroke, Fill]
+ run(&mut s, "paint.editGradient", json!({"item": 0, "kind": "radial"}));
+ let n = node(&s, id);
+ let Paint::Gradient(g) = fill_paint(&n, 0) else { panic!("lower fill is not a gradient") };
+ assert_eq!(g.gradient.kind, GradientKind::Radial);
+ assert_eq!(*fill_paint(&n, 2), Paint::solid(Color::WHITE));
+ // The gradient vector of the lower fill, through the active item (the gradient tool's path).
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "paint.setGradientGeom", json!({"start": [100, 150], "end": [200, 150]}));
+ let n = node(&s, id);
+ let Paint::Gradient(g) = fill_paint(&n, 0) else { panic!() };
+ assert_eq!(g.geom.unwrap().end.x, 200.0);
+ assert_eq!(*fill_paint(&n, 2), Paint::solid(Color::WHITE));
+ // A stroke row makes the gradient vector a stroke gradient.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ run(&mut s, "paint.setGradientGeom", json!({"start": [100, 150], "end": [100, 250]}));
+ assert!(matches!(stroke(&node(&s, id), 1).paint, Paint::Gradient(_)));
+}
+
+#[test]
+fn active_item_targets_paint_and_proxies_and_clears_on_selection_change() {
+ let mut s = session();
+ let other = rect(&mut s, 250.0);
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({})); // [Fill, Stroke, Fill]
+ assert!(s.execute("appearance.setActiveItem", &json!({"index": 5})).is_err());
+ assert_eq!(run(&mut s, "appearance.setActiveItem", json!({"index": 0}))["index"], 0);
+ assert_eq!(s.appearance_item(), Some(0));
+ assert_eq!(inspect::document(&s)["paint"]["appearanceItem"], 0);
+ assert!(s.fill_active);
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ let n = node(&s, id);
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ assert_eq!(*fill_paint(&n, 2), Paint::solid(Color::WHITE));
+ // The stroke edits fall back to the top stroke while a fill row is active.
+ run(&mut s, "paint.setStroke", json!({"color": "#00ff00"}));
+ assert_eq!(stroke(&node(&s, id), 1).paint.color().unwrap().to_hex(), "#00ff00");
++ // The proxies show the active row for its kind and the top one for the other.
++ let (f, st) = s.proxy_paints();
++ assert_eq!((f.color().unwrap().to_hex(), st.color().unwrap().to_hex()), ("#ff0000".to_string(), "#00ff00".to_string()));
+ // A stroke row brings the Stroke proxy forward.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ assert!(!s.fill_active);
+ // Changing the selection clears it, also when the same object is selected again.
+ run(&mut s, "select.set", json!({"ids": [other.0]}));
+ assert_eq!(s.appearance_item(), None);
+ run(&mut s, "select.set", json!({"ids": [id.0]}));
+ assert_eq!(s.appearance_item(), None);
+ run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
+ let n = node(&s, id);
+ assert_eq!(fill_paint(&n, 2).color().unwrap().to_hex(), "#0000ff");
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ // Explicit ids never use the active item, and `null` forces the top one.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "paint.setFill", json!({"color": "#222222", "ids": [id.0]}));
+ assert_eq!(fill_paint(&node(&s, id), 2).color().unwrap().to_hex(), "#222222");
+ run(&mut s, "paint.setFill", json!({"color": "#111111", "item": null}));
+ let n = node(&s, id);
+ assert_eq!(fill_paint(&n, 2).color().unwrap().to_hex(), "#111111");
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ run(&mut s, "appearance.setActiveItem", json!({"index": null}));
+ assert_eq!(s.appearance_item(), None);
+}
+
+#[test]
+fn item_rows_follow_remove_and_move() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({})); // [Fill, Stroke, Fill]
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ run(&mut s, "appearance.moveItem", json!({"from": 1, "to": 2}));
+ assert_eq!(s.appearance_item(), Some(2));
+ assert!(matches!(node(&s, id).appearance.items[2], AppearanceItem::Stroke(_)));
+ run(&mut s, "appearance.removeItem", json!({"index": 0}));
+ assert_eq!(s.appearance_item(), Some(1));
+ run(&mut s, "appearance.removeItem", json!({"index": 1}));
+ assert_eq!(s.appearance_item(), None);
+}
+
+#[test]
+fn transparency_goes_to_the_targeted_item() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "transparency.set", json!({"item": 1, "opacity": 40, "blend": "multiply"}));
+ let n = node(&s, id);
+ assert_eq!((stroke(&n, 1).opacity, stroke(&n, 1).blend), (0.4, BlendMode::Multiply));
+ assert_eq!((n.opacity, n.blend), (1.0, BlendMode::Normal));
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ // Opacity and blend go to the active item, isolate stays on the object.
+ run(&mut s, "transparency.set", json!({"opacity": 1, "isolate": true}));
+ let n = node(&s, id);
+ assert!((n.appearance.items[0].opacity() - 0.01).abs() < 1e-6);
+ assert!(n.isolate);
+ assert_eq!(n.opacity, 1.0);
+ run(&mut s, "transparency.set", json!({"item": null, "opacity": 50}));
+ assert_eq!(node(&s, id).opacity, 0.5);
+ assert!(s.execute("transparency.set", &json!({"item": 9, "opacity": 50})).is_err());
+}
+
+#[test]
+fn group_rows_are_the_groups_own_stack() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ let b = rect(&mut s, 250.0);
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
+ run(&mut s, "appearance.addFill", json!({}));
+ assert_eq!(node(&s, g).appearance.items.len(), 1);
+ assert_eq!(node(&s, a).appearance.items.len(), 2);
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ assert_eq!(fill_paint(&node(&s, g), 0).color().unwrap().to_hex(), "#ff0000");
+ assert_eq!(*fill_paint(&node(&s, a), 0), Paint::solid(Color::WHITE));
+ // Without a targeted item, a group's fill edit still recolours its contents.
+ run(&mut s, "appearance.setActiveItem", json!({"index": null}));
+ run(&mut s, "paint.setFill", json!({"color": "#00ff00"}));
+ assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00");
+}
+
+#[test]
+fn text_items_take_item_paint() {
+ let mut s = session();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap());
+ run(&mut s, "select.set", json!({"ids": [t.0]}));
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "paint.setFill", json!({"item": 0, "color": "#ff0000"}));
+ let n = node(&s, t);
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ let vectorcraft_doc::NodeKind::Text(tx) = &n.kind else { panic!() };
+ assert_ne!(tx.first_style().fill, Paint::solid(Color::from_hex("#ff0000").unwrap()));
+}
+
+#[test]
+fn effects_land_on_the_targeted_item() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ let r = run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 1}));
+ assert_eq!((r["index"].clone(), r["item"].clone()), (json!(0), json!(1)));
+ let n = node(&s, id);
+ assert_eq!(stroke(&n, 1).effects.len(), 1);
+ assert!(n.appearance.effects.is_empty() && n.appearance.items[0].effects().is_empty());
+ run(&mut s, "edit.undo", json!({}));
+ assert!(stroke(&node(&s, id), 1).effects.is_empty());
+ assert!(s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 9})).is_err());
+ assert!(s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": -1})).is_err());
+ // The active item takes the Effect menu's effects (and its alias).
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "effect.apply", json!({"effect": "distort.twist"}));
+ run(&mut s, "appearance.addEffect", json!({"effect": "stylize.roundCorners"}));
+ let n = node(&s, id);
+ assert_eq!(n.appearance.items[0].effects().iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["distort.twist", "stylize.roundCorners"]);
+ let l = run(&mut s, "effect.list", json!({}));
+ assert_eq!(l["activeItem"], 0);
+ assert_eq!(l["applied"][0]["items"][0]["kind"], "fill");
+ assert_eq!(l["applied"][0]["items"][0]["effects"].as_array().unwrap().len(), 2);
+ // Sub-row eye, duplicate and delete address the item's list.
+ run(&mut s, "effect.setParams", json!({"index": 1, "visible": false}));
+ run(&mut s, "effect.duplicate", json!({"index": 0}));
+ run(&mut s, "effect.remove", json!({"index": 2}));
+ let fx = node(&s, id).appearance.items[0].effects().clone();
+ assert_eq!(fx.iter().map(|e| (e.id.as_str(), e.visible)).collect::<Vec<_>>(), [("distort.twist", true), ("distort.twist", true)]);
+ assert!(s.execute("effect.remove", &json!({"index": 5})).is_err());
+ // `item: null` addresses the object's own effects.
+ run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "item": null}));
+ assert_eq!(node(&s, id).appearance.effects.len(), 1);
+}
+
+#[test]
+fn per_fill_offset_path_renders() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ run(&mut s, "paint.setStroke", json!({"none": true}));
+ let render = |s: &Session| {
+ vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default())
+ };
+ assert_eq!(render(&s).pixel(90, 150)[3], 0);
+ run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 20}, "item": 0}));
+ assert_eq!(node(&s, id).appearance.items[0].effects().len(), 1);
+ let px = render(&s).pixel(90, 150);
+ assert!(px[0] > 200 && px[3] > 200, "{px:?}");
+}
+
+#[test]
+fn text_fill_items_composite_with_their_opacity() {
+ let mut s = session();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 20, "y": 200, "text": "HIM", "size": 150}))["id"].as_u64().unwrap());
+ run(&mut s, "select.set", json!({"ids": [t.0]}));
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "appearance.setItem", json!({"index": 0, "color": "#ff0000"}));
+ let render = |s: &Session| {
+ vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default())
+ };
+ let opaque = render(&s);
+ // A pixel the red fill covers fully (over the black character fill).
+ let (x, y) = (0..400u32).flat_map(|y| (0..400u32).map(move |x| (x, y))).find(|&(x, y)| opaque.pixel(x, y) == [255, 0, 0, 255]).expect("red text");
+ run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 50, "blend": "multiply"}));
+ let px = render(&s).pixel(x, y);
+ // Half of red multiplied over black: black.
+ assert!(px[0] < 20 && px[3] == 255, "{px:?}");
+ run(&mut s, "appearance.setItem", json!({"index": 0, "blend": "normal"}));
+ let px = render(&s).pixel(x, y);
+ assert!((110..=145).contains(&px[0]) && px[1] < 10, "{px:?}");
+}
+
+#[test]
+fn add_fill_and_stroke_copy_the_top_ones() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ run(&mut s, "stroke.set", json!({"weight": 4}));
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Fill, Stroke]
+ let n = node(&s, id);
+ assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "stroke", "fill", "stroke"]);
+ assert_eq!(fill_paint(&n, 2).color().unwrap().to_hex(), "#ff0000");
+ assert_eq!(stroke(&n, 3).width, 4.0);
+ assert!(!n.appearance.is_basic());
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(node(&s, id).appearance.items.len(), 3);
+}
+
+#[test]
+fn set_item_and_remove_item() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.setItem", json!({"index": 1, "opacity": 50, "blend": "screen", "weight": 3, "color": "#0000ff"}));
+ let n = node(&s, id);
+ let st = stroke(&n, 1);
+ assert_eq!((st.opacity, st.blend, st.width), (0.5, BlendMode::Screen, 3.0));
+ assert_eq!(st.paint.color().unwrap().to_hex(), "#0000ff");
+ run(&mut s, "appearance.setItem", json!({"index": 0, "visible": false, "opacity": 25}));
+ let n = node(&s, id);
+ assert!(!n.appearance.items[0].visible() && n.appearance.items[0].opacity() == 0.25);
+ assert!(s.execute("appearance.setItem", &json!({})).is_err());
+ run(&mut s, "appearance.removeItem", json!({"index": 0}));
+ let n = node(&s, id);
+ assert_eq!(n.appearance.items.len(), 1);
+ assert!(n.appearance.fill().is_none() && n.appearance.stroke().is_some());
+}
+
+#[test]
+fn clear_and_reduce_to_basic() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addStroke", json!({}));
+ run(&mut s, "appearance.setItem", json!({"index": 2, "visible": false, "color": "#00ff00"}));
+ run(&mut s, "appearance.setItem", json!({"index": 1, "opacity": 50}));
+ run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 1}));
+ run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "item": null}));
+ run(&mut s, "transparency.set", json!({"opacity": 40, "blend": "multiply"}));
+ // Reduce keeps the topmost visible fill and stroke, plain, and the object's transparency.
+ run(&mut s, "appearance.reduceToBasic", json!({}));
+ let n = node(&s, id);
+ assert!(n.appearance.is_basic(), "{:?}", n.appearance);
+ assert_eq!(stroke(&n, 1).paint, Paint::solid(Color::BLACK));
+ assert_eq!((n.opacity, n.blend), (0.4, BlendMode::Multiply));
+ // Clear leaves one None fill and stroke, and resets the object's Opacity row.
+ run(&mut s, "appearance.clear", json!({}));
+ let n = node(&s, id);
+ assert_eq!(n.appearance, vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0));
+ assert_eq!((n.opacity, n.blend), (1.0, BlendMode::Normal));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(node(&s, id).opacity, 0.4);
+}
+
+#[test]
+fn graphic_style_apply_replaces_the_stack() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
+ let name = run(&mut s, "graphicStyle.new", json!({"name": "Rough"}))["name"].clone();
+ let b = rect(&mut s, 250.0);
+ run(&mut s, "graphicStyle.apply", json!({ "name": name }));
+ assert_eq!(node(&s, b).appearance, node(&s, a).appearance);
+ assert!(s.execute("graphicStyle.apply", &json!({"name": "nope"})).is_err());
+}
+
+#[test]
+fn an_active_row_of_the_other_kind_leaves_edits_on_the_painted_leaves() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ let b = rect(&mut s, 250.0);
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
+ run(&mut s, "appearance.addFill", json!({}));
+ // The group's own fill row is active: stroke edits still go to the members' strokes.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "stroke.set", json!({"weight": 5}));
+ run(&mut s, "paint.setStroke", json!({"color": "#00ff00"}));
+ assert_eq!(node(&s, g).appearance.items.len(), 1, "no stroke row added to the group");
+ for id in [a, b] {
+ assert_eq!(stroke(&node(&s, id), 1).width, 5.0);
+ assert_eq!(stroke(&node(&s, id), 1).paint.color().unwrap().to_hex(), "#00ff00");
+ }
+}
+
+#[test]
+fn the_active_row_follows_only_edits_of_its_object() {
+ let mut s = session();
+ let other = rect(&mut s, 250.0);
+ rect(&mut s, 100.0);
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ run(&mut s, "appearance.removeItem", json!({"index": 0, "ids": [other.0]}));
+ run(&mut s, "appearance.duplicateItem", json!({"index": 0, "ids": [other.0]}));
+ assert_eq!(s.appearance_item(), Some(1));
+}
+
+#[test]
+fn item_transparency_is_one_step_and_checks_the_blend_mode() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ let steps = |s: &Session| s.doc().unwrap().history.undo.len();
+ let before = steps(&s);
+ run(&mut s, "transparency.set", json!({"knockout": true}));
+ assert_eq!(steps(&s), before + 1, "isolate/knockout alone do not touch the item");
+ assert!(node(&s, id).knockout);
+ assert!(s.execute("transparency.set", &json!({"blend": "nope"})).is_err());
+ assert_eq!(stroke(&node(&s, id), 1).blend, BlendMode::Normal);
+}
+
+#[test]
+fn clear_and_reduce_keep_a_groups_stack_empty() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ let b = rect(&mut s, 250.0);
+ let members = node(&s, a).appearance;
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
+ run(&mut s, "appearance.reduceToBasic", json!({}));
+ assert!(node(&s, g).appearance.items.is_empty());
+ run(&mut s, "appearance.addStroke", json!({}));
+ run(&mut s, "appearance.reduceToBasic", json!({}));
+ assert_eq!(node(&s, g).appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["stroke"]);
+ run(&mut s, "transparency.set", json!({"opacity": 50}));
+ run(&mut s, "appearance.clear", json!({}));
+ let n = node(&s, g);
+ assert!(n.appearance.items.is_empty() && n.opacity == 1.0);
+ // The members keep their own appearance.
+ assert_eq!(node(&s, a).appearance, members);
+}
diff --cc crates/ui-egui/src/dialogs/color_picker.rs
index 000000000,8b69fc5f4..790f9f23e
mode 000000,100644..100644
--- a/crates/ui-egui/src/dialogs/color_picker.rs
+++ b/crates/ui-egui/src/dialogs/color_picker.rs
@@@ -1,0 -1,510 +1,510 @@@
+ //! The Color Picker (double-click a Fill/Stroke proxy, or `ui.colorPicker`): a colour field with a
+ //! channel slider for H, S, B, R, G or B; HSB, RGB, Lab and CMYK fields and hex; Only Web Colors;
+ //! the out-of-gamut and out-of-web warnings (click to correct); New/Original chips; and a Color
+ //! Swatches list. OK applies the colour to its proxy through `paint.setFill` / `paint.setStroke`.
+ //!
+ //! Fields agents set with `ui.dialog.set`: `hex` (`"00FF00"`) or `color` (any colour the paint
+ //! commands take), `channel` (`hue`, `saturation`, `brightness`, `red`, `green`, `blue`), `webOnly`
+ //! and `swatches`. `stroke` and `original` come from the opener.
+
+ use egui::{Rect, Sense, Ui, vec2};
+ use serde_json::{Value, json};
+ use vectorcraft_color::cms::{self, Lab};
+ use vectorcraft_color::{Color, Paint};
+ use vectorcraft_doc::ColorMode;
+ use vectorcraft_engine::cmd::color_value;
+
+ use super::DialogSpec;
+ use crate::panels::color::{GAMUT_WARNING, WEB_WARNING, gamut_fix, hex_digits, is_web_safe, parse_hex, warning_chip, web_safe};
+ use crate::panels::{c32, color_json};
+ use crate::state::Dialog;
+ use crate::theme::Tokens;
+ use crate::{VectorcraftApp, widgets};
+
+ pub(super) const KIND: &str = "colorPicker";
+
+ pub(super) const SPEC: DialogSpec =
+ DialogSpec { heading: |_| "Color Picker".into(), body, confirm, min_width: 600.0, max_width: Some(640.0), ..DialogSpec::FORM };
+
+ /// Side of the colour field (and height of the channel slider).
+ const FIELD: f32 = 240.0;
+ /// Width of the value fields.
+ const VALUE_W: f32 = 54.0;
+
+ /// The component the channel slider edits; the colour field shows the other two.
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+ pub enum Channel {
+ #[default]
+ Hue,
+ Saturation,
+ Brightness,
+ Red,
+ Green,
+ Blue,
+ }
+
+ impl Channel {
+ pub const ALL: [Channel; 6] = [Channel::Hue, Channel::Saturation, Channel::Brightness, Channel::Red, Channel::Green, Channel::Blue];
+
+ pub fn id(self) -> &'static str {
+ match self {
+ Channel::Hue => "hue",
+ Channel::Saturation => "saturation",
+ Channel::Brightness => "brightness",
+ Channel::Red => "red",
+ Channel::Green => "green",
+ Channel::Blue => "blue",
+ }
+ }
+ pub fn parse(s: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|c| c.id() == s)
+ }
+ fn label(self) -> &'static str {
+ match self {
+ Channel::Hue => "H",
+ Channel::Saturation => "S",
+ Channel::Brightness | Channel::Blue => "B",
+ Channel::Red => "R",
+ Channel::Green => "G",
+ }
+ }
+ fn is_hsb(self) -> bool {
+ matches!(self, Channel::Hue | Channel::Saturation | Channel::Brightness)
+ }
+ /// Indices of (slider, field x, field y) into the channel's space: [h, s, b] or [r, g, b].
+ fn axes(self) -> (usize, usize, usize) {
+ match self {
+ Channel::Hue => (0, 1, 2),
+ Channel::Saturation => (1, 0, 2),
+ Channel::Brightness => (2, 0, 1),
+ Channel::Red => (0, 2, 1),
+ Channel::Green => (1, 2, 0),
+ Channel::Blue => (2, 0, 1),
+ }
+ }
+ }
+
+ /// The picked colour with its HSB (hue in degrees), kept so the hue survives grey colours.
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ pub struct Picked {
+ pub color: Color,
+ pub hsb: [f32; 3],
+ }
+
+ impl Picked {
+ pub fn of(color: Color) -> Self {
+ Self { color, hsb: color.to_hsb() }
+ }
+ fn from_hsb(hsb: [f32; 3]) -> Self {
+ Self { color: Color::from_hsb(hsb[0], hsb[1], hsb[2]), hsb }
+ }
+ /// The nearest web colour when Only Web Colors is on.
+ pub fn snapped(self, web: bool) -> Self {
+ if web && !is_web_safe(&self.color) { Self::of(web_safe(&self.color)) } else { self }
+ }
+ }
+
+ /// The slider value and the field point (x right, y down; 0..1 each) of a colour.
+ pub fn field_pos(ch: Channel, p: &Picked) -> (f32, f32, f32) {
+ let v = if ch.is_hsb() { [p.hsb[0] / 360.0, p.hsb[1], p.hsb[2]] } else { p.color.to_rgb() };
+ let (z, x, y) = ch.axes();
+ (v[z], v[x], 1.0 - v[y])
+ }
+
+ /// The colour at slider value `z` and field point (x, y): the inverse of [`field_pos`].
+ pub fn field_pick(ch: Channel, z: f32, x: f32, y: f32) -> Picked {
+ let (zi, xi, yi) = ch.axes();
+ let mut v = [0.0; 3];
+ v[zi] = z;
+ v[xi] = x;
+ v[yi] = 1.0 - y;
+ let v = v.map(|c| c.clamp(0.0, 1.0));
+ if ch.is_hsb() { Picked::from_hsb([v[0] * 360.0, v[1], v[2]]) } else { Picked::of(Color::rgb(v[0], v[1], v[2])) }
+ }
+
+ /// The channel slider's track at `z`: the full spectrum for hue, else the colour with only the
+ /// slider's component changing.
+ pub fn slider_color(ch: Channel, z: f32, x: f32, y: f32) -> Color {
+ if ch == Channel::Hue { Color::from_hsb(z * 360.0, 1.0, 1.0) } else { field_pick(ch, z, x, y).color }
+ }
+
+ /// The colour the dialog holds: an edited `hex` wins over `color` (agents set either one).
+ fn picked(d: &Dialog) -> Picked {
+ let hex = d.str("hex");
+ let color = match parse_hex(&hex) {
+ Some(c) if hex != d.str("__hex") => c,
+ _ => d.fields.get("color").and_then(color_value).unwrap_or(Color::WHITE),
+ };
+ let hsb = d.fields.get("__hsb").and_then(|v| serde_json::from_value::<[f32; 3]>(v.clone()).ok());
+ let p = match hsb {
+ Some(h) if Picked::from_hsb(h).color.to_hex() == color.to_hex() => Picked { color, hsb: h },
+ _ => Picked::of(color),
+ };
+ p.snapped(d.bool("webOnly"))
+ }
+
+ fn store(d: &mut Dialog, p: &Picked) {
+ let hex = hex_digits(&p.color);
+ d.fields.insert("color".into(), color_json(&p.color));
+ d.fields.insert("hex".into(), json!(hex));
+ d.fields.insert("__hex".into(), json!(hex));
+ d.fields.insert("__hsb".into(), json!(p.hsb));
+ }
+
+ /// The colour the proxy shows (a gradient's first stop; the last colour for None and patterns).
+ fn proxy_color(app: &VectorcraftApp, stroke: bool) -> Color {
+ let (f, s) = crate::panels::current_paints(app);
+ match if stroke { s } else { f } {
+ Paint::Solid { color, .. } => color,
+ Paint::Gradient(g) => g.gradient.stops.first().map_or(app.session.last_solid, |s| s.color),
+ Paint::None | Paint::Pattern { .. } => app.session.last_solid,
+ }
+ }
+
+ /// `ui.colorPicker {stroke?, color?}`: open the picker for the fill (or stroke) proxy, starting
+ /// from `color` or the proxy's colour.
+ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
+ let stroke = p.get("stroke").and_then(Value::as_bool).unwrap_or(!app.session.fill_active);
+ let color = match p.get("color") {
+ Some(v) => color_value(v).ok_or_else(|| format!("bad color {v}"))?,
+ None => proxy_color(app, stroke),
+ };
+ let mut d = Dialog::new(
+ KIND,
+ json!({"stroke": stroke, "original": color_json(&color), "channel": Channel::default().id(), "webOnly": false, "swatches": false}),
+ );
+ store(&mut d, &Picked::of(color));
+ app.ui.dialog = Some(d);
+ Ok(Value::Null)
+ }
+
+ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool {
+ let channel = Channel::parse(&d.str("channel")).unwrap_or_default();
+ let web = d.bool("webOnly");
+ let swatches = d.bool("swatches");
+ let p = picked(d);
+ let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color);
+ let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color);
+ let mut pick: Option<Picked> = None;
+ let mut new_channel = None;
+ let mut toggle_swatches = false;
+ ui.horizontal_top(|ui| {
+ if swatches {
+ pick = swatch_list(app, ui, &p.color).map(Picked::of);
+ } else {
+ let (z, x, y) = field_pos(channel, &p);
+ let at = |x: f32, y: f32| c32(&field_pick(channel, z, x, y).snapped(web).color);
+ if let (Some((x, y)), _) = widgets::color_field(ui, "cp-field", vec2(FIELD, FIELD), (x, y), &at) {
+ pick = Some(field_pick(channel, z, x, y));
+ }
+ ui.add_space(6.0);
+ let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color);
+ if let (Some(z), _) = widgets::channel_slider(ui, "cp-slider", z, vec2(22.0, FIELD), &track) {
+ pick = Some(field_pick(channel, z, x, y));
+ }
+ }
+ ui.add_space(14.0);
+ ui.vertical(|ui| {
+ ui.horizontal_top(|ui| {
+ if new_original_chips(ui, &p.color, &original) {
+ pick = Some(Picked::of(original));
+ }
+ ui.add_space(8.0);
+ ui.vertical(|ui| {
+ if let Some(fix) = gamut
+ && warning_chip(ui, GAMUT_WARNING, &fix)
+ {
+ pick = Some(Picked::of(fix));
+ }
+ let ws = web_safe(&p.color);
+ if !web && !is_web_safe(&p.color) && warning_chip(ui, WEB_WARNING, &ws) {
+ pick = Some(Picked::of(ws));
+ }
+ });
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
+ toggle_swatches = widgets::flat_button(ui, if swatches { "Color Models" } else { "Color Swatches" }, 110.0).clicked();
+ });
+ });
+ ui.add_space(10.0);
+ let (edit, ch) = value_fields(ui, &p, channel);
+ pick = pick.or(edit);
+ new_channel = ch;
+ });
+ });
+ ui.add_space(8.0);
+ if widgets::check(ui, "Only Web Colors", web, true) {
+ d.fields.insert("webOnly".into(), json!(!web));
+ }
+ if let Some(ch) = new_channel {
+ d.fields.insert("channel".into(), json!(ch.id()));
+ }
+ if toggle_swatches {
+ d.fields.insert("swatches".into(), json!(!swatches));
+ }
+ store(d, &pick.unwrap_or(p).snapped(d.bool("webOnly")));
+ false
+ }
+
+ /// The New (top) and Original (bottom) chips. Returns true when Original is clicked.
+ fn new_original_chips(ui: &mut Ui, new: &Color, original: &Color) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let (r, _) = ui.allocate_exact_size(vec2(64.0, 60.0), Sense::hover());
+ let top = Rect::from_min_max(r.min, egui::pos2(r.right(), r.center().y));
+ let bottom = Rect::from_min_max(egui::pos2(r.left(), r.center().y), r.max);
+ widgets::paint_chip(ui, top, &Paint::solid(*new));
+ widgets::paint_chip(ui, bottom, &Paint::solid(*original));
+ ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Outside);
+ ui.interact(top, ui.id().with("cp-new"), Sense::hover()).on_hover_text("New");
+ ui.interact(bottom, ui.id().with("cp-original"), Sense::click()).on_hover_text("Original: click to restore").clicked()
+ }
+
+ /// The HSB and RGB fields with the channel radios, hex, Lab and CMYK. Returns the edited colour
+ /// and the newly chosen channel.
+ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option<Picked>, Option<Channel>) {
+ let t = Tokens::get(ui.ctx());
+ let rgb = p.color.to_rgb();
+ let lab = p.color.to_lab();
+ let cms = cms::active();
+ let cmyk = p.color.to_cmyk_managed(cms.settings().intent);
+ let mut edit = None;
+ let mut chosen = None;
+ egui::Grid::new("cp-values").num_columns(4).spacing([6.0, 4.0]).show(ui, |ui| {
+ for i in 0..7 {
+ if let Some(&ch) = Channel::ALL.get(i) {
- if widgets::radio(ui, ch.label(), ch == channel) {
++ if widgets::radio(ui, ch.label(), ch == channel, true) {
+ chosen = Some(ch);
+ }
+ let (v, suffix) = match i {
+ 0 => (p.hsb[0], "°"),
+ 1 | 2 => (p.hsb[i] * 100.0, "%"),
+ _ => (rgb[i - 3] * 255.0, ""),
+ };
+ if let Some(nv) = widgets::plain_field(ui, ("cp-left", i), v as f64, suffix, 0, VALUE_W) {
+ let nv = nv as f32;
+ edit = Some(match i {
+ 0..3 => {
+ let mut hsb = p.hsb;
+ hsb[i] = if i == 0 { nv.clamp(0.0, 360.0) } else { (nv / 100.0).clamp(0.0, 1.0) };
+ Picked::from_hsb(hsb)
+ }
+ _ => {
+ let mut c = rgb;
+ c[i - 3] = (nv / 255.0).clamp(0.0, 1.0);
+ Picked::of(Color::rgb(c[0], c[1], c[2]))
+ }
+ });
+ }
+ } else if let Some(c) = widgets::hex_field(ui, "cp-hex", &hex_digits(&p.color)).as_deref().and_then(parse_hex) {
+ edit = Some(Picked::of(c));
+ }
+ let (label, v, suffix) = match i {
+ 0 => ("L", lab.l, ""),
+ 1 => ("a", lab.a, ""),
+ 2 => ("b", lab.b, ""),
+ _ => (["C", "M", "Y", "K"][i - 3], cmyk[i - 3] * 100.0, "%"),
+ };
+ ui.horizontal(|ui| {
+ ui.add_space(12.0);
+ ui.label(egui::RichText::new(label).size(12.5).color(t.text));
+ });
+ if let Some(nv) = widgets::plain_field(ui, ("cp-right", i), v as f64, suffix, 0, VALUE_W) {
+ let nv = nv as f32;
+ edit = Some(Picked::of(if i < 3 {
+ let mut l = [lab.l, lab.a, lab.b];
+ l[i] = if i == 0 { nv.clamp(0.0, 100.0) } else { nv.clamp(-128.0, 127.0) };
+ cms.from_lab(Lab::new(l[0], l[1], l[2]))
+ } else {
+ let mut k = cmyk;
+ k[i - 3] = (nv / 100.0).clamp(0.0, 1.0);
+ Color::cmyk(k[0], k[1], k[2], k[3])
+ }));
+ }
+ ui.end_row();
+ }
+ });
+ (edit, chosen)
+ }
+
+ /// The document's colour swatches as a list; returns the clicked swatch's colour.
+ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, current: &Color) -> Option<Color> {
+ let t = Tokens::get(ui.ctx());
+ let mut chosen = None;
+ ui.allocate_ui(vec2(FIELD + 28.0, FIELD), |ui| {
+ widgets::list_box(ui, |ui| {
+ egui::ScrollArea::vertical().id_salt("cp-swatches").max_height(FIELD).show(ui, |ui| {
+ ui.set_width(FIELD + 24.0);
+ let Some(st) = app.session.active() else {
+ widgets::dim_label(ui, "Open a document to see its swatches.");
+ return;
+ };
+ let doc = &st.doc;
+ for s in doc.swatches.iter().chain(doc.swatch_groups.iter().flat_map(|g| g.swatches.iter())) {
+ let Paint::Solid { color, .. } = &s.paint else { continue };
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(r, 0.0, t.hover);
+ }
+ let chip = Rect::from_min_size(r.left_center() + vec2(4.0, -7.0), vec2(14.0, 14.0));
+ widgets::swatch_tile(ui, chip, &s.paint, color == current, false);
+ ui.painter().text(
+ egui::pos2(chip.right() + 8.0, r.center().y),
+ egui::Align2::LEFT_CENTER,
+ &s.name,
+ egui::FontId::proportional(12.0),
+ t.text,
+ );
+ if resp.clicked() {
+ chosen = Some(*color);
+ }
+ }
+ });
+ });
+ });
+ chosen
+ }
+
+ /// OK: apply the colour to the proxy (as CMYK in a CMYK document).
+ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
+ let mut c = picked(d).color;
+ if matches!(c, Color::Rgb { .. }) && app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) {
+ let [cy, m, y, k] = c.to_cmyk_managed(cms::active().settings().intent);
+ c = Color::cmyk(cy, m, y, k);
+ }
+ let cmd = if d.bool("stroke") { "paint.setStroke" } else { "paint.setFill" };
+ super::run_and_close(app, cmd, json!({ "color": color_json(&c) }))
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use vectorcraft_engine::Session;
+
+ use super::*;
+ use crate::panels::color::in_gamut;
+
+ fn app() -> VectorcraftApp {
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
+ app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
+ app
+ }
+
+ fn frame(app: &mut VectorcraftApp) {
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx);
+ let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx()));
+ out.textures_delta.clear();
+ }
+
+ fn fill_hex(app: &VectorcraftApp) -> String {
+ crate::panels::current_paints(app).0.color().unwrap().to_hex()
+ }
+
+ #[test]
+ fn field_and_slider_map_back_per_channel() {
+ let p = Picked::of(Color::rgb8(51, 153, 204));
+ for ch in Channel::ALL {
+ let (z, x, y) = field_pos(ch, &p);
+ assert_eq!(field_pick(ch, z, x, y).color.to_hex(), "#3399cc", "{ch:?}");
+ assert_eq!(Channel::parse(ch.id()), Some(ch));
+ }
+ // Hue: x is saturation, y brightness (white at the top left, black along the bottom).
+ assert_eq!(field_pick(Channel::Hue, 0.0, 0.0, 0.0).color.to_hex(), "#ffffff");
+ assert_eq!(field_pick(Channel::Hue, 0.0, 1.0, 0.0).color.to_hex(), "#ff0000");
+ assert_eq!(field_pick(Channel::Hue, 0.5, 1.0, 1.0).color.to_hex(), "#000000");
+ // Red: the slider is red, x blue and y green (green grows upwards).
+ assert_eq!(field_pick(Channel::Red, 1.0, 1.0, 0.0).color.to_hex(), "#ffffff");
+ assert_eq!(field_pick(Channel::Red, 0.0, 1.0, 1.0).color.to_hex(), "#0000ff");
+ assert_eq!(field_pick(Channel::Green, 1.0, 0.0, 1.0).color.to_hex(), "#00ff00");
+ assert_eq!(field_pick(Channel::Blue, 0.0, 1.0, 1.0).color.to_hex(), "#ff0000");
+ // The hue slider shows the spectrum whatever the colour; the others vary one component.
+ assert_eq!(slider_color(Channel::Hue, 1.0 / 3.0, 0.0, 1.0).to_hex(), "#00ff00");
+ assert_eq!(slider_color(Channel::Saturation, 0.0, 0.0, 0.0).to_hex(), "#ffffff");
+ // A grey keeps the hue it was picked with.
+ let grey = field_pick(Channel::Hue, 0.5, 0.0, 0.5);
+ assert_eq!(grey.hsb[0], 180.0);
+ assert_eq!(field_pos(Channel::Hue, &grey).0, 0.5);
+ }
+
+ #[test]
+ fn only_web_colors_snaps() {
+ let p = Picked::of(Color::rgb8(230, 120, 40));
+ assert_eq!(p.snapped(false), p);
+ assert_eq!(p.snapped(true).color.to_hex(), "#ff6633");
+ assert!(is_web_safe(&p.snapped(true).color));
+ let mut d = Dialog::new(KIND, json!({"color": "#e67828", "webOnly": true}));
+ assert_eq!(picked(&d).color.to_hex(), "#ff6633");
+ d.fields.insert("webOnly".into(), json!(false));
+ assert_eq!(picked(&d).color.to_hex(), "#e67828");
+ }
+
+ #[test]
+ fn gamut_correction_gives_a_printable_colour() {
+ let mut app = app();
+ let blue = Color::rgb(0.0, 0.0, 1.0);
+ assert!(blue.out_of_gamut());
+ let fix = in_gamut(&mut app, &blue).expect("pure blue can't be printed");
+ assert!(!fix.out_of_gamut(), "{fix:?}");
+ assert!(matches!(fix, Color::Rgb { .. }));
+ assert_eq!(in_gamut(&mut app, &Color::rgb8(128, 128, 128)), None);
+ // The dialog and the Color panel ask through a cache.
+ let ctx = egui::Context::default();
+ assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), Some(fix));
+ assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), Some(fix));
+ assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &Color::rgb8(128, 128, 128)), None);
+ }
+
+ #[test]
+ fn open_set_hex_and_confirm_fills() {
+ let mut app = app();
+ app.run("ui.colorPicker", json!({})).unwrap();
+ let d = app.ui.dialog.as_ref().unwrap();
+ assert_eq!(super::super::DialogKind::of(&d.kind), Some(super::super::DialogKind::ColorPicker));
+ assert_eq!(d.str("hex"), "FFFFFF", "starts from the fill");
+ assert!(!d.bool("stroke"));
+ frame(&mut app);
+ // `ui.dialog.set {field: "hex"}` then `ui.dialog.confirm`.
+ app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("00ff00"));
+ frame(&mut app);
+ assert_eq!(app.ui.dialog.as_ref().unwrap().str("hex"), "00FF00");
+ super::super::confirm(&mut app).unwrap();
+ assert!(app.ui.dialog.is_none());
+ assert_eq!(fill_hex(&app), "#00ff00");
+ // Without a frame in between, a set hex still wins; `color` works as well.
+ app.run("ui.colorPicker", json!({"stroke": true})).unwrap();
+ app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("#3366CC"));
+ super::super::confirm(&mut app).unwrap();
+ assert_eq!(crate::panels::current_paints(&app).1.color().unwrap().to_hex(), "#3366cc");
+ // The stroke proxy is in front now: the opener follows it unless told otherwise.
+ app.run("ui.colorPicker", json!({})).unwrap();
+ assert!(app.ui.dialog.as_ref().unwrap().bool("stroke"));
+ app.run("ui.colorPicker", json!({"stroke": false})).unwrap();
+ app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!({"c": 0, "m": 1, "y": 1, "k": 0}));
+ super::super::confirm(&mut app).unwrap();
+ assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Cmyk { .. })), "CMYK is kept");
+ assert!(app.run("ui.colorPicker", json!({"color": "nope"})).is_err());
+ // Colours take every form the paint commands take (CMYK in percent too).
+ app.run("ui.colorPicker", json!({"stroke": false, "color": {"c": 0, "m": 100, "y": 100, "k": 0}})).unwrap();
+ super::super::confirm(&mut app).unwrap();
+ assert_eq!(crate::panels::current_paints(&app).0.color(), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)));
+ }
+
+ #[test]
+ fn every_mode_draws_and_cmyk_documents_get_cmyk() {
+ let mut app = app();
+ for fields in
+ [json!({"channel": "red"}), json!({"channel": "brightness", "webOnly": true}), json!({"swatches": true}), json!({"color": "#0000ff"})]
+ {
+ app.run("ui.colorPicker", json!({})).unwrap();
+ let d = app.ui.dialog.as_mut().unwrap();
+ for (k, v) in fields.as_object().unwrap() {
+ d.fields.insert(k.clone(), v.clone());
+ }
+ frame(&mut app);
+ assert!(app.ui.dialog.is_some());
+ }
+ app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
+ app.run("ui.colorPicker", json!({"color": "#ff0000"})).unwrap();
+ super::super::confirm(&mut app).unwrap();
+ assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Cmyk { .. })));
+ }
+ }
diff --cc crates/ui-egui/src/dialogs/mod.rs
index 2066fb3ce,f79ce01d4..5d2072933
--- a/crates/ui-egui/src/dialogs/mod.rs
+++ b/crates/ui-egui/src/dialogs/mod.rs
@@@ -9,8 -9,8 +9,9 @@@
mod about;
mod all_tools;
mod artboard_options;
+ mod color_picker;
mod command;
+pub mod confirm;
mod document_setup;
mod effect;
mod export_for_screens;
@@@ -132,11 -129,7 +134,12 @@@ registry!
Shortcuts: ["shortcuts"] => DialogSpec::window(crate::shortcut_editor::show, |app, _| crate::shortcut_editor::confirm(app)),
Workspaces: ["newWorkspace", "manageWorkspaces"] => DialogSpec::window(crate::workspaces::show, |app, _| crate::workspaces::confirm(app)),
FindFont: ["findFont"] => DialogSpec::window(crate::find_font::show, |app, _| crate::find_font::confirm(app)),
+ SwatchOptions: [swatch_options::KIND] => swatch_options::SPEC,
+ Confirm: [confirm::KIND] => confirm::SPEC,
+ NewSwatch: [new_swatch::KIND] => new_swatch::SPEC,
+ NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC,
+ GradientStop: ["gradientStop"] => gradient_stop::SPEC,
+ ColorPicker: [color_picker::KIND] => color_picker::SPEC,
}
/// The spec for a `Dialog::kind` ([`DialogSpec::FORM`] when unregistered).
diff --cc crates/ui-egui/src/dialogs/swatch_options.rs
index 0800c2992,000000000..1c48608e9
mode 100644,000000..100644
--- a/crates/ui-egui/src/dialogs/swatch_options.rs
+++ b/crates/ui-egui/src/dialogs/swatch_options.rs
@@@ -1,267 -1,0 +1,267 @@@
+//! Swatch Options: name, colour type (process or spot), Global, colour mode with sliders and hex,
+//! previewed live on the canvas (Cancel rolls the preview back). Double-clicking a swatch opens it
+//! for a solid colour; gradients open the Gradient panel and patterns pattern editing ([`open`]).
+//!
+//! Fields: `__swatch` (the swatch being edited), `name`, `spot`, `global`, `mode` (`gray`, `rgb`,
+//! `hsb`, `cmyk` or `web`), `color` (`"#rrggbb"` or a colour object such as
+//! `{"model": "cmyk", "c": 0.1, "m": 0.2, "y": 0.3, "k": 0}`) and `preview`.
+
+use egui::vec2;
+use serde_json::{Value, json};
+use vectorcraft_color::{Color, Paint};
+
+use super::{DialogSpec, form, run_and_close};
+use crate::VectorcraftApp;
+use crate::panels::color::{Mode, components, from_components, parse_hex, track_color, web_safe};
+use crate::state::Dialog;
+use crate::theme::Tokens;
+use crate::widgets;
+
+/// The dialog kind of Swatch Options.
+pub const KIND: &str = "swatchOptions";
+
+pub(super) const SPEC: DialogSpec =
+ DialogSpec { heading: |_| "Swatch Options".into(), body, confirm, preview: true, min_width: 340.0, ..DialogSpec::FORM };
+
+/// Colour modes with their `mode` field / `swatch.edit` ids.
+const MODES: [(Mode, &str); 5] = [(Mode::Grayscale, "gray"), (Mode::Rgb, "rgb"), (Mode::Hsb, "hsb"), (Mode::Cmyk, "cmyk"), (Mode::WebSafe, "web")];
+
+const TYPES: [&str; 2] = ["Process Color", "Spot Color"];
+
+pub(super) fn mode_id(m: Mode) -> &'static str {
+ MODES.iter().find(|x| x.0 == m).map_or("rgb", |x| x.1)
+}
+
+fn mode_of(d: &Dialog) -> Mode {
+ let id = d.str("mode");
+ MODES.iter().find(|x| x.1 == id).map_or(Mode::Rgb, |x| x.0)
+}
+
+/// The dialog's colour: a hex string or a serialized colour.
+pub(super) fn color_of(d: &Dialog) -> Color {
+ match d.fields.get("color") {
+ Some(Value::String(s)) => Color::from_hex(s),
+ Some(v) => serde_json::from_value(v.clone()).ok(),
+ None => None,
+ }
+ .unwrap_or(Color::BLACK)
+}
+
+fn set_color(d: &mut Dialog, c: Color) {
+ d.fields.insert("color".into(), json!(c));
+}
+
+/// Open the editor of swatch `name`: Swatch Options for a colour, the Gradient panel (with the
+/// gradient applied to the active proxy) for a gradient, pattern editing for a pattern.
+pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> {
+ let sw = app.session.active().and_then(|st| st.doc.swatch(name).cloned()).ok_or_else(|| format!("no swatch `{name}`"))?;
+ match &sw.paint {
+ Paint::Solid { color, .. } => {
+ let fields = json!({
+ "__swatch": name, "name": name, "spot": sw.spot, "global": sw.global,
+ "mode": mode_id(Mode::of(color)), "color": color, "preview": true,
+ });
+ app.ui.dialog = Some(Dialog::new(KIND, fields));
+ Ok(Value::Null)
+ }
+ Paint::Gradient(_) => {
- app.run(crate::panels::paint_target(app), json!({"swatch": name}))?;
++ app.run(crate::panels::proxy_cmd(app, false), json!({"swatch": name}))?;
+ app.ui.open_panel = Some("gradient".into());
+ Ok(Value::Null)
+ }
+ Paint::Pattern { pattern, .. } => {
+ app.run("object.pattern.edit", json!({"name": pattern}))?;
+ app.ui.open_panel = Some("patternOptions".into());
+ Ok(Value::Null)
+ }
+ Paint::None => Err(format!("`{name}` has no options")),
+ }
+}
+
+/// `swatch.edit` parameters from the fields.
+fn edit_params(d: &Dialog) -> Value {
+ json!({
+ "name": d.str("__swatch"),
+ "newName": d.str("name"),
+ "color": color_of(d),
+ "mode": d.str("mode"),
+ "global": d.bool("global"),
+ "spot": d.bool("spot"),
+ })
+}
+
+fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
+ let changed = editor(ui, d);
+ ui.add_space(8.0);
+ let mut pv = d.bool("preview");
+ let pv_changed = widgets::check(ui, "Preview", pv, true);
+ if pv_changed {
+ pv = !pv;
+ d.fields.insert("preview".into(), json!(pv));
+ }
+ if pv && (changed || pv_changed || !app.session.in_interaction()) {
+ let _ = app.session.begin_interaction("Swatch Options");
+ if let Err(e) = app.session.preview("swatch.edit", &edit_params(d)) {
+ app.status(e.to_string());
+ }
+ } else if !pv && pv_changed {
+ let _ = app.session.cancel_interaction();
+ }
+ false
+}
+
+/// Drop the preview and apply the edit as one undo step (which also updates the default paints).
+fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
+ let _ = app.session.cancel_interaction();
+ run_and_close(app, "swatch.edit", edit_params(d))
+}
+
+/// The fields' grid of the swatch dialogs.
+pub(super) fn grid<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
+ egui::Grid::new("swatch-options").num_columns(2).spacing([10.0, 8.0]).show(ui, add).inner
+}
+
+/// A dimmed field label in the swatch dialogs' grid.
+pub(super) fn label(ui: &mut egui::Ui, s: &str) {
+ ui.label(egui::RichText::new(s).color(Tokens::get(ui.ctx()).text_dim));
+}
+
+/// The Swatch Name row of the grid. Returns true when it changed.
+pub(super) fn name_row(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
+ label(ui, "Swatch Name:");
+ let changed = form::text(ui, d, "name", 190.0);
+ ui.end_row();
+ changed
+}
+
+/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders and
+/// hex. Returns true when anything changed.
+pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
+ let mut changed = false;
+ grid(ui, |ui| {
+ changed |= name_row(ui, d);
+ label(ui, "Color Type:");
+ let spot = d.bool("spot");
+ if let Some(i) = widgets::dropdown(ui, "swatch-type", TYPES[usize::from(spot)], &TYPES, 200.0) {
+ d.fields.insert("spot".into(), json!(i == 1));
+ changed = true;
+ }
+ ui.end_row();
+ ui.label("");
+ // Spot colours are always global.
+ let global = spot || d.bool("global");
+ if widgets::check(ui, "Global", global, !spot) {
+ d.fields.insert("global".into(), json!(!global));
+ changed = true;
+ }
+ ui.end_row();
+ label(ui, "Color Mode:");
+ let mode = mode_of(d);
+ let labels: Vec<&str> = Mode::ALL.iter().map(|m| m.1).collect();
+ let current = Mode::ALL.iter().find(|m| m.0 == mode).map_or("RGB", |m| m.1);
+ if let Some(i) = widgets::dropdown(ui, "swatch-mode", current, &labels, 200.0) {
+ let m = Mode::ALL[i].0;
+ // Switching modes converts the colour (HSB is a view of RGB), like the Color panel.
+ let base = if m == Mode::Hsb { Mode::Rgb } else { m };
+ set_color(d, from_components(base, &components(base, &color_of(d))));
+ d.fields.insert("mode".into(), json!(mode_id(m)));
+ changed = true;
+ }
+ ui.end_row();
+ });
+ ui.add_space(6.0);
+ changed | sliders(ui, d)
+}
+
+/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web)
+/// and a chip of the colour. Returns true when the colour changed.
+fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool {
+ let t = Tokens::get(ui.ctx());
+ let mode = mode_of(d);
+ let color = color_of(d);
+ // Keep the displayed components while the colour is unchanged (hue survives S = 0 etc.).
+ let key = format!("{}|{}", mode_id(mode), serde_json::to_string(&color).unwrap_or_default());
+ let comps: Vec<f32> = match d.fields.get("__comps") {
+ Some(v) if d.str("__compsKey") == key => serde_json::from_value(v.clone()).unwrap_or_else(|_| components(mode, &color)),
+ _ => components(mode, &color),
+ };
+ let mut new: Option<(Color, Vec<f32>)> = None;
+ ui.horizontal(|ui| {
+ ui.vertical(|ui| {
+ for (i, lbl) in mode.labels().iter().enumerate() {
+ ui.horizontal(|ui| {
+ ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(*lbl).size(12.5).color(t.text)));
+ let max = mode.max(i);
+ let v = comps.get(i).copied().unwrap_or(0.0);
+ let track = |x: f32| crate::panels::c32(&track_color(mode, &comps, i, x));
+ if let (Some(nv), _) = widgets::color_slider(ui, ("swatch-slider", i), v / max, 200.0, &track) {
+ let mut c2 = comps.clone();
+ c2[i] = if mode == Mode::WebSafe { ((nv * 5.0).round() / 5.0) * max } else { (nv * max).round() };
+ new = Some((from_components(mode, &c2), c2));
+ }
+ if let Some(fv) = widgets::plain_field(ui, ("swatch-field", i), v as f64, mode.suffix(i), 0, 52.0) {
+ let mut c2 = comps.clone();
+ c2[i] = (fv as f32).clamp(0.0, max);
+ new = Some((from_components(mode, &c2), c2));
+ }
+ });
+ }
+ if matches!(mode, Mode::Rgb | Mode::Hsb | Mode::WebSafe) {
+ ui.horizontal(|ui| {
+ ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new("#").size(12.5).color(t.text)));
+ let hex = color.to_hex().trim_start_matches('#').to_uppercase();
+ if let Some(c) = hex_field(ui, &hex) {
+ let c = if mode == Mode::WebSafe { web_safe(&c) } else { c };
+ new = Some((c, components(mode, &c)));
+ }
+ });
+ }
+ });
+ let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover());
+ widgets::swatch_tile(ui, r, &Paint::solid(color), false, false);
+ });
+ let Some((c, comps)) = new else { return false };
+ set_color(d, c);
+ d.fields.insert("__compsKey".into(), json!(format!("{}|{}", mode_id(mode), serde_json::to_string(&c).unwrap_or_default())));
+ d.fields.insert("__comps".into(), json!(comps));
+ true
+}
+
+/// A hex field showing `hex`; returns the colour typed into it once committed.
+fn hex_field(ui: &mut egui::Ui, hex: &str) -> Option<Color> {
+ let t = Tokens::get(ui.ctx());
+ let id = ui.id().with("swatch-hex");
+ let editing = ui.memory(|m| m.has_focus(id));
+ let mut buf: String = if editing { ui.data_mut(|m| m.get_temp::<String>(id)).unwrap_or_else(|| hex.to_string()) } else { hex.to_string() };
+ let resp = egui::Frame::NONE
+ .fill(t.input)
+ .stroke(egui::Stroke::new(1.0, if editing { t.accent } else { t.input_border }))
+ .corner_radius(2)
+ .inner_margin(egui::Margin::symmetric(6, 4))
+ .show(ui, |ui| ui.add(egui::TextEdit::singleline(&mut buf).id(id).frame(egui::Frame::NONE).desired_width(70.0).char_limit(7)))
+ .inner;
+ ui.data_mut(|m| m.insert_temp(id, buf.clone()));
+ (resp.lost_focus() && buf != hex).then(|| parse_hex(&buf)).flatten()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn fields_round_trip_modes_and_colours() {
+ for (m, id) in MODES {
+ assert_eq!(mode_of(&Dialog::new(KIND, json!({"mode": id}))), m);
+ }
+ let d = Dialog::new(KIND, json!({"color": "#ff8000"}));
+ assert_eq!(color_of(&d).to_hex(), "#ff8000");
+ let mut d = Dialog::new(KIND, json!({}));
+ set_color(&mut d, Color::cmyk(0.1, 0.2, 0.3, 0.4));
+ assert_eq!(color_of(&d), Color::cmyk(0.1, 0.2, 0.3, 0.4));
+ let p = edit_params(&Dialog::new(KIND, json!({"__swatch": "A", "name": "B", "spot": true, "color": "#000000", "mode": "cmyk"})));
+ assert_eq!(
+ (p["name"].as_str(), p["newName"].as_str(), p["spot"].as_bool(), p["mode"].as_str()),
+ (Some("A"), Some("B"), Some(true), Some("cmyk"))
+ );
+ }
+}
diff --cc crates/ui-egui/src/menus.rs
index 7d9f23254,c9010356f..9f09c4956
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -165,24 -160,12 +165,30 @@@ pub const UI_COMMANDS: &[(&str, &str, &
("help.about", "About VectorCraft", "", "{}"),
("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"),
("app.quit", "Quit VectorCraft", "Cmd+Q", "{}"),
+ (
+ "ui.swatchOptions",
+ "Swatch Options…",
+ "",
+ "{name} edit a swatch: Swatch Options for a colour (dialog `swatchOptions`, engine: swatch.edit), the Gradient panel for a gradient, pattern editing for a pattern",
+ ),
+ (
+ "ui.newSwatch",
+ "New Swatch…",
+ "",
+ "{spot?, group?: colour group name} open New Swatch for the active fill or stroke (dialog `newSwatch`, engine: swatch.new)",
+ ),
+ (
+ "ui.newColorGroup",
+ "New Color Group…",
+ "",
+ "{swatches?: [names]} open New Color Group, from those swatches or the selected artwork (dialog `newColorGroup`, engine: swatch.newGroup)",
+ ),
+ (
+ "ui.colorPicker",
+ "Color Picker…",
+ "",
+ "{stroke?: bool (default: the active proxy), color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray} (default: the proxy's colour)} open the Color Picker (fields: hex or color, channel, webOnly, swatches); OK runs paint.setFill / paint.setStroke",
+ ),
];
/// Handle a UI command. `None` = not a UI command (the engine handles it).
@@@ -508,15 -488,7 +514,16 @@@ pub fn run_ui_command(app: &mut Vectorc
},
"file.closeAll" => crate::unsaved::close_all(app, "closeAll"),
"app.quit" => crate::unsaved::close_all(app, "quit"),
+ "ui.swatchOptions" => match s("name") {
+ Some(name) => crate::dialogs::swatch_options::open(app, &name),
+ None => Err("missing `name`".into()),
+ },
+ "ui.newSwatch" => crate::dialogs::new_swatch::open(app, p.get("spot").and_then(Value::as_bool).unwrap_or(false), s("group").as_deref()),
+ "ui.newColorGroup" => {
+ let names = p.get("swatches").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect());
+ crate::dialogs::new_color_group::open(app, names.unwrap_or_default())
+ }
+ "ui.colorPicker" => crate::dialogs::open_color_picker(app, p),
_ => return None,
};
Some(r)
diff --cc crates/ui-egui/src/panels/mod.rs
index 20b4807a1,87c49631d..6efe1ca8a
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -37,8 -37,8 +37,8 @@@ pub mod transparency
use egui::{Rect, Sense, Ui, vec2};
use serde_json::{Value, json};
-use vectorcraft_color::{Color, Paint};
-use vectorcraft_doc::Node;
+use vectorcraft_color::{BlendMode, Color, Paint};
- use vectorcraft_doc::{Node, NodeKind, StrokeLayer};
++use vectorcraft_doc::{Node, StrokeLayer};
use crate::theme::Tokens;
use crate::widgets::{Live, dim_label};
@@@ -158,54 -159,51 +158,74 @@@ pub fn libraries(_app: &mut Vectorcraft
// ---------- shared helpers ----------
- /// The paint command for the active proxy (Fill or Stroke).
- pub(crate) fn paint_target(app: &VectorcraftApp) -> &'static str {
- if app.session.fill_active { "paint.setFill" } else { "paint.setStroke" }
+ /// The paint command of the active proxy (Fill or Stroke), or of the inactive one.
+ pub(crate) fn proxy_cmd(app: &VectorcraftApp, inactive: bool) -> &'static str {
+ if app.session.fill_active != inactive { "paint.setFill" } else { "paint.setStroke" }
}
+/// The first selected node, borrowed (for per-frame reads that need no copy of it).
+fn first_node(app: &VectorcraftApp) -> Option<&Node> {
+ let st = app.session.active()?;
+ st.selection.objects.first().and_then(|id| st.doc.node(*id))
+}
+
- /// Fill and stroke as the proxies show them: the first selected object's, where the Appearance
- /// panel's active item stands in for the top fill or stroke of its kind (text without one shows
- /// its first run's style); else, and for a group without its own fill or stroke, the defaults
- /// for new art.
+ /// Is Alt held? A click on a colour then paints the inactive proxy.
+ pub(crate) fn alt_held(ui: &Ui) -> bool {
+ ui.input(|i| i.modifiers.alt)
+ }
+
+ /// Apply a clicked colour, swatch or None (`params`: `{color}`, `{swatch}` or `{none}`) to the
+ /// active proxy, or with Alt held to the inactive one, which stays behind.
+ pub(crate) fn apply_click(app: &mut VectorcraftApp, ui: &Ui, mut params: Value) {
+ let alt = alt_held(ui);
+ params["focus"] = json!(!alt);
+ app.run(proxy_cmd(app, alt), params).ok();
+ }
+
+ /// Fill and stroke as the proxies show them ([`vectorcraft_engine::Session::proxy_paints`]: the
-/// first selected object's, a group's first painted object's, else the defaults for new art).
++/// Appearance panel's active item for the proxy of its kind, else the first selected object's, a
++/// group's first painted object's, else the defaults for new art).
pub(crate) fn current_paints(app: &VectorcraftApp) -> (Paint, Paint) {
- let defaults = || (app.session.paint.fill.clone(), app.session.paint.stroke.clone());
- let Some(n) = first_node(app) else { return defaults() };
- let item = app.session.appearance_item();
- if item.is_none() {
- if let NodeKind::Text(t) = &n.kind {
- let s = t.first_style();
- return (s.fill, s.stroke);
- }
- if n.is_container() && n.appearance.items.is_empty() {
- return defaults();
+ app.session.proxy_paints()
+ }
+
+ /// Whether the selected objects' fills and strokes differ (the proxies show "?"), cached per
+ /// document revision.
+ pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, bool) {
+ let Some(st) = app.session.active() else { return (false, false) };
+ let key = (st.uid, st.revision);
+ match pstate::<Option<((u64, u64), (bool, bool))>>(ctx, "proxy-mixed") {
+ Some((k, mixed)) if k == key => mixed,
+ _ => {
+ let mixed = st.proxy_mixed();
+ set_pstate(ctx, "proxy-mixed", Some((key, mixed)));
+ mixed
}
}
- let ap = &n.appearance;
- (ap.fill_for(item).map_or(Paint::None, |f| f.paint.clone()), ap.stroke_for(item).map_or(Paint::None, |s| s.paint.clone()))
}
+/// The stroke the Stroke panel, Control bar and Properties show: the Appearance panel's active
+/// item when it is a stroke, else the first selected object's top stroke.
+pub(crate) fn current_stroke(app: &VectorcraftApp) -> Option<StrokeLayer> {
+ first_node(app)?.appearance.stroke_for(app.session.appearance_item()).cloned()
+}
+
+/// Opacity and blend mode as the Transparency panel and Control bar show them: the Appearance
+/// panel's active item's, else the first selected object's.
+pub(crate) fn current_transparency(app: &VectorcraftApp) -> Option<(f32, BlendMode)> {
+ let n = first_node(app)?;
+ Some(match app.session.appearance_item().and_then(|i| n.appearance.items.get(i)) {
+ Some(it) => (it.opacity(), it.blend()),
+ None => (n.opacity, n.blend),
+ })
+}
+
+ /// Is the active proxy "?" (the selected objects' paints differ)?
+ pub(crate) fn active_mixed(app: &VectorcraftApp, ctx: &egui::Context) -> bool {
+ let (f, s) = mixed_paints(app, ctx);
+ if app.session.fill_active { f } else { s }
+ }
+
/// The paint behind the active proxy.
pub(crate) fn active_paint(app: &VectorcraftApp) -> Paint {
let (f, s) = current_paints(app);
diff --cc crates/ui-egui/src/widgets.rs
index bf6cf86f9,95b91714d..a065000b8
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@@ -661,15 -562,155 +696,141 @@@ pub fn color_slider
let thumb = vec![tip, pos2(x + 5.5, tip.y + 6.0), pos2(x + 5.5, tip.y + 10.0), pos2(x - 5.5, tip.y + 10.0), pos2(x - 5.5, tip.y + 6.0)];
let fill = if resp.dragged() || resp.hovered() { Color32::WHITE } else { t.icon };
ui.painter().add(egui::Shape::convex_polygon(thumb, fill, Stroke::new(1.0, t.border)));
- let mut out = None;
- let mut phase = Live::Idle;
- if (resp.dragged() || resp.clicked() || resp.drag_stopped())
- && let Some(p) = resp.interact_pointer_pos()
- {
- out = Some(((p.x - bar.left()) / bar.width()).clamp(0.0, 1.0));
- phase = if resp.dragged() && !resp.drag_stopped() { Live::Dragging } else { Live::Released };
+ match pointer_phase(&resp) {
+ Some((p, phase)) => (Some(((p.x - bar.left()) / bar.width()).clamp(0.0, 1.0)), phase),
+ None => (None, Live::Idle),
+ }
+ }
+
+ /// The pointer of a click or drag on `resp` and its phase (dragging, or released on click/drop).
+ pub(crate) fn pointer_phase(resp: &Response) -> Option<(Pos2, Live)> {
+ if !(resp.dragged() || resp.clicked() || resp.drag_stopped()) {
+ return None;
+ }
+ let p = resp.interact_pointer_pos()?;
+ Some((p, if resp.dragged() && !resp.drag_stopped() { Live::Dragging } else { Live::Released }))
+ }
+
+ /// A gradient strip into `rect`: `n` bands along x (or up y when `vertical`), each filled with
+ /// `track(t)` at its centre.
+ fn gradient_strip(ui: &Ui, rect: Rect, n: usize, vertical: bool, track: &dyn Fn(f32) -> Color32) {
+ let len = if vertical { rect.height() } else { rect.width() };
+ let seg = len / n as f32;
+ for i in 0..n {
+ let r = if vertical {
+ Rect::from_min_size(pos2(rect.left(), rect.bottom() - (i + 1) as f32 * seg), vec2(rect.width(), seg + 0.6))
+ } else {
+ Rect::from_min_size(pos2(rect.left() + i as f32 * seg, rect.top()), vec2(seg + 0.6, rect.height()))
+ };
+ ui.painter().rect_filled(r, 0.0, track((i as f32 + 0.5) / n as f32));
}
- (out, phase)
+ }
+
+ /// The Color Picker's 2D colour field: `color_at(x, y)` gives the colour at a point (0..1 each, y
+ /// down) and a ring marks `pos`. Returns the clicked or dragged point and the phase.
+ pub fn color_field(
+ ui: &mut Ui,
+ id: impl std::hash::Hash + std::fmt::Debug,
+ size: Vec2,
+ pos: (f32, f32),
+ color_at: &dyn Fn(f32, f32) -> Color32,
+ ) -> (Option<(f32, f32)>, Live) {
+ let t = Tokens::get(ui.ctx());
+ let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
+ let resp = ui.interact(rect, ui.id().with(id), Sense::click_and_drag());
+ let painter = ui.painter_at(rect.expand(6.0));
+ painter.add(color_mesh(rect, (32, 32), color_at));
+ painter.rect_stroke(rect, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
+ let c = pos2(rect.left() + pos.0.clamp(0.0, 1.0) * rect.width(), rect.top() + pos.1.clamp(0.0, 1.0) * rect.height());
+ painter.circle_stroke(c, 5.0, Stroke::new(1.0, Color32::BLACK));
+ painter.circle_stroke(c, 4.0, Stroke::new(1.0, Color32::WHITE));
+ match pointer_phase(&resp) {
+ Some((p, phase)) => {
+ let f = |v: f32, lo: f32, len: f32| ((v - lo) / len).clamp(0.0, 1.0);
+ (Some((f(p.x, rect.left(), rect.width()), f(p.y, rect.top(), rect.height()))), phase)
+ }
+ None => (None, Live::Idle),
+ }
+ }
+
+ /// A smoothly shaded colour area: a `cols` × `rows` grid over `rect` with `color_at(x, y)` (0..1
+ /// each, y down) at its vertices.
+ pub fn color_mesh(rect: Rect, (cols, rows): (u32, u32), color_at: &dyn Fn(f32, f32) -> Color32) -> egui::Shape {
+ let mut mesh = egui::Mesh::default();
+ let row = cols + 1;
+ mesh.reserve_vertices((row * (rows + 1)) as usize);
+ mesh.reserve_triangles((cols * rows * 2) as usize);
+ for j in 0..=rows {
+ for i in 0..=cols {
+ let (x, y) = (i as f32 / cols as f32, j as f32 / rows as f32);
+ mesh.colored_vertex(pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height()), color_at(x, y));
+ }
+ }
+ for j in 0..rows {
+ for i in 0..cols {
+ let a = j * row + i;
+ mesh.add_triangle(a, a + 1, a + row);
+ mesh.add_triangle(a + 1, a + row + 1, a + row);
+ }
+ }
+ egui::Shape::mesh(mesh)
+ }
+
+ /// The Color Picker's vertical channel slider: `track(t)` gives the colour at 0..1 (bottom to top)
+ /// and arrows on both sides mark `value`. Returns the new value and the phase.
+ pub fn channel_slider(
+ ui: &mut Ui,
+ id: impl std::hash::Hash + std::fmt::Debug,
+ value: f32,
+ size: Vec2,
+ track: &dyn Fn(f32) -> Color32,
+ ) -> (Option<f32>, Live) {
+ let t = Tokens::get(ui.ctx());
+ let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
+ let resp = ui.interact(rect, ui.id().with(id), Sense::click_and_drag());
+ let bar = rect.shrink2(vec2(6.0, 0.0));
+ gradient_strip(ui, bar, (bar.height() / 2.0).ceil().max(2.0) as usize, true, track);
+ ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
+ let y = bar.bottom() - value.clamp(0.0, 1.0) * bar.height();
+ let fill = if resp.dragged() || resp.hovered() { t.text_strong } else { t.icon };
+ for (x, d) in [(rect.left(), 1.0), (rect.right(), -1.0)] {
+ let tip = pos2(x + d * 5.0, y);
+ ui.painter().add(egui::Shape::convex_polygon(vec![tip, pos2(x, y + 4.0 * d), pos2(x, y - 4.0 * d)], fill, Stroke::NONE));
+ }
+ match pointer_phase(&resp) {
+ Some((p, phase)) => (Some(((bar.bottom() - p.y) / bar.height()).clamp(0.0, 1.0)), phase),
+ None => (None, Live::Idle),
+ }
+ }
+
-/// A radio button (a ring, dotted when selected) with a label. Returns true when clicked.
-pub fn radio(ui: &mut Ui, label: &str, selected: bool) -> bool {
- let t = Tokens::get(ui.ctx());
- let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(12.5), t.text);
- let (rect, resp) = ui.allocate_exact_size(vec2(18.0 + galley.size().x, 20.0f32.max(galley.size().y)), Sense::click());
- let c = pos2(rect.left() + 6.5, rect.center().y);
- ui.painter().circle(c, 6.0, t.input, Stroke::new(1.0, if resp.hovered() { t.text } else { t.button_border }));
- if selected {
- ui.painter().circle_filled(c, 3.5, t.accent_strong);
- }
- ui.painter().galley(pos2(rect.left() + 18.0, rect.center().y - galley.size().y / 2.0), galley, t.text);
- resp.clicked()
-}
-
+ /// A hex colour field (`E67828`, no `#`) after a `#` label. Returns the text on commit when it
+ /// changed.
+ pub fn hex_field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, hex: &str) -> Option<String> {
+ let t = Tokens::get(ui.ctx());
+ ui.label(egui::RichText::new("#").size(15.0).color(t.text));
+ let id = ui.id().with(id);
+ let editing = ui.memory(|m| m.has_focus(id));
+ let mut buf: String = if editing { ui.data_mut(|d| d.get_temp::<String>(id)).unwrap_or_else(|| hex.to_string()) } else { hex.to_string() };
+ let resp = egui::Frame::NONE
+ .fill(t.input)
+ .stroke(Stroke::new(1.0, if editing { t.accent } else { t.input_border }))
+ .corner_radius(2)
+ .inner_margin(egui::Margin::symmetric(6, 4))
+ .show(ui, |ui| {
+ ui.add(
+ egui::TextEdit::singleline(&mut buf)
+ .id(id)
+ .frame(egui::Frame::NONE)
+ .desired_width(62.0)
+ .char_limit(7)
+ .font(egui::FontId::proportional(12.5))
+ .text_color(t.text_strong),
+ )
+ })
+ .inner;
+ let commit = resp.lost_focus() && buf != hex;
+ ui.data_mut(|d| d.insert_temp(id, buf.clone()));
+ commit.then_some(buf)
}
/// One swatch tile (Illustrator: 1 px dark frame, white inset on hover/selection).
diff --cc docs/control-protocol.md
index 7f9934696,eb69b6c84..4aacf46a4
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@@ -19,18 -19,5 +19,20 @@@
| `ui.render` | `{path?, scale?}` | render the artboard headlessly (PNG) |
| `ui.resize` / `ui.focus` | | |
| `app.open` / `app.save` / `app.export` / `app.quit` | `{path}` / `{path?}` / `{path?, format?, artboard?, range?, scale?, …}` | `app.open` reads every format `document.open` reads (see `document.formats`). `app.export` encodes through the engine's `document.export` (same options; the document keeps its path) and writes `path` through the host; without `path` it returns `{dataBase64, format, bytes}`, as headless mode does. `app.quit`, `file.close` and `file.closeAll` first open a `saveChanges` dialog for each modified document (they return `{"pending": "saveChanges"}`): `ui.dialog.confirm` saves, `ui.dialog.set {field: "discard", value: true}` then confirm discards, `ui.dialog.cancel` cancels the whole close or quit |
+| `ui.dialog.*` on `gradientStop` | `{field: "color" \| "opacity" \| "location", value}` | double-clicking a stop on the Gradient tool's annotator opens its popover (fields `index`, `x`, `y`, `tab`); set `color` (hex), `opacity` or `location` (percentages) and `ui.dialog.confirm` to apply them to the selected stop. `gradient.selectStop {index}` picks the stop the annotator, the panels and Delete/←/→ (`ui.key`) act on |
+
+Swatch editors: `engine.execute` with `ui.swatchOptions {name}` opens the `swatchOptions` dialog for a colour swatch
+(fields `name`, `spot`, `global`, `mode`: `gray`/`rgb`/`hsb`/`cmyk`/`web`, `color`: `"#rrggbb"` or a colour object,
+`preview`), which previews on the canvas while open; `ui.dialog.confirm` applies it with `swatch.edit` as one undo
+step and `ui.dialog.cancel` rolls the preview back. Gradient swatches open the Gradient panel and pattern swatches
+pattern editing instead.
+
+Confirmations: deleting swatches from the Swatches panel opens a `confirm` dialog (fields `message`, `detail`);
+`ui.dialog.confirm` runs the command it asks about (here `swatch.delete`) and `ui.dialog.cancel` drops it.
+
+New swatches and colour groups: `ui.newSwatch {spot?, group?}` opens the `newSwatch` dialog prefilled from the active
+fill or stroke (fields as in `swatchOptions` plus `group`; a gradient or pattern only takes `name`) and
+`ui.newColorGroup {swatches?}` opens `newColorGroup` (fields `name`, `fromArtwork`, `toGlobal`, `includeTints`,
+`swatches`); `ui.dialog.confirm` runs `swatch.new` / `swatch.newGroup`.
+
+ The Color Picker is a dialog too: `engine.execute {command: "ui.colorPicker", params: {stroke?, color?}}` opens it for the fill (or stroke) proxy; `ui.dialog.set {field: "hex", value: "00FF00"}` (or `color`, `channel`, `webOnly`, `swatches`) then `ui.dialog.confirm` applies the colour through `paint.setFill` / `paint.setStroke`.
diff --cc docs/mcp.md
index 8ca47cb8d,d3d4265a9..345bdde95
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@@ -68,16 -73,6 +73,17 @@@ objects' fills or strokes differ (`fill
| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. |
| `undo` / `redo` | `{}` | |
+Appearance stacks: an object can carry several fills and strokes (`appearance.addFill`, `appearance.addStroke`), indexed
+in paint order (0 is painted first, the bottom row of the Appearance panel). `paint.setFill`, `paint.setStroke`,
+`stroke.set`, `stroke.setAdvanced`, `paint.editGradient`, `paint.setGradientGeom` and `transparency.set` take
+`item` to edit one of them; `run_command appearance.setActiveItem {"index": n}` makes that row the target of later
- calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes.
++calls that omit `item` (as clicking the row in the Appearance panel does) until the selection changes; the proxy of
++its kind (`paint.proxies`) and the Gradient tool's annotator then show that row.
+`inspect_document` reports it as `paint.appearanceItem`. Live effects take the same `item` to apply to one fill or
+stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and
+`effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects;
+`apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`.
+
Errors (unknown tool, bad arguments, a disabled or failing command) come back as a normal result with
`isError: true` and a message. The model can read the message and retry.