Skip to content

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

Merge wp/B2

bflatastic0f169b5c5d05
diff --cc crates/doc/src/appearance.rs
index 53dde758c,98e9604a4..7fa32f352
--- a/crates/doc/src/appearance.rs
+++ b/crates/doc/src/appearance.rs
@@@ -540,14 -540,14 +540,49 @@@ impl Appearance
_ => None,
})
}
-- /// Does a fill or stroke carry a gradient that is fitted to the bounds on each render?
-- pub fn has_unplaced_gradient(&self) -> bool {
++ /// Gradient paints of the fills and strokes.
++ fn gradients(&self) -> impl Iterator<Item = &vectorcraft_color::GradientPaint> {
++ self.items.iter().filter_map(|i| match i {
++ AppearanceItem::Fill(FillLayer { paint: Paint::Gradient(g), .. })
++ | AppearanceItem::Stroke(StrokeLayer { paint: Paint::Gradient(g), .. }) => Some(&**g),
++ _ => None,
++ })
++ }
++ /// Is `self` equal to `other`, placed gradients within rounding (1e-6 pt) of each other, as
++ /// moving them between boxes leaves them?
++ pub fn approx_eq(&self, other: &Appearance) -> bool {
++ if self == other {
++ return true;
++ }
++ let mut a = self.clone();
++ for (g, o) in a.gradients_mut().zip(other.gradients()) {
++ if let (Some(ga), Some(go)) = (&mut g.geom, &o.geom)
++ && ga.start.distance(go.start) <= 1e-6
++ && ga.end.distance(go.end) <= 1e-6
++ && (ga.aspect - go.aspect).abs() <= 1e-6
++ {
++ *ga = *go;
++ }
++ }
++ a == *other
++ }
++ /// Does a fill or stroke carry a gradient whose placement `placed` is (some: placed in document
++ /// space; none: fitted to the bounds on each render)?
++ fn has_gradient(&self, placed: bool) -> bool {
self.items.iter().any(|i| match i {
AppearanceItem::Fill(FillLayer { paint: Paint::Gradient(g), .. })
-- | AppearanceItem::Stroke(StrokeLayer { paint: Paint::Gradient(g), .. }) => g.geom.is_none(),
++ | AppearanceItem::Stroke(StrokeLayer { paint: Paint::Gradient(g), .. }) => g.geom.is_some() == placed,
_ => false,
})
}
++ /// Does a fill or stroke carry a gradient that is fitted to the bounds on each render?
++ pub fn has_unplaced_gradient(&self) -> bool {
++ self.has_gradient(false)
++ }
++ /// Does a fill or stroke carry a placed gradient (start and end in document space)?
++ pub fn has_placed_gradient(&self) -> bool {
++ self.has_gradient(true)
++ }
/// Fix unplaced gradients to their fit on `bounds` (the object's geometric bounds; strokes fit
/// the stroke-inflated box), so they can follow transforms that refitting wouldn't reproduce.
pub fn pin_gradients(&mut self, bounds: vectorcraft_geom::Rect) {
diff --cc crates/doc/src/lib.rs
index f0bdd7ce3,a0a2bb621..2faf41955
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@@ -270,43 -259,17 +270,74 @@@ impl Default for GridPrefs
pub struct GraphicStyle {
pub name: String,
pub appearance: Appearance,
+ /// Stable id linked objects refer to ([`Node::graphic_style`]); 0 until first needed (styles
+ /// from older files get one when an object is first linked to them).
+ #[serde(default, skip_serializing_if = "skip::is_default")]
+ pub id: u32,
+ #[serde(default = "one", skip_serializing_if = "skip::is_one")]
+ pub opacity: f32,
+ #[serde(default, skip_serializing_if = "skip::is_default")]
+ pub blend: vectorcraft_color::BlendMode,
+ #[serde(default, skip_serializing_if = "skip::is_default")]
+ pub isolate: bool,
+ #[serde(default, skip_serializing_if = "skip::is_default")]
+ pub knockout: Knockout,
+ /// Placed gradients are stored relative to the unit box (0, 0)–(1, 1), so applying the style
+ /// places them on each object's own bounds. Styles saved before this kept document
+ /// coordinates (false).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub unit_box: bool,
}
+fn one() -> f32 {
+ 1.0
+}
+
+/// The name of the style new documents list first (Sort by Name keeps it first).
+pub const DEFAULT_GRAPHIC_STYLE: &str = "Default Graphic Style";
+
impl GraphicStyle {
- /// A style with `appearance` and default transparency (no id yet).
- /// A style whose placed gradients (if any) are in unit-box space.
++ /// The box a style's placed gradients are stored relative to.
++ pub const UNIT_BOX: Rect = Rect::new(0.0, 0.0, 1.0, 1.0);
++
++ /// A style with `appearance` (its placed gradients, if any, in unit-box space) and default
++ /// transparency (no id yet).
pub fn new(name: impl Into<String>, appearance: Appearance) -> Self {
- Self { name: name.into(), appearance, id: 0, opacity: 1.0, blend: Default::default(), isolate: false, knockout: Knockout::Neutral }
- Self { name: name.into(), appearance, unit_box: true }
++ Self {
++ name: name.into(),
++ appearance,
++ id: 0,
++ opacity: 1.0,
++ blend: Default::default(),
++ isolate: false,
++ knockout: Knockout::Neutral,
++ unit_box: true,
++ }
+ }
- /// A style capturing `n`'s transparency and `appearance`.
++ /// A style capturing `n`'s transparency and `appearance` (in unit-box space).
+ pub fn of(name: impl Into<String>, appearance: Appearance, n: &Node) -> Self {
+ Self { opacity: n.opacity, blend: n.blend, isolate: n.isolate, knockout: n.knockout, ..Self::new(name, appearance) }
+ }
++ /// The style's appearance as object `n` takes it: placed gradients stored in unit-box space
++ /// land at the same place relative to `n`'s geometric bounds.
++ pub fn appearance_on(&self, n: &Node) -> std::borrow::Cow<'_, Appearance> {
++ let placed = self.unit_box && self.appearance.has_placed_gradient();
++ match n.geometric_bounds().filter(|_| placed) {
++ Some(b) => {
++ let mut ap = self.appearance.clone();
++ ap.rebase_gradients(Self::UNIT_BOX, b);
++ std::borrow::Cow::Owned(ap)
++ }
++ None => std::borrow::Cow::Borrowed(&self.appearance),
++ }
++ }
+ /// Give `n` this style's transparency.
+ pub fn apply_transparency(&self, n: &mut Node) {
+ (n.opacity, n.blend, n.isolate, n.knockout) = (self.opacity, self.blend, self.isolate, self.knockout);
+ }
+ /// Does `n` have this style's transparency?
+ pub fn transparency_matches(&self, n: &Node) -> bool {
+ (n.opacity, n.blend, n.isolate, n.knockout) == (self.opacity, self.blend, self.isolate, self.knockout)
}
}
diff --cc crates/engine/src/cmd/style.rs
index 323cde949,18d9abd0d..09920a44b
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@@ -1,14 -1,7 +1,19 @@@
-//! The Graphic Styles panel: apply, new, delete and duplicate.
+//! The Graphic Styles panel: new, apply (replace or add), link, redefine, break link, rename,
+//! delete, duplicate, sort and list.
+//!
+//! Applying a style links the targeted objects to it ([`Node::graphic_style`]). An object stays
+//! linked while it keeps the style's look; editing its appearance or transparency breaks the link
+//! ([`in_sync`]), and Redefine Graphic Style updates only the objects still linked.
++//!
++//! Styles keep placed gradients relative to the unit box ([`GraphicStyle::unit_box`]): a new or
++//! redefined style stores them relative to its source's bounds, and each object a style is applied
++//! to gets them at the same place relative to its own.
+
+use std::collections::HashMap;
use serde_json::{Value, json};
+use vectorcraft_doc::{Appearance, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, Node, NodeId, NodeKind};
+ use vectorcraft_geom::Rect;
use super::*;
use crate::EngineError;
@@@ -20,8 -16,8 +25,8 @@@ pub fn specs() -> Vec<CommandSpec>
"Apply Graphic Style",
["Window", "Graphic Styles"],
None,
- "{name, add?: bool, ids?} give the objects (default: the selection; a group's contents) the style's appearance, and themselves its opacity, blend mode, isolate and knockout, and link them to it; add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks",
- "{name, ids?} give the selection (or ids) the style's appearance; its placed gradients land at the same place relative to each object's bounds",
- has_selection,
++ "{name, add?: bool, ids?} give the objects (default: the selection; a group's contents) the style's appearance, and themselves its opacity, blend mode, isolate and knockout, and link them to it (placed gradients land at the same place relative to each object's bounds); add: true (Alt-click) adds its fills, strokes and effects on top of the existing appearance instead and unlinks",
+ has_doc,
style_apply
),
cmd!(
@@@ -29,243 -25,36 +34,255 @@@
"New Graphic Style",
["Window", "Graphic Styles"],
None,
- "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'); links the object. Names are made unique → {name}",
- "{name?} from the first selected object's appearance (placed gradients are kept relative to its bounds) → {name}",
- has_selection,
++ "{name?, id?} a style from object `id` or the first selected object: its appearance, opacity, blend mode, isolate and knockout (a group without fills or strokes of its own lends its topmost object's, type its characters'; placed gradients are kept relative to its bounds); links the object. Names are made unique → {name}",
+ has_doc,
style_new
),
- cmd!("graphicStyle.delete", "Delete Graphic Style", ["Window", "Graphic Styles"], None, "{name}", has_doc, style_delete),
- cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name}", has_doc, style_duplicate),
+ cmd!(
+ "graphicStyle.delete",
+ "Delete Graphic Style",
+ ["Window", "Graphic Styles"],
+ None,
+ "{name} | {names: [name…]} delete styles; their objects keep their look but are unlinked",
+ has_doc,
+ style_delete
+ ),
+ cmd!("graphicStyle.duplicate", "Duplicate Graphic Style", ["Window", "Graphic Styles"], None, "{name} → {name}", has_doc, style_duplicate),
+ cmd!(
+ query "graphicStyle.list",
+ "List Graphic Styles",
+ [],
+ None,
+ "{} → {styles: [{id, name, fill, stroke, strokeWidth, fills, strokes, effects: [effect id…], opacity: 0..100, blend, isolate, knockout: \"on\"|\"off\"|\"neutral\", linked: [object ids]}], selected: the style the first selected object is linked to, or null}",
+ has_doc,
+ style_list
+ ),
+ cmd!(
+ "graphicStyle.redefine",
+ "Redefine Graphic Style",
+ ["Window", "Appearance"],
+ None,
+ "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object; the objects still linked to it update, and that object becomes linked → {name}",
+ has_doc,
+ style_redefine
+ ),
+ cmd!(
+ "graphicStyle.breakLink",
+ "Break Link to Graphic Style",
+ ["Window", "Graphic Styles"],
+ None,
+ "{ids?} unlink the objects (default: the selection) from their graphic style; they keep their look",
+ has_doc,
+ style_break_link
+ ),
+ cmd!(
+ "graphicStyle.rename",
+ "Rename Graphic Style",
+ ["Window", "Graphic Styles"],
+ None,
+ "{name, to} (Graphic Style Options; names are unique and linked objects stay linked) → {name}",
+ has_doc,
+ style_rename
+ ),
+ cmd!(
+ query "graphicStyle.unused",
+ "Select All Unused",
+ ["Window", "Graphic Styles"],
+ None,
+ "{} → {names: [the styles no object is linked to]} (the panel selects them)",
+ has_doc,
+ style_unused
+ ),
+ cmd!(
+ "graphicStyle.sortByName",
+ "Sort by Name",
+ ["Window", "Graphic Styles"],
+ None,
+ "{} sort the styles by name (the Default Graphic Style stays first)",
+ has_doc,
+ style_sort
+ ),
]
}
+// ---------- links ----------
+
+/// Does a style applied to `n` (`top`: `n` is the target itself) descend into its children? Groups
+/// and layers style their contents, and so do other containers (blends…) inside them, while a
+/// compound path takes it as a whole, as with paint commands ([`leaf_targets`]).
+fn descends(n: &Node, top: bool) -> bool {
+ match n.kind {
+ NodeKind::Group { .. } | NodeKind::Layer { .. } => true,
+ NodeKind::Compound { .. } => false,
+ _ => !top && n.is_container(),
+ }
+}
+
+/// The objects whose appearance a style applied to `n` sets: `n`, or its painted contents.
+fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
+ match n.children() {
+ Some(ch) if descends(n, top) => ch.iter().for_each(|c| painted(c, false, out)),
+ _ => out.push(n),
+ }
+}
+
+/// [`painted`], mutably (copying only the nodes on the way).
+fn paint_mut(n: &mut Node, top: bool, f: &mut impl FnMut(&mut Node)) {
+ if !descends(n, top) {
+ return f(n);
+ }
+ for c in n.children_mut().into_iter().flatten() {
+ paint_mut(std::sync::Arc::make_mut(c), false, f);
+ }
+}
+
+/// Does `n` still have style `g`'s look (its transparency, and its appearance on every painted
+/// object)? Linked objects that don't are no longer linked.
+pub(crate) fn in_sync(n: &Node, g: &GraphicStyle) -> bool {
+ let mut leaves = vec![];
+ painted(n, true, &mut leaves);
- g.transparency_matches(n) && leaves.iter().all(|l| l.appearance == g.appearance)
++ g.transparency_matches(n) && leaves.iter().all(|l| g.appearance_on(l).approx_eq(&l.appearance))
+}
+
+/// The style `n` is linked to (and still looks like).
+pub(crate) fn linked_style<'a>(d: &'a Document, n: &Node) -> Option<&'a GraphicStyle> {
+ d.graphic_style_by_id(n.graphic_style?).filter(|g| in_sync(n, g))
+}
+
+/// Objects anywhere in the art that `f` accepts.
+fn objects_where(d: &Document, mut f: impl FnMut(&Node) -> bool) -> Vec<NodeId> {
+ let mut ids = vec![];
+ for l in &d.layers {
+ l.walk(&mut |n| {
+ if f(n) {
+ ids.push(n.id);
+ }
+ });
+ }
+ ids
+}
+
+/// The objects linked to each style id.
+fn links(d: &Document) -> HashMap<u32, Vec<NodeId>> {
+ let mut out: HashMap<u32, Vec<NodeId>> = HashMap::new();
+ for l in &d.layers {
+ l.walk(&mut |n| {
+ if let Some(g) = linked_style(d, n) {
+ out.entry(g.id).or_default().push(n.id);
+ }
+ });
+ }
+ out
+}
+
++/// `ap` with its placed gradients moved from box `from` (an object's bounds) to the unit box.
++fn unitized(mut ap: Appearance, from: Option<Rect>) -> Appearance {
++ if let Some(b) = from.filter(|_| ap.has_placed_gradient()) {
++ ap.rebase_gradients(b, GraphicStyle::UNIT_BOX);
++ }
++ ap
++}
++
+/// The appearance a new or redefined style takes from `n`: its own. A group without fills or
+/// strokes of its own lends those of its topmost painted object, and type its characters' fill
- /// and stroke.
++/// and stroke. Placed gradients come relative to the unit box (from the bounds of the object
++/// they're on).
+fn captured(n: &Node) -> Appearance {
+ let mut ap = n.appearance.clone();
+ if !ap.items.is_empty() {
- return ap;
++ return unitized(ap, n.geometric_bounds());
+ }
+ match &n.kind {
+ NodeKind::Text(t) => {
+ if let Some(r) = t.runs.first() {
+ ap.items = Appearance::basic(r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width).items;
++ // Type paints its characters in text space.
++ ap = unitized(ap, Some(t.local_bounds()));
+ }
+ }
+ _ => {
+ let mut leaves = vec![];
+ painted(n, true, &mut leaves);
+ if let Some(top) = leaves.last().filter(|l| l.id != n.id) {
+ // The topmost object's own effects apply before the group's.
+ let top = captured(top);
+ ap.items = top.items;
+ ap.effects.splice(0..0, top.effects);
+ }
+ }
+ }
+ ap
+}
+
+/// Give `id` style `g` (its painted objects the appearance, itself the transparency) and link it.
+fn apply_style(d: &mut Document, id: NodeId, g: &GraphicStyle) {
+ if let Some(n) = d.node_mut(id) {
- paint_mut(n, true, &mut |l| l.appearance = g.appearance.clone());
++ paint_mut(n, true, &mut |l| l.appearance = g.appearance_on(l).into_owned());
+ g.apply_transparency(n);
+ n.graphic_style = Some(g.id);
+ }
+}
+
+fn set_link(d: &mut Document, ids: &[NodeId], link: Option<u32>) {
+ for id in ids {
+ if let Some(n) = d.node_mut(*id) {
+ n.graphic_style = link;
+ }
+ }
+}
+
+fn style_index(d: &Document, name: &str) -> Result<usize> {
+ d.graphic_style_index(name).ok_or_else(|| EngineError::Other(format!("no graphic style `{name}`")))
+}
+
+/// The object a style is made from: `id`, else the first selected object.
+fn source<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<(NodeId, &'a Node)> {
+ let id = match id_param(p, "id") {
+ Some(id) => id,
+ None => super::edit::selected_roots(s)?.first().copied().ok_or_else(|| bad(cmd, "select an object (or pass `id`)"))?,
+ };
+ Ok((id, s.doc()?.doc.node(id).ok_or_else(|| bad(cmd, format!("no object {}", id.0)))?))
+}
+
+impl Session {
+ /// The graphic style of the first selected object: the one it was last linked to, and whether
+ /// it is still linked (still has that style's look).
+ pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> {
+ let st = self.active()?;
+ let n = st.doc.node(*st.selection.objects.first()?)?;
+ let g = st.doc.graphic_style_by_id(n.graphic_style?)?;
+ Some((g, in_sync(n, g)))
+ }
+}
+
+// ---------- commands ----------
+
fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("graphicStyle.apply", "missing name"))?;
- let style = s
- .doc()?
- .doc
- .graphic_styles
- .iter()
- .find(|g| g.name == name)
- .cloned()
- .ok_or_else(|| EngineError::Other(format!("no graphic style `{name}`")))?;
- let ids = paint_targets(s, p)?;
+ let i = style_index(&s.doc()?.doc, name)?;
+ let add = bool_or(p, "add", false);
+ let ids = super::appearance::appearance_targets(s, p)?;
+ if ids.is_empty() {
+ return Err(bad("graphicStyle.apply", "nothing selected (or pass `ids`)"));
+ }
s.edit("Apply Graphic Style", |d, _| {
- for id in &ids {
- if let Some(n) = d.node_mut(*id) {
- let mut ap = style.appearance.clone();
- if style.unit_box
- && let Some(b) = n.geometric_bounds()
- {
- ap.rebase_gradients(UNIT_BOX, b);
+ if add {
- let ap = d.graphic_styles[i].appearance.clone();
++ let g = d.graphic_styles[i].clone();
+ for id in &ids {
+ if let Some(n) = d.node_mut(*id) {
+ paint_mut(n, true, &mut |l| {
- l.appearance.items.extend(ap.items.iter().cloned());
- l.appearance.effects.extend(ap.effects.iter().cloned());
++ let ap = g.appearance_on(l).into_owned();
++ l.appearance.items.extend(ap.items);
++ l.appearance.effects.extend(ap.effects);
+ });
+ n.graphic_style = None;
}
- n.appearance = ap;
+ }
+ } else {
+ d.graphic_style_id(i);
+ let g = d.graphic_styles[i].clone();
+ for id in &ids {
+ apply_style(d, *id, &g);
}
}
Ok(())
diff --cc crates/engine/src/lib.rs
index 91362a01b,104d3418f..8cdb54b84
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -754,8 -758,8 +758,10 @@@ mod tests_file
#[cfg(test)]
mod tests_gradient;
#[cfg(test)]
+ mod tests_gradpanel;
+ #[cfg(test)]
+mod tests_knockout;
+#[cfg(test)]
mod tests_live;
#[cfg(test)]
mod tests_menucmds;
diff --cc crates/engine/src/tests_gradpanel.rs
index 000000000,51e66cb5c..104dff923
mode 000000,100644..100644
--- a/crates/engine/src/tests_gradpanel.rs
+++ b/crates/engine/src/tests_gradpanel.rs
@@@ -1,0 -1,153 +1,168 @@@
+ //! Gradient panel and gradient behaviour: sampling a colour into a gradient stop (M3.33) and
+ //! copied appearances placing their gradients on the target's own bounds (M3.34) and the
+ //! Gradient tool's snapping and Eyedropper Options (M3.35).
+
+ use serde_json::json;
+ use vectorcraft_color::{GradientGeom, Paint};
+ use vectorcraft_geom::Point;
+
+ use super::*;
+
+ fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
+ s
+ }
+
+ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
+ let r = s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
+ NodeId(r["id"].as_u64().unwrap())
+ }
+
+ fn stop_hexes(s: &Session, id: NodeId, stroke: bool) -> Vec<String> {
+ let a = &s.doc().unwrap().doc.node(id).unwrap().appearance;
+ match if stroke { a.stroke_paint() } else { a.fill_paint() } {
+ Paint::Gradient(g) => g.gradient.stops.iter().map(|s| s.color.to_hex()).collect(),
+ p => panic!("expected a gradient, got {p:?}"),
+ }
+ }
+
+ #[test]
+ fn sample_color_with_a_stop_recolours_that_stop_in_one_undo_step() {
+ let mut s = session();
+ let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
+ // A solid fill: no stop to recolour.
+ let err = s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 0})).unwrap_err();
+ assert!(err.to_string().contains("not a gradient"), "{err}");
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 1})).unwrap();
+ assert_eq!(stop_hexes(&s, id, false), ["#ffffff", "#ff0000"]);
+ assert!(s.execute("paint.sampleColor", &json!({"color": "#ff0000", "stop": 2})).unwrap_err().to_string().contains("no stop 2"));
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(stop_hexes(&s, id, false), ["#ffffff", "#000000"]);
+ // The stroke's gradient through `stroke`, the fill left alone.
+ s.execute("paint.setStroke", &json!({"gradient": {}})).unwrap();
+ s.execute("paint.sampleColor", &json!({"color": "#00ff00", "stop": 0, "stroke": true})).unwrap();
+ assert_eq!(
+ (stop_hexes(&s, id, true), stop_hexes(&s, id, false)),
+ (vec!["#00ff00".into(), "#000000".into()], vec!["#ffffff".into(), "#000000".into()])
+ );
+ }
+
+ fn fill_geom(s: &Session, id: NodeId) -> Option<GradientGeom> {
+ match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
+ Paint::Gradient(g) => g.geom,
+ p => panic!("expected a gradient, got {p:?}"),
+ }
+ }
+
+ fn close(a: Point, b: Point) -> bool {
+ a.distance(b) < 1e-9
+ }
+
+ /// A 100 × 100 source at (10, 10) with a placed gradient from 20 % to 80 % across its middle,
+ /// and a 200 × 100 target at x = 500.
+ fn source_and_target() -> (Session, NodeId, NodeId) {
+ let mut s = session();
+ let src = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"gradient": {"start": [30, 60], "end": [90, 60]}})).unwrap();
+ let dst = rect(&mut s, 500.0, 10.0, 200.0, 100.0);
+ (s, src, dst)
+ }
+
+ #[test]
+ fn the_eyedropper_places_copied_gradients_on_the_target() {
+ let (mut s, src, dst) = source_and_target();
+ s.execute("appearance.copyFrom", &json!({"source": src.0, "ids": [dst.0]})).unwrap();
+ let g = fill_geom(&s, dst).expect("placed");
+ assert!(close(g.start, Point::new(540.0, 60.0)) && close(g.end, Point::new(660.0, 60.0)), "{g:?}");
+ // The source keeps its own; new art fits the gradient to itself.
+ assert!(close(fill_geom(&s, src).unwrap().start, Point::new(30.0, 60.0)));
+ assert!(matches!(&s.paint.fill, Paint::Gradient(g) if g.geom.is_none()));
+ // The eyedropper tool's click runs the same command.
+ s.execute("select.set", &json!({"ids": [dst.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.select_tool("eyedropper", ViewInfo::default()).unwrap();
+ let ev = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Down, 50.0, 50.0);
+ s.pointer(&ev, ViewInfo::default()).unwrap();
+ assert!(close(fill_geom(&s, dst).unwrap().start, Point::new(540.0, 60.0)));
+ }
+
+ #[test]
+ fn graphic_styles_keep_gradients_relative_to_the_bounds() {
+ let (mut s, src, dst) = source_and_target();
+ s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
+ s.execute("graphicStyle.new", &json!({"name": "Glow"})).unwrap();
+ let style = s.doc().unwrap().doc.graphic_styles.iter().find(|g| g.name == "Glow").cloned().unwrap();
+ let Paint::Gradient(g) = style.appearance.fill_paint() else { panic!() };
+ assert!(style.unit_box && close(g.geom.unwrap().start, Point::new(0.2, 0.5)), "stored in unit-box space: {g:?}");
+ s.execute("select.set", &json!({"ids": [dst.0]})).unwrap();
+ s.execute("graphicStyle.apply", &json!({"name": "Glow"})).unwrap();
+ let g = fill_geom(&s, dst).unwrap();
+ assert!(close(g.start, Point::new(540.0, 60.0)) && close(g.end, Point::new(660.0, 60.0)), "{g:?}");
++ // Both stay linked (each has the style's look on its own bounds); redefining the style from an
++ // edited source moves the new placement onto the linked target's bounds too.
++ let linked = |s: &mut Session| {
++ let list = s.execute("graphicStyle.list", &json!({})).unwrap();
++ list["styles"].as_array().unwrap().iter().find(|g| g["name"] == "Glow").unwrap()["linked"].clone()
++ };
++ assert_eq!(linked(&mut s), json!([src.0, dst.0]));
++ s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
++ s.execute("paint.setFill", &json!({"gradient": {"start": [13.3, 47.7], "end": [97.1, 71.9]}})).unwrap();
++ assert_eq!(linked(&mut s), json!([dst.0]), "the edited source is no longer linked");
++ s.execute("graphicStyle.redefine", &json!({"name": "Glow"})).unwrap();
++ let g = fill_geom(&s, dst).unwrap();
++ assert!(close(g.start, Point::new(506.6, 47.7)) && close(g.end, Point::new(674.2, 71.9)), "{g:?}");
++ assert_eq!(linked(&mut s), json!([src.0, dst.0]));
++ s.execute("select.set", &json!({"ids": [dst.0]})).unwrap();
+ // The flag survives a save; a style from an older file (no flag) keeps document coordinates.
+ let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, false);
+ let back = vectorcraft_format::load(&bytes).unwrap();
+ assert_eq!(back.graphic_styles, s.doc().unwrap().doc.graphic_styles);
+ let legacy: vectorcraft_doc::GraphicStyle = serde_json::from_value(json!({"name": "Old", "appearance": style.appearance})).unwrap();
+ assert!(!legacy.unit_box);
+ s.edit("Add", |d, _| {
+ d.graphic_styles.push(legacy);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("graphicStyle.apply", &json!({"name": "Old"})).unwrap();
+ assert!(close(fill_geom(&s, dst).unwrap().start, Point::new(0.2, 0.5)), "legacy styles are applied as stored");
+ }
+
+ #[test]
+ fn eyedropper_options_choose_what_copy_from_takes() {
+ let mut s = session();
+ let src = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.execute("transparency.set", &json!({"opacity": 40})).unwrap();
+ let dst = rect(&mut s, 200.0, 10.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
+ assert_eq!(s.execute("eyedropper.setOptions", &json!({})).unwrap(), json!({"appearance": true, "transparency": true}));
+ assert_eq!(s.execute("eyedropper.setOptions", &json!({"appearance": false})).unwrap(), json!({"appearance": false, "transparency": true}));
+ let n = |s: &Session| s.doc().unwrap().doc.node(dst).unwrap().clone();
+ s.execute("appearance.copyFrom", &json!({"source": src.0, "ids": [dst.0]})).unwrap();
+ assert_eq!((n(&s).opacity, n(&s).appearance.fill_paint().color().unwrap().to_hex()), (0.4, "#ffffff".into()));
+ // Params override the options for one call.
+ s.execute("appearance.copyFrom", &json!({"source": src.0, "ids": [dst.0], "appearance": true})).unwrap();
+ assert_eq!(n(&s).appearance.fill_paint().color().unwrap().to_hex(), "#ff0000");
+ // Nothing to copy: no edit.
+ let undo = s.doc().unwrap().history.undo.len();
+ assert_eq!(s.execute("appearance.copyFrom", &json!({"source": src.0, "ids": [dst.0], "transparency": false})).unwrap(), json!({"ids": []}));
+ assert_eq!(s.doc().unwrap().history.undo.len(), undo);
+ }
+
+ #[test]
+ fn the_gradient_tool_reads_the_constrain_angle_preference() {
+ let mut s = session();
+ rect(&mut s, 100.0, 100.0, 100.0, 100.0);
+ s.execute("prefs.set", &json!({"key": "constrainAngle", "value": 30})).unwrap();
+ s.select_tool("gradient", ViewInfo::default()).unwrap();
+ let ev = |kind, x, y, shift| vectorcraft_tools::PointerEvent::new(kind, x, y).with_mods(vectorcraft_tools::Mods { shift, ..Default::default() });
+ use vectorcraft_tools::PointerKind::{Down, Drag, Up};
+ s.pointer(&ev(Down, 120.0, 180.0, false), ViewInfo::default()).unwrap();
+ s.pointer(&ev(Drag, 190.0, 140.0, true), ViewInfo::default()).unwrap();
+ s.pointer(&ev(Up, 190.0, 140.0, true), ViewInfo::default()).unwrap();
+ let id = s.doc().unwrap().selection.objects[0];
+ assert!((fill_geom(&s, id).unwrap().angle_deg() - 30.0).abs() < 1e-9);
+ }
diff --cc crates/ui-egui/src/canvas.rs
index 3825d0922,c7873d675..b879e0e82
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -136,7 -136,7 +136,7 @@@ pub fn show(app: &mut VectorcraftApp, u
handle_input(app, ui, &resp, rect);
let v = *app.view().unwrap_or(&View::default());
let xf = Xf::new(rect, &v);
- paint_drop(app, ui, &resp, &xf);
- paint_drop(app, &resp, &xf);
++ panel_drop(app, ui, &resp, &xf);
let painter = ui.painter_at(rect);
let Some(st) = app.session.active() else { return };
let doc = st.doc.clone();
@@@ -668,29 -668,22 +668,41 @@@ fn node_outline(n: &Node) -> BezPath
bp
}
-/// The art under the pointer (3 screen pixels of tolerance).
-fn hit_under_pointer(app: &VectorcraftApp, xf: &Xf) -> Option<vectorcraft_doc::hit::Hit> {
- let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0 / xf.zoom, outline: app.ui.view.outline, path_only: false };
- vectorcraft_doc::hit::hit_test(&app.session.active()?.doc, app.hover_doc?, opt)
+/// The topmost editable object under document point `p` at `zoom` (3 px tolerance).
+fn hit_at(app: &VectorcraftApp, p: Point, zoom: f64) -> Option<vectorcraft_doc::hit::Hit> {
+ let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0 / zoom, outline: app.ui.view.outline, path_only: false };
+ vectorcraft_doc::hit::hit_test(&app.session.active()?.doc, p, opt)
}
- /// Swatches and Fill/Stroke proxies dropped on art paint the object under the pointer (the active
- /// proxy's fill or stroke); a chip of the dragged paint follows the pointer meanwhile.
- fn paint_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) {
- use crate::panels::swatches;
- swatches::drag_preview(app, ui.ctx());
-/// A paint dragged out of a panel (a swatch, the Gradient panel's thumbnail) and dropped on art
-/// paints the active proxy of the object under the pointer (`paint.setFill`/`paint.setStroke`
-/// with its `ids`), selected or not.
-fn paint_drop(app: &mut VectorcraftApp, resp: &egui::Response, xf: &Xf) {
- let Some(d) = resp.dnd_release_payload::<widgets::PaintDrag>() else { return };
- let Some(hit) = hit_under_pointer(app, xf) else { return };
++/// A panel drag ([`widgets::PanelDrag`]) dropped on art acts on the object under the pointer,
++/// selected or not: a paint (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail) goes
++/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it). A
++/// chip of a dragged paint follows the pointer meanwhile.
++fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) {
++ crate::panels::swatches::drag_preview(app, ui.ctx());
+ let Some(pos) = ui.input(|i| i.pointer.interact_pos()) else { return };
+ // Not through a floating panel over the canvas.
+ if ui.ctx().layer_id_at(pos).is_some_and(|l| l != resp.layer_id) {
+ return;
+ }
- let Some(mut params) = swatches::released_paint(app, resp) else { return };
++ let Some(d) = resp.dnd_release_payload::<widgets::PanelDrag>() else { return };
+ let Some(hit) = hit_at(app, xf.to_doc(pos), xf.zoom) else { return };
- params["ids"] = json!([hit.leaf.0]);
- params["focus"] = json!(false);
- if let Err(e) = app.run(crate::panels::proxy_cmd(app, false), params) {
+ let Some(st) = app.session.active() else { return };
- let mut params = d.params.clone();
- params["ids"] = json!([vectorcraft_tools::xform::paint_owner(&st.doc, hit.leaf).0]);
- app.run(crate::panels::proxy_cmd(app, false), params).ok();
++ let (cmd, params) = match &*d {
++ widgets::PanelDrag::Paint { params, .. } => {
++ // Colour groups paint nothing.
++ if params.is_null() {
++ return;
++ }
++ let mut params = params.clone();
++ params["ids"] = json!([vectorcraft_tools::xform::paint_owner(&st.doc, hit.leaf).0]);
++ params["focus"] = json!(false);
++ (crate::panels::proxy_cmd(app, false), params)
++ }
++ };
++ if let Err(e) = app.run(cmd, params) {
+ app.status(e);
+ }
}
fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) {
@@@ -1108,35 -1100,29 +1120,39 @@@ mod tests
}
#[test]
- fn a_paint_dropped_on_art_paints_that_object_selected_or_not() {
+ fn swatches_and_proxy_paints_dropped_on_art_fill_the_object_hit() {
- use crate::panels::swatches::SwatchDrag;
- use vectorcraft_color::{Color, Paint};
++ use vectorcraft_color::{Color, GradientGeom, GradientPaint, Paint};
++ use widgets::{PanelDrag, SwatchRows};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
- let id = app.session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
+ let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.session.execute("select.none", &json!({})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
- let at = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(Point::new(150.0, 150.0));
- let drop = |app: &mut VectorcraftApp, at: Pos2, params: serde_json::Value| {
- egui::DragAndDrop::set_payload(&ctx, widgets::PaintDrag { paint: vectorcraft_color::Paint::None, params });
- frame(app, &ctx, vec![egui::Event::PointerMoved(at)]);
+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
- let release = |at: Pos2| {
- vec![
- egui::Event::PointerMoved(at),
- egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() },
- ]
++ let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| {
++ let at = xf.to_screen(at);
++ egui::DragAndDrop::set_payload(&ctx, d);
+ let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
- frame(app, &ctx, vec![up]);
++ frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]);
};
- drop(&mut app, at, json!({"color": "#ff0000"}));
let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint();
- let drag = SwatchDrag { grabbed: "Red".into(), names: vec!["Red".into()], groups: false };
- assert_eq!(fill(&app).color().map(|c| c.to_hex()), Some("#ff0000".into()));
- assert!(app.session.active().unwrap().selection.is_empty(), "the drop does not select");
- // Off the art nothing changes.
- drop(&mut app, at - vec2(0.0, 120.0), json!({"color": "#00ff00"}));
- assert_eq!(fill(&app).color().map(|c| c.to_hex()), Some("#ff0000".into()));
- // A gradient fits the object it lands on.
- drop(&mut app, at, json!({"gradient": {}}));
- assert!(matches!(fill(&app), vectorcraft_color::Paint::Gradient(g) if g.geom.is_none()));
++ let red = Paint::solid(Color::from_hex("#ed1c24").unwrap());
++ let rows = SwatchRows { grabbed: "Red".into(), names: vec!["Red".into()], groups: false };
++ let swatch = PanelDrag::Paint { paint: red.clone(), params: json!({"swatch": "Red"}), rows: Some(rows) };
+ // Off the art nothing happens.
- egui::DragAndDrop::set_payload(&ctx, drag.clone());
- frame(&mut app, &ctx, release(xf.to_screen(Point::new(300.0, 250.0))));
++ drop(&mut app, swatch.clone(), Point::new(300.0, 250.0));
+ assert_eq!(fill(&app), Paint::solid(Color::WHITE));
- egui::DragAndDrop::set_payload(&ctx, drag);
- frame(&mut app, &ctx, release(xf.to_screen(Point::new(100.0, 100.0))));
- assert_eq!(fill(&app), Paint::solid(Color::from_hex("#ed1c24").unwrap()), "paint.setFill with the hit id");
++ drop(&mut app, swatch, Point::new(100.0, 100.0));
++ assert_eq!(fill(&app), red, "paint.setFill with the hit id");
+ assert!(app.session.active().unwrap().selection.is_empty(), "the selection stays as it was");
+ // A proxy's paint works the same.
- egui::DragAndDrop::set_payload(&ctx, Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
- frame(&mut app, &ctx, release(xf.to_screen(Point::new(60.0, 60.0))));
++ drop(&mut app, PanelDrag::paint(Paint::solid(Color::rgb(0.0, 0.0, 1.0))), Point::new(60.0, 60.0));
+ assert_eq!(fill(&app), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
++ // A dragged gradient (the Gradient panel's thumbnail, a proxy) fits the object it lands on.
++ let mut g = GradientPaint::new(Default::default());
++ g.geom = Some(GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0 });
++ drop(&mut app, PanelDrag::paint(Paint::Gradient(Box::new(g))), Point::new(100.0, 100.0));
++ assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none()));
}
}
diff --cc crates/ui-egui/src/menus.rs
index ca5e7473a,247bf02be..80ce683d8
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -189,12 -189,12 +189,18 @@@ pub const UI_COMMANDS: &[(&str, &str, &
"",
"{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",
),
+ (
+ "ui.graphicStyleOptions",
+ "Graphic Style Options…",
+ "",
+ "{name?} open Graphic Style Options (dialog `graphicStyleOptions`, field `name`): for style `name` OK renames it (graphicStyle.rename); without, OK makes a new style of that name from the selection (graphicStyle.new)",
+ ),
+ (
+ "tool.options",
+ "Tool Options…",
+ "",
+ "{tool: id} what double-clicking a tool button opens: gradient → the Gradient panel (window.panel), eyedropper → Eyedropper Options (dialog `command` running eyedropper.setOptions, fields appearance, transparency)",
+ ),
];
/// Handle a UI command. `None` = not a UI command (the engine handles it).
@@@ -530,7 -530,7 +536,8 @@@ pub fn run_ui_command(app: &mut Vectorc
crate::dialogs::new_color_group::open(app, names.unwrap_or_default())
}
"ui.colorPicker" => crate::dialogs::open_color_picker(app, p),
+ "ui.graphicStyleOptions" => crate::dialogs::graphic_style_options::open(app, s("name").as_deref()),
+ "tool.options" => crate::toolbar::open_options(app, &s("tool").unwrap_or_default()),
_ => return None,
};
Some(r)
diff --cc crates/ui-egui/src/panels/gradient.rs
index 80583ce0b,848e39cb0..84b1ed2e7
--- a/crates/ui-egui/src/panels/gradient.rs
+++ b/crates/ui-egui/src/panels/gradient.rs
@@@ -1,15 -1,25 +1,25 @@@
- //! Gradient panel: type buttons, angle / aspect ratio / reverse, the gradient slider with draggable
- //! stops and midpoint diamonds (click below the ramp adds a stop, drag a stop off to remove it),
- //! and stop Opacity / Location fields. Stop colours are edited with the Color panel.
+ //! Gradient panel: the gradient thumbnail (drag it onto art; its menu lists the document's
+ //! gradient swatches and Save to Swatches), type buttons, the Fill/Stroke proxy, angle and aspect
+ //! ratio fields with preset menus, Reverse, the gradient slider and the selected stop's fields.
+ //!
+ //! On the slider: click below the ramp to add a stop, drag a stop to move it (Alt drags a copy;
+ //! Alt-dropping it on another stop swaps their colours), drag it off to remove it, double-click it
+ //! for the stop popover, and drag a diamond to move a midpoint (a selected diamond's midpoint
+ //! shows in Location). Dropping a colour swatch on the ramp adds a stop of that colour, or
+ //! recolours the stop it lands on. Hide Options leaves the thumbnail, the proxy and the slider.
- use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
+ use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use serde_json::{Value, json};
- use vectorcraft_color::gradient::{MIN_STOPS, insert_stop, midpoint_from_pos, midpoint_pos, move_stop, remove_stop, set_midpoint};
- use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
+ use vectorcraft_color::gradient::{
+ MIN_STOPS, duplicate_stop, insert_stop, midpoint_from_pos, midpoint_pos, move_stop, remove_stop, set_midpoint, swap_stop_colors,
+ };
+ use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
+ use vectorcraft_doc::NodeId;
use super::{active_paint, live_run, pstate, set_pstate};
+ use crate::state::Dialog;
use crate::theme::Tokens;
- use crate::widgets::{self, Live, menu_item};
-use crate::widgets::{self, Live, PaintDrag, menu_item};
++use crate::widgets::{self, Live, PanelDrag, menu_item};
use crate::{VectorcraftApp, icons};
/// Dragging a stop this far below the ramp removes it.
@@@ -124,51 -225,83 +225,80 @@@ pub fn show(app: &mut VectorcraftApp, u
ui.add_space(6.0);
ramp(app, ui, &g.gradient, is_grad);
ui.add_space(4.0);
- // Stop fields.
- let sel = app.session.selected_stop().filter(|i| *i < g.gradient.stops.len());
- ui.horizontal(|ui| {
- let enabled = is_grad && sel.is_some();
- let stop = sel.and_then(|i| g.gradient.stops.get(i)).copied();
- widgets::dim_label(ui, "Opacity:");
- let op = stop.map(|s| s.opacity as f64 * 100.0).unwrap_or(100.0);
- if let Some(v) = widgets::plain_field(ui, "grad-op", op, "%", 0, 54.0)
- && enabled
- && let Some(i) = sel
- {
- let mut stops = g.gradient.stops.clone();
- stops[i].opacity = (v / 100.0).clamp(0.0, 1.0) as f32;
- edit(app, json!({"stops": stops_json(&stops)}), Live::Released);
+ stop_fields(app, ui, &g.gradient, is_grad);
+ if !is_grad {
+ widgets::dim_label(ui, "Click the ramp or a type button to apply a gradient.");
+ }
+ }
+
+ /// The gradient thumbnail (click: apply a gradient; drag: onto art) and its menu of gradient
+ /// swatches with Save to Swatches.
+ fn thumbnail(app: &mut VectorcraftApp, ui: &mut Ui, g: &GradientPaint, is_grad: bool) {
+ let t = Tokens::get(ui.ctx());
+ let (r, resp) = ui.allocate_exact_size(vec2(40.0, 40.0), Sense::click_and_drag());
+ widgets::gradient_chip(ui, r, &g.gradient);
+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
+ let resp = resp.on_hover_text("Gradient Fill: click to apply, drag onto art");
+ if resp.clicked() && !is_grad {
+ edit(app, json!({}), Live::Released);
+ }
+ // The dragged copy carries no placement: it fits the art it lands on.
- widgets::paint_drag_source(ui, &resp, || {
- let paint = Paint::Gradient(Box::new(GradientPaint { geom: None, ..g.clone() }));
- PaintDrag { params: super::paint_params(&paint), paint }
- });
++ widgets::drag_source(ui, &resp, || PanelDrag::paint(Paint::Gradient(Box::new(g.clone()))));
+ let dr = Rect::from_min_size(r.right_top() + vec2(1.0, 0.0), vec2(14.0, 40.0));
+ ui.advance_cursor_after_rect(dr);
+ let dresp = ui.interact(dr, ui.id().with("grad-swatches"), Sense::click());
+ icons::paint(ui, "chevron-down", Rect::from_center_size(dr.center(), vec2(12.0, 12.0)), if dresp.hovered() { t.text_strong } else { t.icon });
+ let dresp = dresp.on_hover_text("Gradient swatches");
+ egui::Popup::menu(&dresp).show(|ui| {
+ ui.set_min_width(200.0);
+ let mut chosen = None;
+ let swatches = gradient_swatches(app);
+ if swatches.is_empty() {
+ widgets::dim_label(ui, "No gradient swatches");
}
- widgets::dim_label(ui, "Location:");
- let loc = stop.map(|s| s.offset as f64 * 100.0).unwrap_or(0.0);
- if let Some(v) = widgets::plain_field(ui, "grad-loc", loc, "%", 1, 54.0)
- && enabled
- && let Some(i) = sel
- {
- let (stops, ni) = move_stop(&g.gradient.stops, i, (v / 100.0) as f32);
- edit(app, json!({"stops": stops_json(&stops)}), Live::Released);
- select_stop(app, ni);
+ for (name, grad) in &swatches {
+ let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
+ if resp.hovered() {
+ ui.painter().rect_filled(row, 0.0, t.hover);
+ }
+ let chip = Rect::from_min_size(row.left_center() + vec2(4.0, -8.0), vec2(16.0, 16.0));
+ widgets::gradient_chip(ui, chip, grad);
+ ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside);
+ ui.painter().text(chip.right_center() + vec2(8.0, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(12.5), t.text);
+ if resp.clicked() {
+ chosen = Some(name.clone());
+ }
}
- let can_del = enabled && g.gradient.stops.len() > MIN_STOPS;
- if widgets::icon_button_enabled(ui, "trash-2", "Delete Stop", false, can_del, 22.0).clicked()
- && let Some(i) = sel
- && let Some(stops) = remove_stop(&g.gradient.stops, i)
- {
- edit(app, json!({"stops": stops_json(&stops)}), Live::Released);
- select_stop(app, i.min(stops.len() - 1));
+ ui.separator();
+ if menu_item(ui, "Save to Swatches", is_grad, false) {
+ save_to_swatches(app, g);
+ }
+ if let Some(name) = chosen {
+ super::apply_click(app, ui, json!({ "swatch": name }));
+ ui.close();
}
});
- if let Some(i) = sel
- && is_grad
- {
- let c = g.gradient.stops[i].color;
+ }
+
+ /// The selected stop's colour (click: its popover; the eyedropper samples one from the art),
+ /// opacity and location (a selected diamond's midpoint instead), and Delete Stop.
+ fn stop_fields(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) {
+ let stops = &g.stops;
+ let sel = app.session.selected_stop().filter(|i| *i < stops.len() && is_grad);
+ let mid = selected_mid(app, ui.ctx(), stops.len()).filter(|_| is_grad);
+ let stop = sel.map(|i| stops[i]);
+ if let (Some(i), Some(s)) = (sel, stop) {
ui.horizontal(|ui| {
- widgets::dim_label(ui, "Stop color:");
+ widgets::dim_label(ui, "Color:");
let (r, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click());
- widgets::swatch_tile(ui, r, &Paint::solid(c), false, resp.hovered());
- widgets::dim_label(ui, &c.to_hex().to_uppercase());
- if resp.on_hover_text("Edit the stop in the Color panel").clicked() {
- app.ui.open_panel = Some("color".into());
+ widgets::swatch_tile(ui, r, &Paint::solid(s.color), false, resp.hovered());
+ widgets::dim_label(ui, &s.color.to_hex().to_uppercase());
+ if resp.on_hover_text("Edit the stop").clicked() {
+ open_popover(app, i, r.left_bottom() + vec2(0.0, 4.0));
+ }
+ ui.add_space(ui.available_width() - 22.0);
+ if widgets::icon_button(ui, "pipette", "Eyedropper: click the art to sample the stop's colour", false, 22.0).clicked() {
+ stop_eyedropper(app);
}
});
}
@@@ -208,11 -389,17 +386,17 @@@ fn ramp(app: &mut VectorcraftApp, ui: &
Rect::from_min_size(pos2(bar.left() + i as f32 * bar.width() / n as f32, bar.top()), vec2(bar.width() / n as f32 + 0.5, bar.height()));
ui.painter().rect_filled(rr, 0.0, Color32::from_rgba_unmultiplied(r, gg, b, a));
}
- ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
+ // A colour swatch held over the ramp: outline it as a drop target.
- let droppable = is_grad && area_resp.dnd_hover_payload::<PaintDrag>().is_some_and(|d| d.paint.color().is_some());
++ let droppable = is_grad && area_resp.dnd_hover_payload::<PanelDrag>().is_some_and(|d| d.color().is_some());
+ let edge = if droppable { Stroke::new(2.0, t.accent) } else { Stroke::new(1.0, t.border) };
+ ui.painter().rect_stroke(bar, 0.0, edge, StrokeKind::Outside);
let x_of = |o: f32| bar.left() + o * bar.width();
+ let offset_at = |p: Pos2| x_to_offset(p.x, bar.left(), bar.width());
+ let marker = |o: f32| Rect::from_min_size(pos2(x_of(o) - 6.0, bar.bottom() + 2.0), vec2(12.0, 16.0));
let sel = app.session.selected_stop();
- let mut drag: Drag = pstate(ui.ctx(), "grad-drag");
let stops = &g.stops;
+ let mid_sel = selected_mid(app, ui.ctx(), stops.len());
+ let mut drag: Drag = pstate(ui.ctx(), "grad-drag");
// While dragging, edits are computed against the stops as they were when the drag began (the
// document shows the preview).
let origin: Vec<GradientStop> = if drag == Drag::None { stops.clone() } else { pstate::<Vec<GradientStop>>(ui.ctx(), "grad-origin") };
@@@ -300,34 -516,35 +513,35 @@@
}
}
}
- // Click below the ramp (not on a stop) adds a stop; clicking the ramp applies a gradient.
- let below = Rect::from_min_max(pos2(bar.left(), bar.bottom()), pos2(bar.right(), area.bottom()));
- let resp = ui.interact(below, ui.id().with("grad-add"), Sense::click());
- if resp.hovered() && !hit_stop && is_grad {
- ui.ctx().set_cursor_icon(egui::CursorIcon::Copy);
- }
- if resp.clicked()
- && !hit_stop
- && let Some(p) = resp.interact_pointer_pos()
+ // A colour swatch dropped on the ramp.
+ if is_grad
- && let Some(d) = area_resp.dnd_release_payload::<PaintDrag>()
- && let Some(c) = d.paint.color()
++ && let Some(d) = area_resp.dnd_release_payload::<PanelDrag>()
++ && let Some(c) = d.color()
+ && let Some(p) = ui.input(|i| i.pointer.latest_pos())
{
- if is_grad {
- let (v, i) = insert_stop(g, x_to_offset(p.x, bar.left(), bar.width()));
- select = Some(i);
- changed = Some((v, Live::Released));
- } else {
- edit(app, json!({}), Live::Released);
- }
- }
- let bar_resp = ui.interact(bar, ui.id().with("grad-bar"), Sense::click());
- if bar_resp.clicked() && !is_grad {
- edit(app, json!({}), Live::Released);
+ let (v, i) = drop_color(g, stops.iter().position(|s| marker(s.offset).contains(p)), offset_at(p), c);
+ select = Some(i);
+ changed = Some((v, Live::Released));
}
set_pstate(ui.ctx(), "grad-drag", drag);
- if let Some((v, phase)) = changed {
- edit(app, json!({"stops": stops_json(&v)}), phase);
+ if let Some(i) = pick_mid {
+ set_pstate(ui.ctx(), MID_SELECTED, Some((i, first_id(app))));
+ if sel.is_some() {
+ select_stop(app, None);
+ }
+ } else if select.is_some() {
+ set_pstate(ui.ctx(), MID_SELECTED, None::<(usize, Option<NodeId>)>);
+ }
+ match changed {
+ Some((v, phase)) => set_stops(app, &v, select, phase),
+ None => {
+ if let Some(i) = select.filter(|i| sel != Some(*i)) {
+ select_stop(app, Some(i));
+ }
+ }
}
- if let Some(i) = select {
- select_stop(app, i);
+ if let Some((i, at)) = popover {
+ open_popover(app, i, at);
}
}
@@@ -361,4 -584,251 +581,251 @@@ mod tests
assert_eq!(j.as_array().unwrap().len(), 2);
assert_eq!(j[1]["midpoint"], json!(0.5));
}
+
+ #[test]
+ fn dropped_colours_recolour_or_add_an_opaque_stop() {
+ let mut g = Gradient::default();
+ g.stops[1].opacity = 0.5;
+ let red = Color::rgb(1.0, 0.0, 0.0);
+ let (v, i) = drop_color(&g, Some(1), 0.3, red);
+ assert_eq!((v.len(), i, v[1].color, v[1].opacity), (2, 1, red, 1.0));
+ let (v, i) = drop_color(&g, None, 0.3, red);
+ assert_eq!((v.len(), i, v[1].color, v[1].offset, v[1].opacity), (3, 1, red, 0.3, 1.0));
+ }
+
+ #[test]
+ fn dragged_stops_move_copy_or_swap() {
+ let g = Gradient::default();
+ let (v, i) = dragged_stops(&g.stops, 0, 0.4, false, Some(1));
+ assert_eq!((v.len(), i, v[0].offset), (2, 0, 0.4));
+ let (v, i) = dragged_stops(&g.stops, 0, 0.4, true, None);
+ assert_eq!((v.len(), i, v[1].offset, v[1].color), (3, 1, 0.4, Color::WHITE));
+ let (v, i) = dragged_stops(&g.stops, 0, 1.0, true, Some(1));
+ assert_eq!((v.len(), i, v[0].color, v[1].color), (2, 0, Color::BLACK, Color::WHITE));
+ // Dropped on itself: a copy.
+ assert_eq!(dragged_stops(&g.stops, 0, 0.0, true, Some(0)).0.len(), 3);
+ }
+
+ // ---------- headless frames ----------
+
+ /// A selected rectangle filled with `fill` (`paint.setFill` params).
+ fn app(fill: Value) -> VectorcraftApp {
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
+ app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap();
+ app.run("paint.setFill", fill).unwrap();
+ app
+ }
+
+ /// A headless Gradient panel: frames share one context and a clock.
+ struct Panel {
+ ctx: egui::Context,
+ time: f64,
+ }
+
+ impl Panel {
+ fn new() -> Self {
+ let ctx = egui::Context::default();
+ crate::theme::install_fonts(&ctx);
+ Self { ctx, time: 0.0 }
+ }
+
+ /// One frame with `events` (and `modifiers` held); returns the texts drawn and where.
+ fn frame(&mut self, app: &mut VectorcraftApp, events: Vec<Event>, modifiers: Modifiers) -> Vec<(String, Pos2)> {
+ fn texts(s: &egui::Shape, out: &mut Vec<(String, Pos2)>) {
+ match s {
+ egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.pos + t.galley.rect.center().to_vec2())),
+ egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
+ _ => {}
+ }
+ }
+ self.time += 0.1;
+ let mut events = events;
+ events.insert(0, Event::ModifiersChanged(modifiers));
+ let input = egui::RawInput {
+ time: Some(self.time),
+ events,
+ screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(260.0, 600.0))),
+ ..Default::default()
+ };
+ let mut out = self.ctx.run_ui(input, |ui| show(app, ui));
+ out.textures_delta.clear();
+ let mut v = vec![];
+ out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
+ v
+ }
+
+ /// The rect of the widget its parent ui keyed `key` (last frame).
+ fn widget(&self, key: impl std::hash::Hash + std::fmt::Debug + Copy) -> Rect {
+ self.ctx
+ .viewport(|vp| vp.prev_pass.widgets.layers().flat_map(|(_, w)| w.iter()).find(|w| w.id == w.parent_id.with(key)).map(|w| w.rect))
+ .expect("widget drawn")
+ }
+
+ fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) -> Vec<(String, Pos2)> {
+ let b = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
+ self.frame(app, vec![Event::PointerMoved(at), b(true)], Modifiers::NONE);
+ self.frame(app, vec![b(false)], Modifiers::NONE);
+ self.frame(app, vec![], Modifiers::NONE)
+ }
+
+ /// Press at `from`, move to `to` in steps and release there, with `m` held.
+ fn drag(&mut self, app: &mut VectorcraftApp, from: Pos2, to: Pos2, m: Modifiers) {
+ let b = |at, pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: m };
+ self.frame(app, vec![Event::PointerMoved(from), b(from, true)], m);
+ for k in 1..=4 {
+ self.frame(app, vec![Event::PointerMoved(from + (to - from) * (k as f32 / 4.0))], m);
+ }
+ self.frame(app, vec![b(to, false)], m);
+ self.frame(app, vec![], Modifiers::NONE);
+ }
+ }
+
+ fn fill(app: &VectorcraftApp) -> GradientPaint {
+ match crate::panels::current_paints(app).0 {
+ Paint::Gradient(g) => *g,
+ p => panic!("expected a gradient fill, got {p:?}"),
+ }
+ }
+
+ fn hexes(app: &VectorcraftApp) -> Vec<String> {
+ fill(app).gradient.stops.iter().map(|s| s.color.to_hex()).collect()
+ }
+
+ #[test]
+ fn the_proxy_toggles_fill_and_stroke_and_stays_with_options_hidden() {
+ let mut app = app(json!({"gradient": {}}));
+ let mut p = Panel::new();
+ let texts = p.frame(&mut app, vec![], Modifiers::NONE);
+ assert!(texts.iter().any(|(t, _)| t == "Opacity:"));
+ let stroke = p.widget("stroke-proxy");
+ p.click(&mut app, stroke.right_bottom() - vec2(2.0, 2.0));
+ assert!(!app.session.fill_active, "the Stroke proxy came to the front");
+ set_pstate(&p.ctx, HIDE_OPTIONS, true);
+ let texts = p.frame(&mut app, vec![], Modifiers::NONE);
+ assert!(!texts.iter().any(|(t, _)| t == "Opacity:" || t == "Type:"), "{texts:?}");
+ let fill = p.widget("fill-proxy");
+ p.click(&mut app, fill.left_top() + vec2(2.0, 2.0));
+ assert!(app.session.fill_active, "the proxy works with the options hidden");
+ p.widget(("grad-stop", 1));
+ }
+
+ #[test]
+ fn a_selected_diamond_shows_and_sets_its_midpoint_in_location() {
+ let stops = json!([{"offset": 0, "color": "#ffffff", "midpoint": 0.3}, {"offset": 1, "color": "#000000"}]);
+ let mut app = app(json!({"gradient": {"stops": stops}}));
+ app.run("gradient.selectStop", json!({"index": 1})).unwrap();
+ let mut p = Panel::new();
+ let texts = p.frame(&mut app, vec![], Modifiers::NONE);
+ assert!(texts.iter().any(|(t, _)| t == "100%"), "the stop's location: {texts:?}");
+ let diamond = p.widget(("grad-mid", 0));
+ let texts = p.click(&mut app, diamond.center());
+ assert_eq!(app.session.selected_stop(), None, "the diamond replaces the stop selection");
+ assert!(texts.iter().any(|(t, _)| t == "30%"), "the midpoint: {texts:?}");
+ // Typing a location moves the midpoint.
+ let field = texts.iter().find(|(t, _)| t == "30%").unwrap().1;
+ p.click(&mut app, field);
+ let key = |k, modifiers| Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers };
+ p.frame(&mut app, vec![key(egui::Key::A, Modifiers::COMMAND), Event::Text("60".into())], Modifiers::NONE);
+ p.frame(&mut app, vec![key(egui::Key::Enter, Modifiers::NONE)], Modifiers::NONE);
+ assert!((fill(&app).gradient.stops[0].midpoint - 0.6).abs() < 1e-6, "{:?}", fill(&app).gradient.stops);
+ // Clicking a stop selects it again.
+ let stop = p.widget(("grad-stop", 0));
+ let texts = p.click(&mut app, stop.center());
+ assert_eq!(app.session.selected_stop(), Some(0));
+ assert!(texts.iter().any(|(t, _)| t == "0%"));
+ }
+
+ #[test]
+ fn the_thumbnail_menu_applies_gradient_swatches_and_saves_one() {
+ let mut app = app(json!({"color": "#336699"}));
+ let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]);
+ app.run("swatch.new", json!({"name": "Dusk", "gradient": {"stops": stops}})).unwrap();
+ let mut p = Panel::new();
+ p.frame(&mut app, vec![], Modifiers::NONE);
+ let menu = p.widget("grad-swatches").center();
+ let texts = p.click(&mut app, menu);
+ let dusk = texts.iter().find(|(t, _)| t == "Dusk").unwrap_or_else(|| panic!("the menu lists the swatch: {texts:?}")).1;
+ assert!(texts.iter().any(|(t, _)| t.ends_with("Save to Swatches")));
+ p.click(&mut app, dusk);
+ assert_eq!(hexes(&app), ["#ff0000", "#0000ff"]);
+ // Save to Swatches adds the current gradient.
+ let before = gradient_swatches(&app).len();
+ let texts = p.click(&mut app, menu);
+ let save = texts.iter().find(|(t, _)| t.ends_with("Save to Swatches")).unwrap().1;
+ p.click(&mut app, save);
+ assert_eq!(gradient_swatches(&app).len(), before + 1);
+ }
+
+ #[test]
+ fn alt_drag_copies_a_stop_and_alt_dropping_on_a_stop_swaps_colours() {
+ let mut app = app(json!({"gradient": {}}));
+ let mut p = Panel::new();
+ p.frame(&mut app, vec![], Modifiers::NONE);
+ let (a, b) = (p.widget(("grad-stop", 0)).center(), p.widget(("grad-stop", 1)).center());
+ let mid = pos2((a.x + b.x) / 2.0, a.y);
+ let offsets = |app: &VectorcraftApp| fill(app).gradient.stops.iter().map(|s| (s.offset * 10.0).round() / 10.0).collect::<Vec<_>>();
+ // A plain drag moves the stop.
+ p.drag(&mut app, a, mid, Modifiers::NONE);
+ assert_eq!(offsets(&app), [0.5, 1.0]);
+ app.run("edit.undo", json!({})).unwrap();
+ // Alt leaves the original and drags a copy, selected on release; one undo step.
+ p.frame(&mut app, vec![], Modifiers::NONE);
+ p.drag(&mut app, a, mid, Modifiers::ALT);
+ assert_eq!((offsets(&app), hexes(&app)), (vec![0.0, 0.5, 1.0], vec!["#ffffff".to_string(), "#ffffff".into(), "#000000".into()]));
+ assert_eq!(app.session.selected_stop(), Some(1));
+ // Alt-dropping the first stop on the last swaps their colours.
+ p.drag(&mut app, a, b, Modifiers::ALT);
+ assert_eq!((offsets(&app), hexes(&app)), (vec![0.0, 0.5, 1.0], vec!["#000000".to_string(), "#ffffff".into(), "#ffffff".into()]));
+ app.run("edit.undo", json!({})).unwrap();
+ app.run("edit.undo", json!({})).unwrap();
+ assert_eq!(hexes(&app), ["#ffffff", "#000000"]);
+ }
+
+ #[test]
+ fn a_dropped_swatch_adds_or_recolours_a_stop() {
+ let mut app = app(json!({"gradient": {}}));
+ let mut p = Panel::new();
+ p.frame(&mut app, vec![], Modifiers::NONE);
+ let (a, b) = (p.widget(("grad-stop", 0)).center(), p.widget(("grad-stop", 1)).center());
+ let drop = |p: &mut Panel, app: &mut VectorcraftApp, at: Pos2| {
- egui::DragAndDrop::set_payload(&p.ctx, PaintDrag { paint: Paint::solid(Color::rgb(1.0, 0.0, 0.0)), params: json!({"color": "#ff0000"}) });
++ egui::DragAndDrop::set_payload(&p.ctx, PanelDrag::paint(Paint::solid(Color::rgb(1.0, 0.0, 0.0))));
+ p.frame(app, vec![Event::PointerMoved(at)], Modifiers::NONE);
+ let up = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE };
+ p.frame(app, vec![up], Modifiers::NONE);
+ };
+ drop(&mut p, &mut app, pos2((a.x + b.x) / 2.0, a.y - 20.0));
+ assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#000000"]);
+ p.frame(&mut app, vec![], Modifiers::NONE);
+ let last = p.widget(("grad-stop", 2)).center();
+ drop(&mut p, &mut app, last);
+ assert_eq!(hexes(&app), ["#ffffff", "#ff0000", "#ff0000"]);
+ }
+
+ #[test]
+ fn double_clicking_a_stop_opens_the_shared_popover_beside_it() {
+ let mut app = app(json!({"gradient": {}}));
+ let mut p = Panel::new();
+ p.frame(&mut app, vec![], Modifiers::NONE);
+ let stop = p.widget(("grad-stop", 1));
+ let b = |pressed| Event::PointerButton { pos: stop.center(), button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
+ p.frame(&mut app, vec![Event::PointerMoved(stop.center()), b(true), b(false), b(true), b(false)], Modifiers::NONE);
+ let d = app.ui.dialog.clone().expect("the popover opened");
+ assert_eq!(
+ (d.kind.as_str(), &d.fields["index"], &d.fields["screen"]),
+ ("gradientStop", &json!(1), &json!([stop.left(), stop.bottom() + 4.0]))
+ );
+ assert_eq!(app.session.selected_stop(), Some(1));
+ }
+
+ #[test]
+ fn the_stop_eyedropper_arms_the_eyedropper_for_the_stop() {
+ let mut app = app(json!({"gradient": {}}));
+ app.select_tool("gradient");
+ app.run("gradient.selectStop", json!({"index": 0})).unwrap();
+ let texts = Panel::new().frame(&mut app, vec![], Modifiers::NONE);
+ assert!(texts.iter().any(|(t, _)| t == "#FFFFFF"), "the stop's colour row: {texts:?}");
+ stop_eyedropper(&mut app);
+ assert_eq!((app.session.tool_id(), app.session.tool_options()), ("eyedropper", json!({"stop": "gradient"})));
+ }
}
diff --cc crates/ui-egui/src/panels/swatches.rs
index 465c7e7f6,6dca15365..4a82cb32d
--- a/crates/ui-egui/src/panels/swatches.rs
+++ b/crates/ui-egui/src/panels/swatches.rs
@@@ -1,18 -1,13 +1,18 @@@
-//! Swatches panel: proxy, Recent Colors, thumbnail grid (15.5 pt tiles on a 17 pt pitch) or list,
-//! colour groups as folders, None/Registration first, bottom bar and panel menu.
+//! Swatches panel: proxy, Recent Colors, find field, thumbnail grid (15.5 pt tiles on a 17 pt pitch)
+//! or list, colour groups as folders, None/Registration first, bottom bar and panel menu.
+//!
+//! Swatches drag to reorder, into and out of colour groups (`swatch.move`) and onto art (the active
- //! proxy's paint command with the object's id); a Fill/Stroke proxy dropped on the panel becomes a
- //! swatch (`swatch.new`).
++//! proxy's paint command with the object's id) and onto the Gradient panel's ramp; a Fill/Stroke
++//! proxy or the Gradient panel's thumbnail dropped on the panel becomes a swatch (`swatch.new`).
-use egui::{Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
-use serde_json::json;
-use vectorcraft_color::Paint;
+use egui::{Color32, Rect, Response, Sense, Shape, Stroke, StrokeKind, Ui, pos2, vec2};
+use serde_json::{Value, json};
+use vectorcraft_color::{Color, GradientKind, Paint};
+use vectorcraft_doc::Document;
use super::{active_paint, pstate, set_pstate};
use crate::theme::Tokens;
--use crate::widgets::{self, menu_item, swatch_tile};
++use crate::widgets::{self, PanelDrag, SwatchRows, menu_item, swatch_tile};
use crate::{VectorcraftApp, icons};
/// View modes of the swatch list.
@@@ -135,19 -121,27 +135,20 @@@ fn entries(app: &VectorcraftApp, kind:
out
}
- /// The paint command params that apply swatch (or Registration) `name`; `None` for colour groups
- /// and unknown names.
- fn swatch_params(d: &Document, name: &str) -> Option<Value> {
- if name == REGISTRATION {
- return Some(json!({"color": {"c": 1.0, "m": 1.0, "y": 1.0, "k": 1.0}}));
- }
- Some(if d.swatch(name)?.paint.is_none() { json!({"none": true}) } else { json!({"swatch": name}) })
-/// The paint params (`paint.setFill`) of an entry; none for a group.
-fn params(e: &Entry) -> Option<serde_json::Value> {
++/// The paint command params that apply entry `e` (`paint.setFill`); none for a colour group.
++fn swatch_params(e: &Entry) -> Option<Value> {
+ Some(match e {
+ Entry::Registration => json!({"color": {"c": 1.0, "m": 1.0, "y": 1.0, "k": 1.0}}),
+ Entry::Swatch { paint, .. } if paint.is_none() => json!({"none": true}),
+ Entry::Swatch { name, .. } => json!({"swatch": name}),
+ Entry::Folder(_) => return None,
+ })
}
/// Apply a clicked swatch to the active proxy (Alt: the inactive one).
fn apply(app: &mut VectorcraftApp, ui: &Ui, e: &Entry) {
- if let Some(params) = app.session.active().and_then(|st| swatch_params(&st.doc, e.name())) {
- if let Some(p) = params(e) {
- super::apply_click(app, ui, p);
- }
-}
-
-/// Let a swatch tile be dragged onto art or the Gradient panel's ramp.
-fn drag_source(ui: &Ui, resp: &egui::Response, e: &Entry) {
- if let Entry::Swatch { paint, .. } = e {
- widgets::paint_drag_source(ui, resp, || widgets::PaintDrag { paint: paint.clone(), params: params(e).unwrap_or_default() });
++ if let Some(params) = swatch_params(e) {
+ super::apply_click(app, ui, params);
}
}
@@@ -329,227 -237,6 +330,213 @@@ fn click_selection(ui: &Ui, mut sel: Ve
sel
}
- /// What the Swatches panel drags: the swatch, None, Registration or colour group under the pointer
- /// when the drag started (it paints art it's dropped on) and the names it moves: the panel
- /// selection when the grabbed one is part of it (only colour groups, or only swatches, like the
- /// grabbed one), in panel order.
- #[derive(Clone, Debug)]
- pub(crate) struct SwatchDrag {
- pub grabbed: String,
- pub names: Vec<String>,
- /// The names are colour groups.
- pub groups: bool,
- }
-
+/// A drag released on the panel.
+enum Drop {
+ /// Swatches (or colour groups) dropped before or `after` row `target`, into folder `target`, or
+ /// at the end (`None`).
+ Move { names: Vec<String>, target: Option<String>, after: bool },
- /// A Fill/Stroke proxy's paint dropped on row `target` (or between rows) becomes a swatch.
++ /// A paint from elsewhere (a Fill/Stroke proxy, the Gradient panel's thumbnail) dropped on row
++ /// `target` (or between rows) becomes a swatch.
+ New { paint: Paint, target: Option<String> },
+}
+
- /// A drag payload of type `T` released on `resp`. (egui's release takes any payload, so the type is
- /// checked first: a payload of another type stays for the next drop target.)
- fn released<T: std::any::Any + Send + Sync>(resp: &Response) -> Option<std::sync::Arc<T>> {
- resp.dnd_hover_payload::<T>()?;
- resp.dnd_release_payload::<T>()
++impl Drop {
++ /// What releasing `d` before or `after` row `target` (`None`: at the end) does: move the rows
++ /// it carries, or make a swatch of a paint dragged from elsewhere.
++ fn of(d: &PanelDrag, target: Option<String>, after: bool) -> Self {
++ let PanelDrag::Paint { paint, rows, .. } = d;
++ match rows {
++ Some(r) => Drop::Move { names: r.names.clone(), target, after },
++ None => Drop::New { paint: paint.clone(), target },
++ }
++ }
++}
++
++/// The drag a tile or row of `e` starts, moving rows `names`. Registration and colour groups have
++/// no paint of their own (the chip under the pointer draws Registration's mark).
++fn drag_of(e: &Entry, names: Vec<String>) -> PanelDrag {
++ let paint = if let Entry::Swatch { paint, .. } = e { paint.clone() } else { Paint::None };
++ let rows = SwatchRows { grabbed: e.name().to_string(), names, groups: e.is_folder() };
++ PanelDrag::Paint { paint, params: swatch_params(e).unwrap_or_default(), rows: Some(rows) }
+}
+
+/// What the tiles or rows saw this frame.
+#[derive(Default)]
+struct TileEvents {
+ clicked: Option<(Entry, egui::Modifiers)>,
+ /// Double-click opens the swatch's editor (Swatch Options, Gradient panel or pattern editing).
+ edit: Option<String>,
+ drop: Option<Drop>,
+ /// A drag is held over a tile or row.
+ over: bool,
+}
+
+/// Clicks, double-clicks, tooltips and drag and drop of the tile or row `resp` of entry `e`
+/// (`items`: the panel's rows, `sel`: its selection, `list`: rows stack downwards). A drag from it
- /// starts a [`SwatchDrag`]; a drag held over it shows where it would land (before or after it by
- /// the pointer's half, or into a folder) and a release there sets the drop.
++/// starts a [`PanelDrag`] carrying the rows it moves; see [`tile_drop`] for drags held over it.
+fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], sel: &[String], list: bool, ev: &mut TileEvents) {
+ let name = e.name();
+ if matches!(e, Entry::Swatch { .. }) && resp.double_clicked() {
+ ev.edit = Some(name.to_string());
+ }
+ if resp.drag_started() {
+ let with_sel = sel.iter().any(|s| s == name);
+ let names = items
+ .iter()
+ .filter(|x| x.is_folder() == e.is_folder() && (x.name() == name || (with_sel && sel.iter().any(|s| s == x.name()))))
+ .map(|x| x.name().to_string())
+ .collect();
- egui::DragAndDrop::set_payload(ui.ctx(), SwatchDrag { grabbed: name.to_string(), names, groups: e.is_folder() });
- }
- let moving = resp.dnd_hover_payload::<SwatchDrag>();
- // Swatches dropped on one of themselves stay where they are.
- if moving.as_ref().is_some_and(|d| d.names.iter().any(|n| n == name)) {
- ev.over = true;
- released::<SwatchDrag>(&resp);
- } else if moving.is_some() || resp.dnd_hover_payload::<Paint>().is_some() {
- ev.over = true;
- let t = Tokens::get(ui.ctx());
- let r = resp.rect;
- let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center());
- let after = if list { at.y > r.center().y } else { at.x > r.center().x };
- // A proxy's paint, or swatches over a folder, go into it; otherwise a bar marks the slot.
- if moving.as_ref().is_none_or(|d| e.is_folder() && !d.groups) {
- ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside);
- } else if list {
- let y = if after { r.bottom() } else { r.top() };
- ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent));
- } else {
- let x = if after { r.right() + 0.75 } else { r.left() - 0.75 };
- ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent));
- }
- let target = Some(name.to_string());
- if let Some(d) = moving.and_then(|_| released::<SwatchDrag>(&resp)) {
- ev.drop = Some(Drop::Move { names: d.names.clone(), target, after });
- } else if let Some(p) = released::<Paint>(&resp) {
- ev.drop = Some(Drop::New { paint: (*p).clone(), target });
- }
++ egui::DragAndDrop::set_payload(ui.ctx(), drag_of(e, names));
+ }
++ tile_drop(ui, &resp, e, list, ev);
+ let resp = match e {
+ Entry::Folder(n) => resp.on_hover_text(format!("Color Group: {n}")),
+ Entry::Swatch { paint, global, spot, .. } if list => resp.on_hover_ui(|ui| {
+ ui.label(format!("{name} ({})", describe(paint, *global, *spot)));
+ }),
+ _ => resp.on_hover_text(name),
+ };
+ if resp.clicked() {
+ ev.clicked = Some((e.clone(), ui.input(|i| i.modifiers)));
+ }
+}
+
++/// A drag held over the tile or row `resp` of entry `e` shows where it would land (before or after
++/// it by the pointer's half, or into a folder); a release there sets the drop.
++fn tile_drop(ui: &Ui, resp: &Response, e: &Entry, list: bool, ev: &mut TileEvents) {
++ let Some(d) = resp.dnd_hover_payload::<PanelDrag>() else { return };
++ let PanelDrag::Paint { rows, .. } = &*d;
++ let name = e.name();
++ ev.over = true;
++ // Swatches dropped on one of themselves stay where they are.
++ if rows.as_ref().is_some_and(|r| r.names.iter().any(|n| n == name)) {
++ resp.dnd_release_payload::<PanelDrag>();
++ return;
++ }
++ let t = Tokens::get(ui.ctx());
++ let r = resp.rect;
++ let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center());
++ let after = if list { at.y > r.center().y } else { at.x > r.center().x };
++ // A paint from elsewhere, or swatches over a folder, go into it; otherwise a bar marks the slot.
++ if rows.as_ref().is_none_or(|d| e.is_folder() && !d.groups) {
++ ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside);
++ } else if list {
++ let y = if after { r.bottom() } else { r.top() };
++ ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent));
++ } else {
++ let x = if after { r.right() + 0.75 } else { r.left() - 0.75 };
++ ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent));
++ }
++ if resp.dnd_release_payload::<PanelDrag>().is_some() {
++ ev.drop = Some(Drop::of(&d, Some(name.to_string()), after));
++ }
++}
++
+/// Drops between and after the tiles (`zone`: the list's viewport) go to the end of the ungrouped
+/// swatches (colour groups to the end of the groups); the list is outlined while one is held there.
+fn zone_input(ui: &Ui, zone: &Response, ev: &mut TileEvents) {
- let held = zone.dnd_hover_payload::<SwatchDrag>().is_some() || zone.dnd_hover_payload::<Paint>().is_some();
- if held && !ev.over {
++ let Some(d) = zone.dnd_hover_payload::<PanelDrag>() else { return };
++ if !ev.over {
+ ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, Tokens::get(ui.ctx()).accent), StrokeKind::Inside);
+ }
- if let Some(d) = released::<SwatchDrag>(zone) {
- ev.drop = Some(Drop::Move { names: d.names.clone(), target: None, after: false });
- } else if let Some(p) = released::<Paint>(zone) {
- ev.drop = Some(Drop::New { paint: (*p).clone(), target: None });
++ if zone.dnd_release_payload::<PanelDrag>().is_some() {
++ ev.drop = Some(Drop::of(&d, None, false));
+ }
+}
+
+/// The colour group `name` is, or the one swatch `name` belongs to.
+fn group_of(d: &Document, name: &str) -> Option<String> {
+ if d.swatch_groups.iter().any(|g| g.name == name) {
+ return Some(name.to_string());
+ }
+ d.swatch_group_of(name).map(|g| d.swatch_groups[g].name.clone())
+}
+
+/// `swatch.move` params for dropping `names` before or `after` row `target`, into folder `target`
+/// (swatches), or at the end (`target` None); `None` when nothing would move. Only solid colours go
+/// into colour groups; None and Registration stay put.
+fn move_params(d: &Document, names: &[String], target: Option<&str>, after: bool) -> Option<Value> {
+ if target.is_some_and(|t| names.iter().any(|n| n == t)) {
+ return None;
+ }
+ let group_index = |n: &str| d.swatch_groups.iter().position(|g| g.name == n);
+ if names.iter().all(|n| group_index(n).is_some()) {
+ let to = match target {
+ None => d.swatch_groups.len(),
+ // Over a group's folder or one of its swatches: next to that group; else before the first.
+ Some(t) => group_index(t).or_else(|| d.swatch_group_of(t)).map_or(0, |i| i + usize::from(after)),
+ };
+ return Some(json!({"names": names, "to": to}));
+ }
+ let (group, to) = match target {
+ Some(t) if group_index(t).is_some() => (Some(t), None),
+ Some(REGISTRATION) => (None, Some(d.swatches.iter().position(|w| !w.paint.is_none()).unwrap_or(0))),
+ Some(t) => {
+ let (group, list) = match d.swatch_group_of(t) {
+ Some(g) => (Some(d.swatch_groups[g].name.as_str()), &d.swatch_groups[g].swatches),
+ None => (None, &d.swatches),
+ };
+ (group, list.iter().position(|w| w.name == t).map(|i| i + usize::from(after)))
+ }
+ None => (None, None),
+ };
+ let movable: Vec<&String> =
+ names.iter().filter(|n| d.swatch(n).is_some_and(|w| !w.paint.is_none() && (group.is_none() || w.paint.color().is_some()))).collect();
+ (!movable.is_empty()).then(|| json!({"names": movable, "to": to, "group": group}))
+}
+
+/// Run a drop on the panel: move the swatches or make a swatch of the proxy's paint (a colour
+/// dropped on a folder or a grouped swatch joins that group).
+fn apply_drop(app: &mut VectorcraftApp, drop: Drop) {
+ let Some(d) = app.session.active().map(|st| &st.doc) else { return };
+ let (cmd, params) = match drop {
+ Drop::Move { names, target, after } => match move_params(d, &names, target.as_deref(), after) {
+ Some(p) => ("swatch.move", p),
+ None => return,
+ },
+ Drop::New { paint, target } => {
+ let mut p = super::paint_params(&paint);
+ if paint.color().is_some()
+ && let Some(g) = target.and_then(|t| group_of(d, &t))
+ {
+ p["group"] = json!(g);
+ }
+ ("swatch.new", p)
+ }
+ };
+ if let Err(e) = app.run(cmd, params) {
+ app.status(e);
+ }
+}
+
- /// Paint command params for swatches or a Fill/Stroke proxy released on `resp`: the grabbed swatch
- /// (`None` for a colour group), or the proxy's paint (a gradient fits the new object afresh).
- pub(crate) fn released_paint(app: &VectorcraftApp, resp: &Response) -> Option<Value> {
- if let Some(d) = released::<SwatchDrag>(resp) {
- return swatch_params(&app.session.active()?.doc, &d.grabbed);
- }
- let mut paint = (*released::<Paint>(resp)?).clone();
- if let Paint::Gradient(g) = &mut paint {
- g.geom = None;
- }
- Some(super::paint_params(&paint))
- }
-
- /// While swatches or a Fill/Stroke proxy are dragged, a chip of the grabbed paint follows the
- /// pointer.
++/// While a paint is dragged (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail), a chip
++/// of it follows the pointer.
+pub(crate) fn drag_preview(app: &VectorcraftApp, ctx: &egui::Context) {
- let (paint, registration) = if let Some(d) = egui::DragAndDrop::payload::<SwatchDrag>(ctx) {
- match app.session.active().and_then(|st| st.doc.swatch(&d.grabbed)) {
- Some(w) => (w.paint.clone(), false),
- None if d.grabbed == REGISTRATION => (Paint::None, true),
- None => return,
- }
- } else if let Some(p) = egui::DragAndDrop::payload::<Paint>(ctx) {
- ((*p).clone(), false)
- } else {
++ let Some(d) = egui::DragAndDrop::payload::<PanelDrag>(ctx) else { return };
++ let PanelDrag::Paint { paint, params, rows } = &*d;
++ // Colour groups paint nothing.
++ if params.is_null() {
+ return;
- };
++ }
++ let registration = rows.as_ref().is_some_and(|r| r.grabbed == REGISTRATION);
+ let Some(at) = ctx.pointer_hover_pos() else { return };
+ let area = egui::Area::new(egui::Id::new("swatch-drag-preview")).order(egui::Order::Tooltip).fixed_pos(at + vec2(12.0, 12.0));
+ area.interactable(false).show(ctx, |ui| {
+ let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover());
+ if registration {
+ draw_registration(ui, r);
+ } else {
- swatch_tile(ui, r, &paint, false, false);
- pattern_thumb(app, ui, r.shrink(1.0), &paint);
++ swatch_tile(ui, r, paint, false, false);
++ pattern_thumb(app, ui, r.shrink(1.0), paint);
+ }
+ });
+}
+
+/// The id of the find field's text (shown with the panel menu's Show Find Field).
+fn find_id() -> egui::Id {
+ egui::Id::new("swatch-find")
+}
+
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
if app.session.active().is_none() {
@@@ -1088,122 -767,6 +1075,122 @@@ mod tests
assert_eq!(fill, Paint::Solid { color: Color::from_hex("#123456").unwrap(), swatch: Some("R=18 G=52 B=86".into()) });
}
+ /// The centre of the tile or row of `name` as laid out by the last frame.
+ fn tile_center(ctx: &egui::Context, name: &str) -> Pos2 {
+ ctx.read_response(egui::Id::new(("swatch-tile", name))).unwrap_or_else(|| panic!("no tile for {name}")).rect.center()
+ }
+
+ /// Press at `from`, drag to `to` and release there, a frame per step from `time`.
+ fn drag(app: &mut VectorcraftApp, ctx: &egui::Context, from: Pos2, to: Pos2, time: f64) {
+ let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
+ frame(app, ctx, vec![Event::PointerMoved(from), button(from, true)], time, show);
+ frame(app, ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], time + 0.1, show);
+ frame(app, ctx, vec![Event::PointerMoved(to)], time + 0.2, show);
+ frame(app, ctx, vec![Event::PointerMoved(to), button(to, false)], time + 0.3, show);
+ }
+
+ fn names_of(app: &VectorcraftApp, group: Option<&str>) -> Vec<String> {
+ let d = &app.session.active().unwrap().doc;
+ let list = match group {
+ Some(g) => &d.swatch_groups.iter().find(|x| x.name == g).unwrap().swatches,
+ None => &d.swatches,
+ };
+ list.iter().map(|w| w.name.clone()).collect()
+ }
+
+ #[test]
+ fn find_field_filters_and_shift_extends_over_what_is_shown() {
+ let mut app = app();
+ let ctx = context();
+ set_pstate(&ctx, "swatch-show-find", true);
+ ctx.data_mut(|d| d.insert_temp(find_id(), "BRIGHT".to_string()));
+ frame(&mut app, &ctx, vec![], 0.0, show);
+ assert!(ctx.read_response(egui::Id::new(("swatch-tile", "Red"))).is_none(), "Red doesn't match");
+ click_tile(&mut app, &ctx, "Bright Red", Modifiers::NONE, 1.0);
+ click_tile(&mut app, &ctx, "Bright Blue", Modifiers::SHIFT, 2.0);
+ assert_eq!(selected(&ctx), ["Bright Red", "Bright Yellow", "Bright Green", "Bright Blue"]);
+ // A group whose name matches shows all its swatches.
+ ctx.data_mut(|d| d.insert_temp(find_id(), "grays".to_string()));
+ frame(&mut app, &ctx, vec![], 3.0, show);
+ frame(&mut app, &ctx, vec![], 3.5, show);
+ assert!(ctx.read_response(egui::Id::new(("swatch-tile", "K=50"))).is_some());
+ assert!(ctx.read_response(egui::Id::new(("swatch-tile", "Bright Red"))).is_none());
+ }
+
+ #[test]
+ fn list_view_rows_take_double_clicks_and_folder_clicks_select_the_group() {
+ let mut app = app();
+ let ctx = context();
+ set_pstate(&ctx, "swatch-view", View::SmallList);
+ double_click_tile(&mut app, &ctx, "Red");
+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "double-click in a list opens Swatch Options");
+ let d = &app.session.active().unwrap().doc;
+ let sel = vec!["Brights".to_string()];
+ assert!(highlighted(d, &sel).contains(&"Bright Violet"), "a selected folder highlights its swatches");
+ assert_eq!(describe(&Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), true, false), "Global Process Color, CMYK");
+ assert_eq!(describe(&Paint::solid(Color::gray(0.5)), true, true), "Spot Color, Grayscale");
+ }
+
+ #[test]
+ fn dragging_tiles_reorders_and_moves_into_groups_as_one_undo_step_each() {
+ let mut app = app();
+ let ctx = context();
+ frame(&mut app, &ctx, vec![], 0.0, show);
+ let undo = app.session.doc().unwrap().history.undo.len();
+ // Onto the left half of Red: before it.
+ let (from, red) = (tile_center(&ctx, "Amber"), tile_center(&ctx, "Red"));
+ drag(&mut app, &ctx, from, red - vec2(4.0, 0.0), 1.0);
+ let n = names_of(&app, None);
+ assert_eq!(n[n.iter().position(|x| x == "Red").unwrap() - 1], "Amber");
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
+ // Onto a folder: into that group, at its end. (Two frames, so tile rects are current.)
+ frame(&mut app, &ctx, vec![], 2.0, show);
+ frame(&mut app, &ctx, vec![], 2.5, show);
+ drag(&mut app, &ctx, tile_center(&ctx, "Amber"), tile_center(&ctx, "Grays"), 3.0);
+ assert_eq!(names_of(&app, Some("Grays")).last().map(String::as_str), Some("Amber"));
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2);
+ // A selection drags together, in panel order; a gradient can't join a group.
+ set_pstate(&ctx, "swatch-selected", vec!["Lime".to_string(), "Sunset".to_string(), "Orange".to_string()]);
+ frame(&mut app, &ctx, vec![], 4.0, show);
+ frame(&mut app, &ctx, vec![], 4.5, show);
+ drag(&mut app, &ctx, tile_center(&ctx, "Lime"), tile_center(&ctx, "Bright Red") - vec2(4.0, 0.0), 5.0);
+ assert_eq!(names_of(&app, Some("Brights"))[..3], ["Orange", "Lime", "Bright Red"]);
+ assert!(names_of(&app, None).contains(&"Sunset".to_string()));
+ // Dropped back on itself: nothing moves.
+ let (before, undo) = (names_of(&app, None), app.session.doc().unwrap().history.undo.len());
+ frame(&mut app, &ctx, vec![], 6.0, show);
+ frame(&mut app, &ctx, vec![], 6.5, show);
+ let white = tile_center(&ctx, "White");
+ drag(&mut app, &ctx, white, white + vec2(2.0, 0.0), 7.0);
+ assert_eq!((names_of(&app, None), app.session.doc().unwrap().history.undo.len()), (before, undo));
+ }
+
+ #[test]
+ fn a_proxy_dropped_on_the_panel_becomes_a_swatch() {
+ let mut app = app();
+ let ctx = context();
+ frame(&mut app, &ctx, vec![], 0.0, show);
+ let at = tile_center(&ctx, "Bright Red");
- egui::DragAndDrop::set_payload(&ctx, Paint::solid(Color::from_hex("#123456").unwrap()));
++ egui::DragAndDrop::set_payload(&ctx, PanelDrag::paint(Paint::solid(Color::from_hex("#123456").unwrap())));
+ let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE };
+ frame(&mut app, &ctx, vec![Event::PointerMoved(at), release], 1.0, show);
+ assert_eq!(
+ names_of(&app, Some("Brights")).last().map(String::as_str),
+ Some("R=18 G=52 B=86"),
+ "dropped on a group's colour: into that group"
+ );
- assert!(egui::DragAndDrop::payload::<Paint>(&ctx).is_none());
++ assert!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).is_none());
+ }
+
+ #[test]
+ fn menu_targets_follow_the_panel_selection() {
+ let app = app();
+ let sel: Vec<String> = ["Red", "Sunset", "Grays", "Orange", "Brights"].map(String::from).to_vec();
+ assert_eq!(mergeable(&app, &sel), ["Red", "Orange"], "Merge Swatches takes the selected colours, first kept");
+ assert_eq!(selected_group(&app, &sel).as_deref(), Some("Grays"));
+ assert_eq!(selected_group(&app, &sel[..2]), None);
+ }
+
#[test]
fn kind_filter() {
let solid = Paint::solid(Color::BLACK);
diff --cc crates/ui-egui/src/widgets.rs
index a6d844965,5eef13d53..bffab921e
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@@ -255,14 -262,8 +255,14 @@@ pub fn fill_stroke_proxy(ui: &mut Ui, f
let s = size * 0.62;
let fill_r = Rect::from_min_size(rect.min + vec2(0.0, 0.0), Vec2::splat(s));
let stroke_r = Rect::from_min_size(rect.max - Vec2::splat(s), Vec2::splat(s));
- let stroke_resp = ui.interact(stroke_r, ui.id().with("stroke-proxy"), Sense::click());
- let fill_resp = ui.interact(fill_r, ui.id().with("fill-proxy"), Sense::click());
+ let stroke_resp = ui.interact(stroke_r, ui.id().with("stroke-proxy"), Sense::click_and_drag());
+ let fill_resp = ui.interact(fill_r, ui.id().with("fill-proxy"), Sense::click_and_drag());
+ // A proxy drags its paint (onto the Swatches panel or art), unless it shows "?".
+ for (resp, paint, mixed) in [(&fill_resp, fill, mixed.0), (&stroke_resp, stroke, mixed.1)] {
- if resp.drag_started() && !mixed {
- egui::DragAndDrop::set_payload(ui.ctx(), paint.clone());
++ if !mixed {
++ drag_source(ui, resp, || PanelDrag::paint(paint.clone()));
+ }
+ }
let question = |ui: &Ui, r: Rect, color: Color32| {
ui.painter().text(r.center(), egui::Align2::CENTER_CENTER, "?", egui::FontId::proportional(r.height() * 0.8), color);
};
@@@ -944,3 -909,31 +944,52 @@@ pub fn opt_field(ui: &mut Ui, id: impl
None
}
}
+
-/// A paint dragged out of a panel (a swatch, the Gradient panel's thumbnail). Dropped on art it
-/// paints the active proxy through `paint.setFill`/`paint.setStroke` with `params` (`{swatch}`,
-/// `{color}`, `{gradient}`…); dropped on the Gradient panel's ramp its colour adds or recolours a
-/// stop.
++/// What panels drag onto art and onto each other. One payload type, so the canvas has one drop
++/// handler for all of them (`canvas::panel_drop`); a chip of a dragged paint follows the pointer.
+ #[derive(Clone, Debug, PartialEq)]
-pub struct PaintDrag {
- pub paint: Paint,
- pub params: serde_json::Value,
++pub enum PanelDrag {
++ /// A paint: Swatches panel tiles, a Fill/Stroke proxy or the Gradient panel's thumbnail. Art it
++ /// is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; null for a colour group,
++ /// which paints nothing) through the active proxy's `paint.setFill`/`paint.setStroke`; the
++ /// Gradient panel's ramp takes its colour as a stop; the Swatches panel moves `rows`, or makes
++ /// a swatch of a paint dragged from elsewhere.
++ Paint { paint: Paint, params: serde_json::Value, rows: Option<SwatchRows> },
++}
++
++/// The Swatches panel rows a drag from that panel moves: the swatch, None, Registration or colour
++/// group under the pointer when the drag started (`grabbed`) and `names`, the panel selection when
++/// the grabbed one is part of it (only colour groups, or only swatches, like the grabbed one), in
++/// panel order.
++#[derive(Clone, Debug, PartialEq)]
++pub struct SwatchRows {
++ pub grabbed: String,
++ pub names: Vec<String>,
++ /// The names are colour groups.
++ pub groups: bool,
++}
++
++impl PanelDrag {
++ /// `paint` dragged from a Fill/Stroke proxy or the Gradient panel's thumbnail. A gradient
++ /// carries no placement: it fits the art it lands on.
++ pub fn paint(mut paint: Paint) -> Self {
++ if let Paint::Gradient(g) = &mut paint {
++ g.geom = None;
++ }
++ Self::Paint { params: crate::panels::paint_params(&paint), paint, rows: None }
++ }
++ /// The dragged colour (a solid paint's), which the Gradient panel's ramp takes.
++ pub fn color(&self) -> Option<vectorcraft_color::Color> {
++ match self {
++ Self::Paint { paint, .. } => paint.color(),
++ }
++ }
+ }
+
-/// Make `resp` (which senses drags) a source of the [`PaintDrag`] `drag` builds when the drag
-/// starts, and draw that paint under the pointer while it travels.
-pub fn paint_drag_source(ui: &Ui, resp: &Response, drag: impl FnOnce() -> PaintDrag) {
++/// Make `resp` (which senses drags) a source of the [`PanelDrag`] `drag` builds when a drag starts
++/// on it.
++pub fn drag_source(ui: &Ui, resp: &Response, drag: impl FnOnce() -> PanelDrag) {
+ if resp.drag_started() {
+ egui::DragAndDrop::set_payload(ui.ctx(), drag());
+ }
- if resp.dragged()
- && let Some(at) = ui.ctx().pointer_interact_pos()
- && let Some(d) = egui::DragAndDrop::payload::<PaintDrag>(ui.ctx())
- {
- let t = Tokens::get(ui.ctx());
- let p = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("paint-drag")));
- let r = Rect::from_min_size(at + vec2(10.0, 10.0), Vec2::splat(18.0));
- draw_paint(&p, r, &d.paint);
- p.rect_stroke(r, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside);
- }
+ }
diff --cc docs/control-protocol.md
index d8a381970,32604f9a9..74b29c1b5
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@@ -37,6 -37,14 +37,19 @@@ fill or stroke (fields as in `swatchOpt
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`.
+Graphic styles: `ui.graphicStyleOptions {name}` opens the `graphicStyleOptions` dialog (field `name`) for a style and
+`ui.dialog.confirm` renames it with `graphicStyle.rename` (a name another style has returns an error and keeps the
+dialog open); without `name` it names a new style made from the selection (`graphicStyle.new`).
++
+ Gradient panel: double-clicking a stop on the panel's slider opens the same `gradientStop` popover, with a `screen`
+ field (`[x, y]`, screen points) in place of `x`/`y`. The panel's stop eyedropper selects the Eyedropper tool with the
+ tool option `stop` (the tool to return to; `tool.setOption {key: "stop", value: "gradient"}`): its next click on art
+ samples the colour there into the selected stop (`paint.sampleColor {color, stop}`) and switches back. Dragging a
-swatch or the panel's gradient thumbnail onto art runs `paint.setFill` / `paint.setStroke` (the active proxy) with
-the swatch's params and the object's `ids`.
++swatch, a Fill/Stroke proxy or the panel's gradient thumbnail onto art runs `paint.setFill` / `paint.setStroke` (the
++active proxy) with the paint's params and the object's `ids`; a colour dropped on the panel's ramp adds or recolours
++a stop.
+
+ Tool options: double-clicking a tool button runs `tool.options {tool}`. For `gradient` it opens the Gradient panel;
+ for `eyedropper` it opens Eyedropper Options, a `command` dialog (fields `appearance`, `transparency`) whose
+ `ui.dialog.confirm` runs `eyedropper.setOptions` (what `appearance.copyFrom` copies). Gradient tool handles snap to
+ anchors, edges and smart guides; Shift constrains them to 45° steps from the `constrainAngle` preference.