VectorCraft: An open-source, vector art tool written by scratch in pure Rust
Merge wp/D2
bflatastic43d7ac420d0a
diff --cc crates/effects/src/reshape.rsindex 000000000,a178a91ff..84d902da7mode 000000,100644..100644--- a/crates/effects/src/reshape.rs+++ b/crates/effects/src/reshape.rs@@@ -1,0 -1,182 +1,182 @@@+ //! Object-level effects on objects that aren't paths: type, placed images, symbol instances and+ //! live objects (blends, envelopes, meshes, repeats).+ //!+ //! Geometry effects reach them through outlines: [`outline_art`] turns the object into plain paths+ //! (glyph outlines, the evaluated live object, the symbol's art) and [`reshape`] runs each effect+ //! over all of them as one piece, with the whole art's bounds as the effect's reference box, so a+ //! warp bends a line of type as a whole. An image is clipped by its reshaped frame. Raster effects+ //! (shadows, glows, blur, feather) stay on the result for the renderer and exporters.++ use std::sync::Arc;++ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeKind, StrokeLayer};+ use vectorcraft_geom::{FillRule, PathData, Rect, shapes};++ use crate::{GeomContext, apply_one, is_geometry, merged_params};++ /// Can object-level effects apply to `n` only through [`outline_art`] / an offscreen layer (it is+ /// neither a path nor a container)?+ pub fn needs_outline(n: &Node) -> bool {+ matches!(+ n.kind,+ NodeKind::Text(_)+ | NodeKind::Image(_)+ | NodeKind::SymbolInstance { .. }+ | NodeKind::Blend { .. }+ | NodeKind::Envelope { .. }+ | NodeKind::Mesh(_)+ | NodeKind::Repeat(_)+ )+ }++ /// Type as glyph outlines in document space: one path per run with the run's fill and stroke,+ /// then (when the object has its own fills/strokes) the whole outline with the object's stack,+ /// painted over the characters as the renderer does.+ pub fn outline_text(n: &Node) -> Option<Node> {+ let NodeKind::Text(t) = &n.kind else { return None };+ let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);+ let mut runs = vec![kurbo::BezPath::new(); t.runs.len()];+ let mut all = kurbo::BezPath::new();+ for g in &layout.glyphs {+ if let Some(r) = runs.get_mut(g.run) {+ r.extend(g.outline.iter());+ }+ all.extend(g.outline.iter());+ }+ let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf);+ let mut children: Vec<Arc<Node>> = runs+ .iter()+ .zip(&t.runs)+ .filter(|(bp, _)| !bp.elements().is_empty())+ .map(|(bp, run)| {+ let mut ap = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(run.style.fill.clone()))], effects: vec![] };+ if !run.style.stroke.is_none() && run.style.stroke_width > 0.0 {+ ap.items.push(AppearanceItem::Stroke(StrokeLayer::new(run.style.stroke.clone(), run.style.stroke_width)));+ }+ Arc::new(Node::path(n.id, path(bp), ap))+ })+ .collect();+ if !n.appearance.items.is_empty() && !all.elements().is_empty() {+ let ap = Appearance { items: n.appearance.items.clone(), effects: vec![] };+ children.push(Arc::new(Node::path(n.id, path(&all), ap)));+ }+ Some(Node::group(n.id, children))+ }++ /// `n` as plain art that geometry effects can reshape, without its transparency and object+ /// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined),+ /// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by+ /// the instance's transform. `None` for other kinds (images, paths, containers).+ pub fn outline_art(n: &Node, symbol_art: Option<&Node>) -> Option<Node> {+ let hook: &dyn Fn(&Node) -> Option<Node> = &outline_text;+ let mut art = match &n.kind {+ NodeKind::Text(_) => outline_text(n)?,+ NodeKind::SymbolInstance { xf, .. } => {+ let mut a = symbol_art?.clone();+ a.transform(*xf, false);+ Node::group(n.id, vec![Arc::new(a)])+ }+ _ if vectorcraft_doc::live::is_live(n) => vectorcraft_doc::live::expand_deep(n, Some(hook)),+ _ => return None,+ };+ outline_nested_text(&mut art);+ art.opacity = 1.0;+ art.blend = Default::default();+ art.isolate = false;- art.knockout = false;++ // One element: its pieces never knock each other out.++ art.knockout = vectorcraft_doc::Knockout::Off;+ art.mask = None;+ art.appearance.effects.clear();+ Some(art)+ }++ /// Replace type anywhere inside `n` by its outlines.+ fn outline_nested_text(n: &mut Node) {+ let Some(ch) = n.children_mut() else { return };+ for c in ch.iter_mut() {+ if let Some(o) = outline_text(c) {+ *c = Arc::new(o);+ } else if c.children().is_some() {+ outline_nested_text(Arc::make_mut(c));+ }+ }+ }++ /// `n` (see [`needs_outline`]) with its object-level geometry effects applied: its [`outline_art`]+ /// reshaped as one piece, or for an image the image clipped by its reshaped frame. The result is+ /// a group with `n`'s id, name, transparency, opacity mask and remaining (raster) effects; `None`+ /// when `n` has no visible geometry effect or no art (a symbol instance without `symbol_art`).+ pub fn reshape(n: &Node, symbol_art: Option<&Node>) -> Option<Node> {+ let fx: Vec<_> = n.appearance.effects.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();+ if fx.is_empty() || !needs_outline(n) {+ return None;+ }+ let mut art = match &n.kind {+ NodeKind::Image(im) => {+ let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);+ let mut clip = Node::path(n.id, frame, Appearance::default());+ if let NodeKind::Path { clipping, .. } = &mut clip.kind {+ *clipping = true;+ }+ let image = Node { appearance: Appearance::default(), ..Node::new(n.id, n.kind.clone()) };+ Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true })+ }+ _ => outline_art(n, symbol_art)?,+ };+ for e in fx {+ // Every leaf takes the effect with the whole art's bounds as its reference box.+ let Some(bounds) = art.geometric_bounds() else { break };+ let params = merged_params(&e.id, &e.params);+ for_each_leaf(&mut art, &mut |leaf| {+ let Some((path, rule)) = leaf_geometry(leaf) else { return };- let w = leaf.appearance.stroke_width();- let ctx = GeomContext { stroke_width: if w > 0.0 { w } else { 1.0 } };- let out = apply_one(&e.id, ¶ms, &path, bounds, &ctx);++ let out = apply_one(&e.id, ¶ms, &path, bounds, &GeomContext::of(leaf));+ set_geometry(leaf, out, rule);+ });+ }+ // The art is a group with `n`'s id (a clip group for an image).+ let mut out = art;+ out.name = n.name.clone();+ out.opacity = n.opacity;+ out.blend = n.blend;+ out.isolate = n.isolate;- out.knockout = n.knockout;++ // One element: its pieces never knock each other out.++ out.knockout = vectorcraft_doc::Knockout::Off;+ out.mask = n.mask.clone();+ out.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();+ Some(out)+ }++ /// Run `f` on every path and compound path under `n` (guides skipped).+ fn for_each_leaf(n: &mut Node, f: &mut dyn FnMut(&mut Node)) {+ match &mut n.kind {+ NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => f(n),+ NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {+ for c in children.iter_mut() {+ for_each_leaf(Arc::make_mut(c), f);+ }+ }+ _ => {}+ }+ }++ fn leaf_geometry(n: &Node) -> Option<(PathData, FillRule)> {+ match &n.kind {+ NodeKind::Path { path, rule, .. } => Some((path.clone(), *rule)),+ NodeKind::Compound { children, rule } => {+ Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule))+ }+ _ => None,+ }+ }++ /// Replace the geometry of path or compound `n` (a compound when `path` has several subpaths).+ fn set_geometry(n: &mut Node, path: PathData, rule: FillRule) {+ let clipping = matches!(n.kind, NodeKind::Path { clipping: true, .. });+ n.kind = if path.subpaths.len() > 1 {+ let id = n.id;+ let children = path.subpaths.into_iter().map(|sp| Arc::new(Node::path(id, PathData::single(sp), Appearance::default()))).collect();+ NodeKind::Compound { children, rule }+ } else {+ NodeKind::Path { path, rule, live: None, clipping, guide: false }+ };+ }diff --cc crates/pdf/src/export.rsindex e1a72e89d,35c9e4443..f8046d51d--- a/crates/pdf/src/export.rs+++ b/crates/pdf/src/export.rs@@@ -425,13 -367,8 +432,11 @@@ impl Exporter<'_>None if !n.is_container() => return,_ => {}}- if n.appearance.effects.iter().any(|e| e.visible && vectorcraft_effects::is_raster(&e.id)) {- self.warn("raster effects (shadows, glows, blur, feather) are not exported to PDF yet");- }+ self.warn_raster(&n.appearance.effects);let container = n.is_container() && !matches!(n.kind, NodeKind::Compound { .. });+ // Whether this container's children knock each other out (a knockout group is isolated).+ let knockout = n.knocks_out(self.knockout);+ let enclosing = std::mem::replace(&mut self.knockout, knockout);let mut pushes = 0;if n.blend != BlendMode::Normal {s.push_blend_mode(blend(n.blend));@@@ -546,7 -489,8 +549,8 @@@if !st.visible || st.paint.is_none() || st.width <= 0.0 {continue;}+ self.warn_raster(&st.effects);- self.stroke(s, bp, &path, r, st, bounds);+ self.stroke(s, bp, &path, r, st, page);}}}diff --cc crates/pdf/src/lib.rsindex e0a18467d,4a45d3501..fcf997bfb--- a/crates/pdf/src/lib.rs+++ b/crates/pdf/src/lib.rs@@@ -108,6 -106,6 +108,8 @@@ pub enum PdfError#[cfg(test)]mod tests;#[cfg(test)]+ mod tests_fx;+ #[cfg(test)]mod tests_stroke;+#[cfg(test)]+mod tests_strokeout;diff --cc crates/render/src/fx.rsindex 273a445e6,d0364732e..7ecd9c73f--- a/crates/render/src/fx.rs+++ b/crates/render/src/fx.rs@@@ -298,25 -337,110 +332,112 @@@ impl Renderer// Document-space reach of the painted geometry (strokes, arrowheads…).let outset = n.appearance.outset();let reach = g.bounding_box().inflate(outset, outset);- // Below the object: shadows and outer glows.+ let content = Content { node: n, cache: Some(0), reach, outline: Some((&g, rule)) };+ self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.paint_items(c, fr, n, &g, rule, &gctx));+ ctx.set_transform(Affine::IDENTITY);+ }++ /// Draw type, an image, a symbol instance or a live object with object-level effects+ /// ([`has_object_fx`]) inside its transparency group: its art (reshaped by the geometry+ /// effects, see [`effects::reshape`]) with the raster effects painted around it as for paths,+ /// the art standing for the object's silhouette.+ pub(crate) fn draw_object_fx(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) {- let layered = !f.opts.outline && (a.opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate);++ let opacity = self.opacity_of(a);++ let layered = !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_doc::color::BlendMode::Normal || a.isolate);+ if layered {+ ctx.set_transform(Affine::IDENTITY);- ctx.push_layer(None, Some(blend_mode(a.blend)), Some(a.opacity), None, None);++ ctx.push_layer(None, Some(blend_mode(a.blend)), Some(opacity), None, None);+ }+ let art = self.fx_art(f.doc, a, cache);+ let rfx = effects::raster_effects(&a.appearance.effects);+ match cull_bounds(&art) {+ Some(reach) if !f.opts.outline && !rfx.is_empty() => {+ // Feather and Inner Glow clip to the art's outline.+ let clipped = rfx.iter().any(|x| matches!(x, RasterFx::Feather { .. } | RasterFx::InnerGlow { .. }));+ let region = if clipped { self.clip_of(&art) } else { None };+ // A symbol's art can change while the instance doesn't: no cached shadows.+ let cache = (cache && !matches!(a.kind, NodeKind::SymbolInstance { .. })).then_some(0);+ let content = Content { node: a, cache, reach, outline: region.as_deref().map(|r| (&r.0, r.1)) };+ self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.draw_node(c, fr, &art, true));+ ctx.set_transform(Affine::IDENTITY);+ }+ _ => self.draw_node(ctx, f, &art, true),+ }+ if layered {+ ctx.pop_layer();+ }+ self.stats.drawn += 1;+ }++ /// The art [`Self::draw_object_fx`] draws for `a` (cached by `Arc` identity when `cache`):+ /// reshaped by its geometry effects, else type and images as themselves and the others as+ /// their evaluated art; without the object's transparency and effects.+ fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>, cache: bool) -> Arc<Node> {+ let key = Arc::as_ptr(a) as usize;+ if cache+ && let Some((node, art)) = self.fx_arts.get(&key)+ && Arc::ptr_eq(node, a)+ {+ return art.clone();+ }+ let symbol = match &a.kind {+ NodeKind::SymbolInstance { symbol, .. } => {+ doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a))+ }+ _ => None,+ };+ let art = match effects::reshape(a, symbol.as_ref()) {+ Some(r) => r,+ None if matches!(a.kind, NodeKind::Text(_) | NodeKind::Image(_)) => (**a).clone(),+ None => effects::outline_art(a, symbol.as_ref()).unwrap_or_else(|| Node::group(a.id, vec![])),+ };+ let art = Arc::new(Node {+ opacity: 1.0,+ blend: Default::default(),+ isolate: false,- knockout: false,++ // One element: its pieces never knock each other out.++ knockout: vectorcraft_doc::Knockout::Off,+ mask: None,+ appearance: vectorcraft_doc::Appearance { effects: vec![], ..art.appearance },+ ..art+ });+ if cache {+ if self.fx_arts.len() > 1024 {+ self.fx_arts.clear();+ }+ self.fx_arts.insert(key, (a.clone(), art.clone()));+ }+ art+ }++ /// Paint `content` with raster effects `rfx` (see the module docs): shadows and outer glows+ /// below it, the content blurred or feathered, inner glows above it (clipped to its outline).+ /// `paint` draws the content in the frame it is given.+ fn raster_fx(+ &mut self,+ ctx: &mut RenderContext,+ f: &Frame,+ content: &Content,+ rfx: &[RasterFx],+ paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),+ ) {+ let reach = content.reach;+ // Below the content: shadows and outer glows.for (i, fx) in rfx.iter().enumerate().filter(|(_, x)| x.is_below()) {- if self.draw_shadow_cached(ctx, f, n, i, fx, &g, rule, &gctx, reach) {+ if let Some(slot) = content.cache+ && self.draw_shadow_cached(ctx, f, content.node, slot + i, fx, reach, paint)+ {continue;}- // The offset is applied to the geometry rather than in the filter: vello_cpu drops- // layer content that lies entirely outside the viewport before filtering.- let (mode, opacity, dx, dy, blur, filter) = match fx {- RasterFx::DropShadow { mode, opacity, dx, dy, blur, color } => {- (*mode, *opacity, *dx, *dy, *blur, shadow_filter(0.0, 0.0, *blur, pcolor(color)))- }- RasterFx::OuterGlow { mode, opacity, blur, color } => {- (*mode, *opacity, 0.0, 0.0, *blur, shadow_filter(0.0, 0.0, *blur, pcolor(color)))- }+ let (mode, opacity, dx, dy, blur, color) = match fx {+ RasterFx::DropShadow { mode, opacity, dx, dy, blur, color } => (*mode, *opacity, *dx, *dy, *blur, *color),+ RasterFx::OuterGlow { mode, opacity, blur, color } => (*mode, *opacity, 0.0, 0.0, *blur, *color),_ => continue,};- let mut gs = g.clone();- gs.apply_affine(Affine::translate((dx, dy)));- let reach = reach + vectorcraft_geom::Vec2::new(dx, dy);+ let filter = shadow_filter(0.0, 0.0, blur, pcolor(&color));+ // The offset moves the content rather than the filter: vello_cpu drops layer content+ // that lies entirely outside the viewport before filtering.+ let reach = reach + Vec2::new(dx, dy);self.with_filters(ctx, f, reach, blur, Some((mode, opacity)), |r, c, fr, comp| {c.set_transform(fr.view);c.push_layer(None, comp.map(|m| blend_mode(m.0)), comp.map(|m| m.1), None, Some(filter));@@@ -443,41 -570,66 +567,66 @@@ctx.set_transform(Affine::IDENTITY);}- /// Paint the fills and strokes of `n` on geometry `g`, applying per-item geometry effects.+ /// Paint the fills and strokes of `n` on geometry `g`, applying per-item geometry effects and+ /// painting per-item raster effects around that item alone.fn paint_items(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, g: &BezPath, rule: FillRule, gctx: &GeomContext) {let bounds = g.bounding_box();- for item in &n.appearance.items {+ for (j, item) in n.appearance.items.iter().enumerate() {+ if !item.visible() || item.paint().is_none() {+ continue;+ }- let ig = apply(item_effects(item), g, gctx);+ let ig = apply(item_effects(item), g, &gctx.item(item));let ib = if effects::has_geometry(item_effects(item)) && !ig.elements().is_empty() { ig.bounding_box() } else { bounds };- match item {- AppearanceItem::Fill(fl) => {- if !fl.visible || fl.paint.is_none() {- continue;- }- let layered = fl.opacity < 1.0 || fl.blend != vectorcraft_doc::color::BlendMode::Normal;- if layered {- ctx.set_transform(Affine::IDENTITY);- ctx.push_layer(None, Some(blend_mode(fl.blend)), Some(fl.opacity), None, None);- }- ctx.set_transform(f.view);- if paint::set_paint(ctx, &fl.paint, ib, f.doc) {- ctx.set_fill_rule(fill_rule(rule));- ctx.fill_path(&ig);- }- if layered {- ctx.pop_layer();- }- }+ let rfx = effects::raster_effects(item_effects(item));+ if rfx.is_empty() {+ self.paint_item(ctx, f, n, item, &ig, rule, ib);+ continue;+ }+ // The item's silhouette: its fill area, or the outline of its stroke.+ let outline = match item {+ AppearanceItem::Fill(_) => ig.clone(),AppearanceItem::Stroke(st) => {- if !st.visible || st.paint.is_none() || st.width <= 0.0 {- continue;- }- // Brushed strokes keep their brush art under effects (e.g. a glowing scatter brush).- if st.brush.is_some() && self.draw_brush(ctx, f, n, &ig, st) {- continue;- }- self.draw_stroke(ctx, f, &ig, rule, st, ib);+ let w = effects::stroke::aligned_width(st, effects::stroke::is_closed(&ig));+ effects::stroke::line_outline(&effects::stroke::stroke_pieces(&ig, st).line, st, w, f.px * 0.25)+ }+ };+ let outset = n.appearance.outset();+ let orule = if item.is_fill() { rule } else { FillRule::NonZero };+ // Each item's shadows get their own cache slots.+ let content = Content { node: n, cache: Some((j + 1) << 8), reach: ib.inflate(outset, outset), outline: Some((&outline, orule)) };+ self.raster_fx(ctx, f, &content, &rfx, &mut |r, c, fr| r.paint_item(c, fr, n, item, &ig, rule, ib));+ ctx.set_transform(Affine::IDENTITY);+ }+ }++ /// Paint one fill or stroke of `n` on its geometry `ig` (bounds `ib`).+ #[allow(clippy::too_many_arguments)]+ fn paint_item(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, item: &AppearanceItem, ig: &BezPath, rule: FillRule, ib: Rect) {+ match item {+ AppearanceItem::Fill(fl) => {+ let layered = fl.opacity < 1.0 || fl.blend != vectorcraft_doc::color::BlendMode::Normal;+ if layered {+ ctx.set_transform(Affine::IDENTITY);+ ctx.push_layer(None, Some(blend_mode(fl.blend)), Some(fl.opacity), None, None);+ }+ ctx.set_transform(f.view);+ if paint::set_paint(ctx, &fl.paint, ib, f.doc) {+ ctx.set_fill_rule(fill_rule(rule));+ ctx.fill_path(ig);+ }+ if layered {+ ctx.pop_layer();+ }+ }+ AppearanceItem::Stroke(st) => {+ if st.width <= 0.0 {+ return;+ }+ // Brushed strokes keep their brush art under effects (e.g. a glowing scatter brush).+ if st.brush.is_some() && self.draw_brush(ctx, f, n, ig, st) {+ return;}+ self.draw_stroke(ctx, f, ig, rule, st, ib);}}}diff --cc crates/render/src/lib.rsindex 24a95fe4d,17c6ebc96..bf056500e--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@@ -230,11 -230,8 +230,13 @@@ pub struct Rendererlive: live::LiveCache,/// Blurred, tinted drop shadow / outer glow rasters per object and effect (see `fx`).shadows: PtrMap<(usize, usize), fx::ShadowEntry>,+ /// Whether the group being drawn is a knockout group (what its neutral children inherit).+ knockout: bool,+ /// Address of the knockout-group element being drawn as its knockout shape: at full object+ /// opacity and without its opacity mask (see [`Self::draw_knockout`]); 0 = none.+ shape_of: usize,+ /// The art drawn for objects with effects that apply through it (see `fx::has_object_fx`).+ fx_arts: PtrMap<usize, (Arc<Node>, Arc<Node>)>,}#[derive(Clone, Copy, Debug, Default)]@@@ -282,8 -279,7 +284,9 @@@ impl Rendererbrushes: Default::default(),shadows: PtrMap::default(),live: live::LiveCache::default(),+ knockout: false,+ shape_of: 0,+ fx_arts: PtrMap::default(),}}@@@ -557,8 -530,11 +560,11 @@@self.stats.drawn += 1;return;}+ if fx::has_object_fx(a) {+ return self.draw_object_fx(ctx, f, a, true);+ }if let NodeKind::Text(t) = &a.kind- && a.opacity >= 1.0+ && self.opacity_of(a) >= 1.0&& a.blend == vectorcraft_color::BlendMode::Normal&& !fx::has_fx(a){@@@ -1083,4 -1022,4 +1092,6 @@@ mod tests#[cfg(test)]mod tests_clip;#[cfg(test)]+mod tests_knockout;++#[cfg(test)]+ mod tests_objectfx;diff --cc crates/svg/src/export.rsindex 5a47e031e,e5072b0b7..27daeeabe--- a/crates/svg/src/export.rs+++ b/crates/svg/src/export.rs@@@ -526,22 -442,15 +526,23 @@@ impl Writer<'_>AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.width > 0.0,}).collect();+ let mut bp = None;+ let plans: Vec<Option<StrokePlan>> = items+ .iter()+ .map(|i| match i {+ AppearanceItem::Stroke(s) => Some(self.stroke_plan(s, &mut bp, paths)),+ AppearanceItem::Fill(_) => None,+ })+ .collect();let fills = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count();let strokes = items.len() - fills;+ // A stroke's paint box is the bounds grown by half its weight, as on the canvas.+ let paint_bounds = |s: &StrokeLayer| bounds.map(|b| s.paint_bounds(b));let simple = fills <= 1&& strokes <= 1+ && !items.iter().any(|i| has_raster(i.effects()))- && items.iter().all(|i| match i {- AppearanceItem::Fill(f) => f.blend == BlendMode::Normal,- AppearanceItem::Stroke(s) => s.blend == BlendMode::Normal && s.align == StrokeAlign::Center,- });+ && items.iter().all(|i| i.blend() == BlendMode::Normal)+ && plans.iter().flatten().all(|p| matches!(p, StrokePlan::Written(Written { shape: WrittenShape::Stroke { .. }, side: None })));if simple {let mut p = Props::new();match items.iter().find_map(|i| if let AppearanceItem::Fill(f) = i { Some(f) } else { None }) {@@@ -567,10 -476,12 +568,12 @@@let a = self.attrs(&Self::node_props(n));self.line(&format!("<g{id}{a}>"));self.depth += 1;- for it in items {+ for (it, plan) in items.into_iter().zip(plans) {+ // The item's own raster effects filter that item alone.+ let filters = self.open_filters(n, it.effects());let mut p = Props::new();- match it {- AppearanceItem::Fill(f) => {+ match (it, plan) {+ (AppearanceItem::Fill(f), _) => {self.fill_props(f, rule, bounds, &mut p);if f.blend != BlendMode::Normal {p.push(("mix-blend-mode", blend_css(f.blend).into()));@@@ -586,55 -496,39 +589,56 @@@if s.blend != BlendMode::Normal {p.push(("mix-blend-mode", blend_css(s.blend).into()));}- let rule_attr = if rule == FillRule::EvenOdd { " clip-rule=\"evenodd\"" } else { "" };- let extra = match s.align {- StrokeAlign::Center => String::new(),- StrokeAlign::Inside => {- let cid = self.fresh_id("clip-path");- self.def(1, &format!("<clipPath id=\"{cid}\">"));- self.def(2, &format!("<path d=\"{d}\"{rule_attr}/>"));- self.def(1, "</clipPath>");- format!(" clip-path=\"url(#{cid})\"")+ let a = self.attrs(&p);+ self.line(&format!("<g{a}>"));+ self.depth += 1;+ for piece in &art {+ self.node(piece);+ }+ self.depth -= 1;+ self.line("</g>");+ }+ (AppearanceItem::Stroke(s), Some(StrokePlan::Written(w))) => {+ let side = self.side_attr(w.side, d, rule, w.reach(s, bounds.unwrap_or_default()));+ let blend = (s.blend != BlendMode::Normal).then(|| ("mix-blend-mode", blend_css(s.blend).to_string()));+ match &w.shape {+ WrittenShape::Stroke { width } => {+ p.push(("fill", "none".into()));+ self.stroke_props(s, *width, paint_bounds(s), &mut p);+ p.extend(blend);+ let a = self.attrs(&p);+ self.line(&format!("<path d=\"{d}\"{a}{side}/>"));}- StrokeAlign::Outside => {- let mid = self.fresh_id("mask");- let b = self- .xf- .transform_rect_bbox(bounds.unwrap_or_default())- .inflate(width * s.miter_limit.max(1.0) + 1.0, width * s.miter_limit.max(1.0) + 1.0);- let (x, y, w, h) = (self.num(b.x0), self.num(b.y0), self.num(b.width()), self.num(b.height()));- let fr = if rule == FillRule::EvenOdd { " fill-rule=\"evenodd\"" } else { "" };- self.def(- 1,- &format!("<mask id=\"{mid}\" maskUnits=\"userSpaceOnUse\" x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\">"),- );- self.def(2, &format!("<rect x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\" fill=\"#fff\"/>"));- self.def(2, &format!("<path d=\"{d}\" fill=\"#000\"{fr}/>"));- self.def(1, "</mask>");- format!(" mask=\"url(#{mid})\"")+ WrittenShape::Fill(outlines) => {+ let paint = self.paint(&s.paint, paint_bounds(s));+ let ds: Vec<String> = outlines.iter().map(|o| self.path_d(&PathData::from_bezpath(o), self.xf)).collect();+ let opacity = (s.opacity < 1.0).then(|| fmt_num(s.opacity as f64, 3));+ if let [one] = &ds[..] {+ p.push(("fill", paint));+ p.extend(opacity.map(|o| ("fill-opacity", o)));+ p.extend(blend);+ let a = self.attrs(&p);+ self.line(&format!("<path d=\"{one}\"{a}{side}/>"));+ } else if !ds.is_empty() {+ // The line and its arrowheads overlap: one group takes the opacity.+ p.extend(opacity.map(|o| ("opacity", o)));+ p.extend(blend);+ let a = self.attrs(&p);+ self.line(&format!("<g{a}{side}>"));+ self.depth += 1;+ let fill = self.attrs(&vec![("fill", paint)]);+ for one in &ds {+ self.line(&format!("<path d=\"{one}\"{fill}/>"));+ }+ self.depth -= 1;+ self.line("</g>");+ }}- };- let a = self.attrs(&p);- self.line(&format!("<path d=\"{d}\"{a}{extra}/>"));+ }}+ (AppearanceItem::Stroke(_), None) => {}}+ self.close_filters(filters);}self.depth -= 1;self.line("</g>");diff --cc crates/ui-egui/src/canvas.rsindex b879e0e82,5bb3865f9..7bb4c3d27--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -668,43 -685,6 +668,51 @@@ fn node_outline(n: &Node) -> BezPathbp}+/// 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)+}++/// 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.++/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the++/// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries++/// (`appearance.copyFrom`). A chip 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(d) = resp.dnd_release_payload::<widgets::PanelDrag>() else { return };+ let Some(hit) = hit_at(app, xf.to_doc(pos), xf.zoom) else { return };+ let Some(st) = app.session.active() else { return };+ 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)+ }++ widgets::PanelDrag::Appearance(source) => {++ let target = hit.top_object(st.isolation);++ if target == *source {++ return;++ }++ ("appearance.copyFrom", json!({"source": source.0, "ids": [target.0]}))++ }+ };+ if let Err(e) = app.run(cmd, params) {+ app.status(e);+ }+}+fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) {let Some(h) = app.hover_doc else { return };if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection") {@@@ -1118,41 -1099,32 +1126,75 @@@ mod testsassert_eq!(app.view().unwrap().center, after.center);assert_eq!(app.session.active().unwrap().doc.art_bounds(), None);}++ #[test]+ fn swatches_and_proxy_paints_dropped_on_art_fill_the_object_hit() {+ 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": 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 xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());+ 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![egui::Event::PointerMoved(at), up]);+ };+ let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint();+ 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.+ drop(&mut app, swatch.clone(), Point::new(300.0, 250.0));+ assert_eq!(fill(&app), Paint::solid(Color::WHITE));+ 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.+ 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()));+ }+++ #[test]+ fn dropping_the_appearance_thumbnail_on_art_copies_the_appearance() {++ use vectorcraft_doc::NodeId;+ let mut app = VectorcraftApp::new(Session::new(), Default::default());+ let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();+ run(&mut app, "file.new", json!({"width": 400, "height": 300}));+ let a = run(&mut app, "shape.rectangle", json!({"x": 20, "y": 20, "width": 100, "height": 100}))["id"].as_u64().unwrap();+ run(&mut app, "effect.apply", json!({"effect": "distort.twist"}));+ run(&mut app, "transparency.set", json!({"opacity": 40}));+ let b = run(&mut app, "shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100}))["id"].as_u64().unwrap();+ run(&mut app, "select.set", json!({ "ids": [a] }));+ let ctx = egui::Context::default();+ frame(&mut app, &ctx, vec![]);+ // The Appearance panel's thumbnail (its drag payload) released over the second rectangle.- egui::DragAndDrop::set_payload(&ctx, crate::panels::appearance::AppearanceDrag(NodeId(a)));+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());- let at = xf.to_screen(Point::new(250.0, 70.0));- frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);- let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };- frame(&mut app, &ctx, vec![up]);++ let drop = |app: &mut VectorcraftApp, at: Point| {++ let at = xf.to_screen(at);++ egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Appearance(NodeId(a)));++ frame(app, &ctx, vec![egui::Event::PointerMoved(at)]);++ let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };++ frame(app, &ctx, vec![up]);++ };++ drop(&mut app, Point::new(250.0, 70.0));+ let doc = &app.session.active().unwrap().doc;+ let (na, nb) = (doc.node(NodeId(a)).unwrap(), doc.node(NodeId(b)).unwrap());+ assert_eq!((&nb.appearance, nb.opacity), (&na.appearance, na.opacity));+ assert_eq!(nb.appearance.effects[0].id, "distort.twist");- // Dropped on empty canvas: nothing changes.++ // Dropped on empty canvas or on the source itself: nothing changes.+ let undo_len = app.session.active().unwrap().history.undo.len();- drop_appearance(&mut app, NodeId(a), Point::new(350.0, 250.0), 1.0);++ drop(&mut app, Point::new(350.0, 250.0));++ drop(&mut app, Point::new(70.0, 70.0));+ assert_eq!(app.session.active().unwrap().history.undo.len(), undo_len);+ }}diff --cc crates/ui-egui/src/dialogs/mod.rsindex ad9321341,85ba0f1a4..0b12280e0--- a/crates/ui-egui/src/dialogs/mod.rs+++ b/crates/ui-egui/src/dialogs/mod.rs@@@ -141,7 -141,7 +142,8 @@@ registry!NewColorGroup: [new_color_group::KIND] => new_color_group::SPEC,GradientStop: ["gradientStop"] => gradient_stop::SPEC,ColorPicker: [color_picker::KIND] => color_picker::SPEC,+ GraphicStyleOptions: [graphic_style_options::KIND] => graphic_style_options::SPEC,+ EffectExists: [effect::EXISTS] => effect::EXISTS_SPEC,}/// The spec for a `Dialog::kind` ([`DialogSpec::FORM`] when unregistered).diff --cc crates/ui-egui/src/panels/appearance.rsindex 066f5d372,73502e018..add1a8811--- a/crates/ui-egui/src/panels/appearance.rs+++ b/crates/ui-egui/src/panels/appearance.rs@@@ -10,8 -15,9 +15,9 @@@ use vectorcraft_color::{BlendMode, Painuse vectorcraft_doc::{AppearanceItem, Effect, Node, NodeId};use super::{first_selected, live_run, pstate, set_pstate};+ use crate::panels::stroke::paint_profile;use crate::theme::Tokens;--use crate::widgets::{self, TransparencyEdit, menu_item};++use crate::widgets::{self, PanelDrag, TransparencyEdit, menu_item};use crate::{VectorcraftApp, icons};const ROW: f32 = 30.0;@@@ -70,8 -77,56 +77,51 @@@ pub(crate) fn select_row(app: &mut Vect}let owner = app.session.active().and_then(|d| d.selection.objects.first().copied());set_pstate(ctx, "ap-sel", (owner, sel));+ set_pstate(ctx, "ap-multi", (owner, sel.item().into_iter().collect::<Vec<usize>>()));+ }++ /// The selected fill/stroke rows of `n` (paint order, ascending): the active row plus those+ /// Cmd/Shift-clicked with it.+ fn selected_items(ctx: &egui::Context, n: Option<&Node>, sel: Sel) -> Vec<usize> {+ let (Some(n), Sel::Item(active)) = (n, sel) else { return vec![] };+ let (owner, mut set): (Option<NodeId>, Vec<usize>) = pstate(ctx, "ap-multi");+ if owner != Some(n.id) || !set.contains(&active) {+ return vec![active];+ }+ set.retain(|i| *i < n.appearance.items.len());+ set.sort_unstable();+ set.dedup();+ set+ }++ /// Click on fill/stroke row `i`: Shift extends the selection from the active row, Cmd toggles+ /// the row, a plain click selects only it.+ fn click_item(app: &mut VectorcraftApp, ctx: &egui::Context, n: &Node, sel: Sel, i: usize, m: egui::Modifiers) {+ let mut set = selected_items(ctx, Some(n), sel);+ let active = match sel {+ Sel::Item(a) if m.shift => {+ set = (a.min(i)..=a.max(i)).collect();+ a+ }+ Sel::Item(a) if m.command => {+ match set.iter().position(|x| *x == i) {+ Some(p) if set.len() > 1 => {+ set.remove(p);+ }+ Some(_) => {}+ None => set.push(i),+ }+ if set.contains(&a) { a } else { set[0] }+ }+ _ => {+ set = vec![i];+ i+ }+ };+ select_row(app, ctx, Sel::Item(active));+ set_pstate(ctx, "ap-multi", (Some(n.id), set));}-/// Dragged from the object row's thumbnail and dropped on art: the object under the pointer takes-/// this object's appearance (`appearance.copyFrom`, see `canvas::drop_appearance`).-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub struct AppearanceDrag(pub NodeId);-fn catalog() -> &'static [(String, String, Vec<String>)] {static C: OnceLock<Vec<(String, String, Vec<String>)>> = OnceLock::new();C.get_or_init(|| {@@@ -184,8 -234,11 +234,11 @@@ pub fn show(app: &mut VectorcraftApp, ulet th = Rect::from_min_size(r.left_center() + vec2(6.0, -12.0), vec2(24.0, 24.0));let fill = node.as_ref().map(|n| n.appearance.fill_paint()).unwrap_or_else(|| app.session.paint.fill.clone());chip(ui, th, &fill);+ if let Some(n) = node.as_ref().filter(|_| !mixed) {- thumbnail_drag(ui, th, n.id, &fill);++ thumbnail_drag(ui, th, n.id);+ }}- text(ui, r.left_center() + vec2(if hide_thumb { 8.0 } else { 46.0 }, 0.0), label, true);+ text(ui, r.left_center() + vec2(if hide_thumb { 8.0 } else { 46.0 }, 0.0), &label, true);match &node {// Objects that differ have no common stack to list.Some(_) if mixed => {}@@@ -198,6 -251,21 +251,16 @@@bottom(app, ui, node.as_ref(), sel);}-/// The object row's thumbnail drags this object's appearance onto art (a chip follows the pointer).-fn thumbnail_drag(ui: &mut Ui, th: Rect, id: NodeId, fill: &Paint) {++/// The object row's thumbnail drags this object's appearance onto art ([`PanelDrag::Appearance`];++/// a chip of its fill follows the pointer).++fn thumbnail_drag(ui: &mut Ui, th: Rect, id: NodeId) {+ let resp = ui.interact(th, ui.id().with("ap-thumb"), Sense::drag()).on_hover_text("Drag onto art to apply this appearance");- resp.dnd_set_drag_payload(AppearanceDrag(id));- if resp.dragged()- && let Some(p) = ui.ctx().pointer_interact_pos()- {++ widgets::drag_source(ui, &resp, || PanelDrag::Appearance(id));++ if resp.dragged() {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);- let layer = egui::LayerId::new(egui::Order::Tooltip, ui.id().with("ap-thumb-drag"));- let r = Rect::from_min_size(p + vec2(8.0, 8.0), vec2(18.0, 18.0));- let ghost = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(r.expand(1.0)));- chip(&ghost, r, fill);+ }+ }+/// The selection as the Control bar and the object row name it: "No Selection", "Mixed Objects"/// or the object's kind ("Path", "Type", …).pub(crate) fn object_label(app: &VectorcraftApp) -> &'static str {@@@ -587,12 -777,10 +772,14 @@@ pub fn menu(app: &mut VectorcraftApp, uset_pstate(ui.ctx(), "ap-hide-thumb", !hide);}ui.separator();- menu_item(ui, "Redefine Graphic Style", false, false);+ let style = app.session.selection_graphic_style().map(|(g, _)| g.name.clone());+ let redefine = style.as_ref().map_or_else(|| "Redefine Graphic Style".into(), |n| format!("Redefine Graphic Style \u{201c}{n}\u{201d}"));+ if menu_item(ui, &redefine, style.is_some(), false) {+ app.run("graphicStyle.redefine", json!({})).ok();+ }- menu_item(ui, "Show All Hidden Attributes", false, false);+ if menu_item(ui, "Show All Hidden Attributes", node.as_ref().is_some_and(|n| n.appearance.has_hidden()), false) {+ app.run("appearance.showAllHidden", json!({})).ok();+ }}#[cfg(test)]diff --cc crates/ui-egui/src/panels/swatches.rsindex 4a82cb32d,5018fd298..886b1426d--- a/crates/ui-egui/src/panels/swatches.rs+++ b/crates/ui-egui/src/panels/swatches.rs@@@ -330,213 -224,6 +330,222 @@@ fn click_selection(ui: &Ui, mut sel: Vesel}+/// 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 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> },+}++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 },++ /// it carries, or make a swatch of a paint dragged from elsewhere (appearances: nothing).++ fn of(d: &PanelDrag, target: Option<String>, after: bool) -> Option<Self> {++ match d {++ PanelDrag::Paint { rows: Some(r), .. } => Some(Drop::Move { names: r.names.clone(), target, after }),++ PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target }),++ PanelDrag::Appearance(_) => None,+ }+ }+}+++/// The drag held over `resp`, if the panel takes it (paints, not the Appearance panel's thumbnail).++fn held(resp: &Response) -> Option<std::sync::Arc<PanelDrag>> {++ resp.dnd_hover_payload::<PanelDrag>().filter(|d| matches!(**d, PanelDrag::Paint { .. }))++}+++/// 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 [`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(), 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 Some(d) = held(resp) else { return };++ let PanelDrag::Paint { rows, .. } = &*d else { return };+ 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));++ ev.drop = 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 Some(d) = zone.dnd_hover_payload::<PanelDrag>() else { return };++ let Some(d) = held(zone) 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 zone.dnd_release_payload::<PanelDrag>().is_some() {- ev.drop = Some(Drop::of(&d, None, false));++ ev.drop = 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);+ }+}+- /// While a paint is dragged (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail), a chip- /// of it follows the pointer.++/// While a panel drags something onto art, a chip follows the pointer: the dragged paint (swatches,++/// a Fill/Stroke proxy, the Gradient panel's thumbnail), or the fill of the object whose++/// appearance the Appearance panel's thumbnail carries.+pub(crate) fn drag_preview(app: &VectorcraftApp, ctx: &egui::Context) {+ 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 (paint, registration) = match &*d {++ // Colour groups paint nothing.++ PanelDrag::Paint { params, .. } if params.is_null() => return,++ PanelDrag::Paint { paint, rows, .. } => (std::borrow::Cow::Borrowed(paint), rows.as_ref().is_some_and(|r| r.grabbed == REGISTRATION)),++ PanelDrag::Appearance(id) => match app.session.active().and_then(|st| st.doc.node(*id)) {++ Some(n) => (std::borrow::Cow::Owned(n.appearance.fill_paint()), false),++ None => return,++ },++ };+ 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() {diff --cc crates/ui-egui/src/panels/tests_effectedit.rsindex 000000000,9a31792cc..f000cbd00mode 000000,100644..100644--- a/crates/ui-egui/src/panels/tests_effectedit.rs+++ b/crates/ui-egui/src/panels/tests_effectedit.rs@@@ -1,0 -1,196 +1,196 @@@+ //! Headless frames of the Appearance panel's editing depth: effect names open their dialog+ //! prefilled, rows drag (Alt copies), several fills/strokes select together, stroke notes, the+ //! chip's Shift-click, the thumbnail drag and the Properties fx button.++ use serde_json::{Value, json};++ use super::tests_appearance::{app_with_rect, click, frame_events, frame_raw, run, text_rect};+ use super::*;++ fn pointer(pos: egui::Pos2, pressed: bool, modifiers: egui::Modifiers) -> egui::Event {+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }+ }++ /// One frame of the Appearance panel with `events` and `modifiers` held.+ fn panel_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, modifiers: egui::Modifiers) -> Vec<(String, egui::Rect)> {+ let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();+ frame_raw(ctx, app, egui::RawInput { events, ..Default::default() }, appearance::show)+ }++ /// Drag from `from` to `to` in the Appearance panel, `modifiers` held on release.+ fn drag(ctx: &egui::Context, app: &mut VectorcraftApp, from: egui::Pos2, to: egui::Pos2, modifiers: egui::Modifiers) {+ let none = egui::Modifiers::NONE;+ panel_frame(ctx, app, vec![egui::Event::PointerMoved(from)], none);+ panel_frame(ctx, app, vec![pointer(from, true, none)], none);+ panel_frame(ctx, app, vec![egui::Event::PointerMoved(from + egui::vec2(0.0, 8.0))], none);+ panel_frame(ctx, app, vec![egui::Event::PointerMoved(to)], modifiers);+ panel_frame(ctx, app, vec![pointer(to, false, modifiers)], modifiers);+ panel_frame(ctx, app, vec![], none);+ }++ /// Click `pos` with `modifiers` held.+ fn click_with(ctx: &egui::Context, app: &mut VectorcraftApp, pos: egui::Pos2, modifiers: egui::Modifiers) {+ for e in [egui::Event::PointerMoved(pos), pointer(pos, true, modifiers), pointer(pos, false, modifiers)] {+ panel_frame(ctx, app, vec![e], modifiers);+ }+ }++ /// A point in the row of the label `s` (right of its chip, weight and notes).+ fn row_of(texts: &[(String, egui::Rect)], s: &str) -> egui::Pos2 {+ let r = text_rect(texts, s);+ egui::pos2(r.left() + 200.0, r.center().y)+ }++ /// The rect of the panel-menu entry `s` (entries are drawn after a check-mark column).+ fn menu_item(texts: &[(String, egui::Rect)], s: &str) -> egui::Rect {+ texts.iter().find(|(t, _)| t.trim_start() == s).unwrap_or_else(|| panic!("`{s}` not in the menu: {texts:?}")).1+ }++ fn effects(app: &VectorcraftApp, item: Option<usize>) -> Vec<vectorcraft_doc::Effect> {+ first_selected(app).unwrap().appearance.effects_at(item).cloned().unwrap_or_default()+ }++ #[test]+ fn an_effect_name_opens_its_dialog_prefilled_and_ok_edits_it_in_place() {+ let mut app = app_with_rect();+ run(&mut app, "effect.apply", json!({"effect": "distort.roughen", "params": {"size": 9}}));+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx);+ let texts = frame_events(&ctx, &mut app, vec![], appearance::show);+ click(&ctx, &mut app, text_rect(&texts, "Roughen").center(), appearance::show);+ let d = app.ui.dialog.clone().expect("the effect's dialog");+ assert_eq!((d.kind.as_str(), d.f64("size", 0.0), d.fields["__index"].clone()), ("effect", 9.0, json!(0)));+ // The dialog previews; OK keeps the new value on the same effect as one undo step.+ let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::show(&mut app, ui.ctx()));+ out.textures_delta.clear();+ app.ui.dialog.as_mut().unwrap().fields.insert("size".into(), json!(20));+ crate::dialogs::confirm(&mut app).unwrap();+ let fx = effects(&app, None);+ assert_eq!((fx.len(), fx[0].params["size"].clone()), (1, json!(20)));+ assert!(app.ui.dialog.is_none() && app.last_effect.is_none(), "an edit is not a new Last Effect");+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(effects(&app, None)[0].params["size"], json!(9));+ }++ #[test]+ fn choosing_an_applied_effect_asks_to_edit_it_or_add_another() {+ let mut app = app_with_rect();+ run(&mut app, "effect.apply", json!({"effect": "distort.roughen", "item": 0, "params": {"size": 9}}));+ run(&mut app, "appearance.setActiveItem", json!({"index": 0}));+ // The active fill already has it: the question comes first; OK edits the applied one.+ assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(), json!({"pending": "effectExists"}));+ crate::dialogs::confirm(&mut app).unwrap();+ let d = app.ui.dialog.clone().unwrap();+ assert_eq!((d.kind.as_str(), d.f64("size", 0.0), d.fields["__index"].clone(), d.fields["__item"].clone()), ("effect", 9.0, json!(0), json!(0)));+ crate::dialogs::confirm(&mut app).unwrap();+ assert_eq!(effects(&app, Some(0)).len(), 1);+ // "Add New": a fresh dialog with the defaults, which adds a second one.+ app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap();+ app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true));+ crate::dialogs::confirm(&mut app).unwrap();+ let d = app.ui.dialog.clone().unwrap();+ assert!(d.fields.get("__index").is_none() && d.f64("size", 0.0) == 5.0, "{:?}", d.fields);+ crate::dialogs::confirm(&mut app).unwrap();+ assert_eq!(effects(&app, Some(0)).len(), 2);+ // Another list without it opens the dialog directly.+ assert_eq!(app.run("effect.dialog", json!({"effect": "distort.roughen", "item": null})).unwrap(), Value::Null);+ assert_eq!(app.ui.dialog.as_ref().unwrap().kind, "effect");+ }++ #[test]+ fn effect_rows_drag_to_reorder_and_into_an_item() {+ let mut app = app_with_rect();+ run(&mut app, "effect.apply", json!({"effect": "distort.twist"}));+ run(&mut app, "effect.apply", json!({"effect": "distort.roughen"}));+ let ctx = egui::Context::default();+ let texts = panel_frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);+ // Twist below Roughen.+ let below = text_rect(&texts, "Roughen").center() + egui::vec2(60.0, 9.0);+ drag(&ctx, &mut app, row_of(&texts, "Twist"), below, egui::Modifiers::NONE);+ let ids = |fx: Vec<vectorcraft_doc::Effect>| fx.into_iter().map(|e| e.id).collect::<Vec<_>>();+ assert_eq!(ids(effects(&app, None)), ["distort.roughen", "distort.twist"]);+ // Alt-dragging Twist onto the stroke row copies it into the stroke's effects.+ let texts = panel_frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);+ drag(&ctx, &mut app, row_of(&texts, "Twist"), row_of(&texts, "Stroke:"), egui::Modifiers::ALT);+ assert_eq!(ids(effects(&app, None)), ["distort.roughen", "distort.twist"]);+ assert_eq!(ids(effects(&app, Some(1))), ["distort.twist"]);+ // Dropped effects become the selected row (their item active).+ assert_eq!(app.session.appearance_item(), Some(1));+ app.run("edit.undo", json!({})).unwrap();+ assert!(effects(&app, Some(1)).is_empty());+ }++ #[test]+ fn alt_dragging_an_item_duplicates_it_and_several_items_delete_together() {+ let mut app = app_with_rect(); // [Fill, Stroke]+ let ctx = egui::Context::default();+ let texts = panel_frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);+ drag(&ctx, &mut app, row_of(&texts, "Fill:"), row_of(&texts, "Stroke:"), egui::Modifiers::ALT);+ let kinds = |app: &VectorcraftApp| first_selected(app).unwrap().appearance.items.iter().map(|i| i.kind_name()).collect::<Vec<_>>();+ assert_eq!(kinds(&app), ["fill", "stroke", "fill"]);+ // Click the stroke, Cmd-click the top fill: both go with Remove Item.+ let texts = panel_frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);+ click_with(&ctx, &mut app, row_of(&texts, "Stroke:"), egui::Modifiers::NONE);+ let top_fill = texts.iter().filter(|(t, _)| t == "Fill:").map(|(_, r)| *r).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap();+ click_with(&ctx, &mut app, egui::pos2(top_fill.left() + 200.0, top_fill.center().y), egui::Modifiers::COMMAND);+ let menu = frame_events(&ctx, &mut app, vec![], appearance::menu);+ click(&ctx, &mut app, menu_item(&menu, "Remove Item").center(), appearance::menu);+ assert_eq!(kinds(&app), ["fill"]);+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(kinds(&app).len(), 3, "one undo step");+ }++ #[test]+ fn stroke_rows_note_dashes_brushes_and_show_all_hidden_attributes() {+ let mut app = app_with_rect();+ let ctx = egui::Context::default();+ assert!(!frame_events(&ctx, &mut app, vec![], appearance::show).iter().any(|(t, _)| t == "Dashed"));+ run(&mut app, "stroke.set", json!({"dash": [4, 2], "profile": "lens"}));+ let brush = run(&mut app, "brush.list", json!({}))["brushes"][0]["name"].as_str().unwrap().to_string();+ run(&mut app, "brush.apply", json!({ "name": brush }));+ let texts = frame_events(&ctx, &mut app, vec![], appearance::show);+ assert!(texts.iter().any(|(t, _)| *t == format!("{brush}, Dashed")), "{texts:?}");+ // Show All Hidden Attributes is enabled once something is hidden, and shows it.+ let enabled = |app: &mut VectorcraftApp| {+ let menu = frame_events(&ctx, app, vec![], appearance::menu);+ let r = menu_item(&menu, "Show All Hidden Attributes");+ click(&ctx, app, r.center(), appearance::menu);+ };+ run(&mut app, "appearance.setItem", json!({"index": 0, "visible": false}));+ enabled(&mut app);+ assert!(first_selected(&app).unwrap().appearance.items[0].visible());+ }++ #[test]+ fn shift_clicking_a_chip_opens_the_mixer_on_that_row() {+ let mut app = app_with_rect();+ let ctx = egui::Context::default();+ let texts = panel_frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);+ // The chip sits 52 pt right of the label's start (label at EYE_W + 24, chip at EYE_W + 76).+ let label = text_rect(&texts, "Fill:");+ click_with(&ctx, &mut app, egui::pos2(label.left() + 52.0 + 9.0, label.center().y), egui::Modifiers::SHIFT);+ assert_eq!(app.ui.open_panel.as_deref(), Some("color"));+ assert_eq!(app.session.appearance_item(), Some(0));+ }++ #[test]+ fn the_thumbnail_drags_the_appearance_and_the_properties_fx_button_opens_the_effects() {+ let mut app = app_with_rect();+ let ctx = egui::Context::default();+ let texts = panel_frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);+ // The thumbnail is left of the object row's label.+ let label = text_rect(&texts, "Rectangle");+ let thumb = egui::pos2(label.left() - 28.0, label.center().y);+ let none = egui::Modifiers::NONE;+ for e in [egui::Event::PointerMoved(thumb), pointer(thumb, true, none), egui::Event::PointerMoved(thumb + egui::vec2(30.0, 30.0))] {+ panel_frame(&ctx, &mut app, vec![e], none);+ }+ let id = first_selected(&app).unwrap().id;- assert_eq!(egui::DragAndDrop::payload::<appearance::AppearanceDrag>(&ctx).as_deref(), Some(&appearance::AppearanceDrag(id)));++ assert_eq!(egui::DragAndDrop::payload::<crate::widgets::PanelDrag>(&ctx).as_deref(), Some(&crate::widgets::PanelDrag::Appearance(id)));+ // Properties: the fx button lists the effect groups.+ let props = egui::Context::default();+ let texts = frame_raw(&props, &mut app, Default::default(), properties::show);+ click(&props, &mut app, text_rect(&texts, "fx").center(), properties::show);+ let texts = frame_raw(&props, &mut app, Default::default(), properties::show);+ assert!(texts.iter().any(|(t, _)| t == "Distort & Transform"), "{texts:?}");+ }diff --cc crates/ui-egui/src/widgets.rsindex bffab921e,a065000b8..70b89b216--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@@ -944,52 -902,3 +944,56 @@@ pub fn opt_field(ui: &mut Ui, id: implNone}}++/// 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 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 Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance++ /// (`appearance.copyFrom`).++ Appearance(vectorcraft_doc::NodeId),+}++/// 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(),++ Self::Appearance(_) => None,+ }+ }+}++/// 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());+ }+}diff --cc docs/control-protocol.mdindex 74b29c1b5,15cc0165c..6cfa113fd--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@@ -37,19 -37,9 +37,26 @@@ fill or stroke (fields as in `swatchOptThe 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, 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.+++ Effect dialogs: `engine.execute {command: "effect.dialog", params: {effect, index?, item?}}` opens the `effect` dialog+ (fields: the effect's parameters, `preview`). With `index` it edits that applied effect of `item` (null: the object's+ effects) prefilled with its values, and `ui.dialog.confirm` runs `effect.setParams`; otherwise confirm runs+ `effect.apply`. Choosing an effect that the list already has returns `{"pending": "effectExists"}` and opens the+ `effectExists` question: `ui.dialog.confirm` opens the applied effect's dialog, `ui.dialog.set {field: "discard",+ value: true}` then confirm opens a fresh one that adds another, `ui.dialog.cancel` drops it.diff --cc docs/mcp.mdindex 9f5465933,f006d6bea..f05d937c2--- a/docs/mcp.md+++ b/docs/mcp.md@@@ -215,19 -197,11 +215,30 @@@ plain group and keeps the clipping path{"name":"run_command","arguments":{"command":"object.clippingMask.make","params":{}}}```+## Graphic styles++A graphic style holds an appearance (fills, strokes, effects) plus opacity, blend mode, isolate and knockout.+`graphicStyle.new {name?, id?}` captures an object (a group without its own fills or strokes lends its topmost+object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the objects the style and links them;+`add: true` adds the style on top of the existing appearance instead. Linked objects stay linked while they keep the+style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}`+updates only the objects still linked. `graphicStyle.list` returns each style with the ids linked to it and the+style of the first selected object; `select.same.graphicStyle` selects an object's fellow users.++Styles keep placed gradients relative to the bounds of the object they were made from, and each object a++style is applied to gets them at the same place relative to its own bounds.++```json+{"name":"run_command","arguments":{"command":"graphicStyle.new","params":{"id":12,"name":"Glow"}}}+{"name":"run_command","arguments":{"command":"graphicStyle.apply","params":{"name":"Glow","ids":[15,20]}}}+{"name":"run_command","arguments":{"command":"graphicStyle.redefine","params":{"id":12}}}+{"name":"run_command","arguments":{"command":"graphicStyle.list","params":{}}}+```+++ ## Editing appearance stacks++ `effect.move {from, to, fromItem?, toItem?, copy?}` reorders an effect or moves it between the object's effects+ (`null`) and a fill's or stroke's (an item index), as dragging its row in the Appearance panel does; `copy: true` copies+ it (Alt-drag). `appearance.duplicateItem {index, to?}` / `{indices}` and `appearance.removeItem {index | indices}`+ act on several fills/strokes at once, and `appearance.showAllHidden` makes every hidden fill, stroke and effect+ visible again. In remote mode, `effect.dialog {effect, index, item}` opens an applied effect's dialog prefilled+ (`ui.dialog.confirm` runs `effect.setParams`); see the control protocol for the "already applied" question.