Skip to content

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

Merge wp/F1

bflatastic96f1b6852a73
diff --cc crates/doc/src/node.rs
index 9ed084cf6,4665da16d..5e36727aa
--- a/crates/doc/src/node.rs
+++ b/crates/doc/src/node.rs
@@@ -525,55 -516,88 +525,121 @@@ impl Node
self.walk(&mut |_| n += 1);
n
}
+ /// Fix this node's unplaced gradients to their fit on its current bounds (before a transform
+ /// or warp that refitting wouldn't reproduce). Descendants pin their own when transformed.
+ pub fn pin_gradients(&mut self) {
+ if self.appearance.has_unplaced_gradient()
+ && let Some(b) = self.geometric_bounds()
+ {
+ self.appearance.pin_gradients(b);
+ }
+ }
+ /// The paint behind the Fill (or Stroke) proxy, the map from its space to the document and
+ /// the box (in that space) an unplaced gradient fits. `item` (the Appearance panel's active
+ /// item) stands in for the topmost fill or stroke when it is of the proxy's kind. Otherwise
+ /// type objects paint their runs (the first run speaks for all) in text space, fitted to the
+ /// layout bounds; everything else paints its fill or stroke in the document, fitted to the
+ /// geometric bounds. Strokes fit the box grown by half their weight.
+ pub fn proxy_paint(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::Paint, Affine, Rect)> {
+ let item = self.appearance.item_of_kind(item, !stroke);
+ if item.is_none()
+ && let NodeKind::Text(t) = &self.kind
+ {
+ let st = &t.runs.first()?.style;
+ let b = t.local_bounds();
+ return Some(if stroke { (&st.stroke, t.xf, crate::appearance::stroke_paint_bounds(b, st.stroke_width)) } else { (&st.fill, t.xf, b) });
+ }
+ let b = self.geometric_bounds()?;
+ if stroke {
+ self.appearance.stroke_at(item).map(|s| (&s.paint, Affine::IDENTITY, s.paint_bounds(b)))
+ } else {
+ self.appearance.fill_at(item).map(|f| (&f.paint, Affine::IDENTITY, b))
+ }
+ }
+ /// The gradient behind the Fill (or Stroke) proxy and its placement in document coordinates
+ /// (see [`Node::proxy_paint`]): what the gradient annotator shows and edits.
+ pub fn proxy_gradient(&self, stroke: bool, item: Option<usize>) -> Option<(&vectorcraft_color::GradientPaint, vectorcraft_color::GradientGeom)> {
+ let (paint, to_doc, b) = self.proxy_paint(stroke, item)?;
+ let vectorcraft_color::Paint::Gradient(g) = paint else { return None };
+ let mut geom = g.resolve(b);
+ if to_doc != Affine::IDENTITY {
+ geom.transform(to_doc, g.gradient.kind);
+ }
+ Some((g, geom))
+ }
}
+ /// Unites filled regions (each under its own fill rule) into one path filled non-zero. Booleans
+ /// live above this crate (`vectorcraft-pathops`), so callers supply it.
+ pub type Uniter<'a> = &'a dyn Fn(&[(BezPath, FillRule)]) -> BezPath;
+
+ impl Node {
+ /// The filled regions this object clips to as the clipping path of a clip group, in document
+ /// space, each with its fill rule: a path, a compound path (with its holes), an image's frame,
+ /// text outlined by `text` (glyph outlines need the font engine, above this crate), the visible
+ /// members of a group (their union) and the clipping path of a nested clip group. Live objects
+ /// are evaluated first. Guides and symbol instances add nothing.
+ pub fn clip_shapes(&self, text: Outliner) -> Vec<(BezPath, FillRule)> {
+ let mut out = vec![];
+ self.push_clip_shapes(text, &mut out);
+ out
+ }
+
+ fn push_clip_shapes(&self, text: Outliner, out: &mut Vec<(BezPath, FillRule)>) {
+ match &self.kind {
+ NodeKind::Path { guide: true, .. } | NodeKind::SymbolInstance { .. } => {}
+ NodeKind::Path { path, rule, .. } => out.push((path.to_bezpath(), *rule)),
+ NodeKind::Compound { children, rule } => {
+ let mut bp = BezPath::new();
+ for p in children.iter().filter_map(|c| c.path_data()) {
+ bp.extend(p.to_bezpath());
+ }
+ out.push((bp, *rule));
+ }
+ NodeKind::Group { children, clip: true } => {
+ if let Some(c) = children.first() {
+ c.push_clip_shapes(text, out);
+ }
+ }
+ NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
+ for c in children.iter().filter(|c| c.visible) {
+ c.push_clip_shapes(text, out);
+ }
+ }
+ NodeKind::Text(_) => {
+ if let Some(o) = text.and_then(|f| f(self)) {
+ o.push_clip_shapes(None, out);
+ }
+ }
+ NodeKind::Image(im) => {
+ let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
+ out.push((frame.to_bezpath(), FillRule::NonZero));
+ }
+ NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) => {
+ crate::live::expand_deep(self, text).push_clip_shapes(text, out);
+ }
+ }
+ }
+
+ /// The region this object clips to as one path and fill rule ([`Self::clip_shapes`]), shared
+ /// by the renderer and the SVG and PDF writers so every output clips alike. One shape keeps its
+ /// own rule; several are united by `unite` (filled non-zero). `None` when there is nothing to
+ /// clip by: the clipped art is then hidden.
+ pub fn clip_outline(&self, text: Outliner, unite: Uniter) -> Option<(BezPath, FillRule)> {
+ let mut shapes = self.clip_shapes(text);
+ match shapes.len() {
+ 0 => None,
+ 1 => shapes.pop(),
+ _ => Some((unite(&shapes), FillRule::NonZero)),
+ }
+ }
+ }
+
-fn transform_paints(ap: &mut Appearance, a: Affine) {
- use crate::appearance::AppearanceItem;
- use vectorcraft_color::Paint;
- for it in &mut ap.items {
- let p = match it {
- AppearanceItem::Fill(f) => &mut f.paint,
- AppearanceItem::Stroke(s) => &mut s.paint,
- };
- if let Paint::Gradient(g) = p
- && let Some(geom) = &mut g.geom
- {
- geom.transform(a);
- }
- }
+/// Is `a` a move plus a positive uniform scale (after which a refit gradient still matches)?
+fn keeps_gradient_fit(a: Affine) -> bool {
+ let [m0, m1, m2, m3, _, _] = a.as_coeffs();
+ let eps = 1e-12 * m0.abs().max(1.0);
+ m0 > 0.0 && m1.abs() <= eps && m2.abs() <= eps && (m0 - m3).abs() <= eps
}
#[cfg(test)]
diff --cc crates/effects/src/lib.rs
index 3268d9488,db3ebd0e1..425d3167c
--- a/crates/effects/src/lib.rs
+++ b/crates/effects/src/lib.rs
@@@ -8,10 -8,10 +8,12 @@@
//! - **Raster effects** (Drop Shadow, Inner/Outer Glow, Feather, Gaussian Blur) are described by
//! [`raster_effects`] and painted by the renderer; [`outset`] says how far they reach beyond
//! the geometry.
+//! - **Stroke geometry** ([`stroke`]): arrowheads, dash patterns and width profiles, shared by the
+//! renderer, the exporters and Outline Stroke.
//! - [`effect_catalog`] lists every effect with its menu path, parameter documentation and the
//! defaults of Illustrator's dialogs. Missing parameters always fall back to those defaults.
+ //! - [`clip_outline`] is the region a clip group clips to, shared by the renderer and the SVG and
+ //! PDF writers.
//!
//! Everything is deterministic: "random" effects (Roughen, Tweak, Scribble) use a seeded hash
//! noise (`seed` parameter, default 0).
diff --cc crates/engine/src/cmd/appearance.rs
index e3d041045,d4863d37f..48ac07dc5
--- a/crates/engine/src/cmd/appearance.rs
+++ b/crates/engine/src/cmd/appearance.rs
@@@ -11,9 -3,10 +11,10 @@@
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
-use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, NodeKind, StrokeLayer};
+use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeKind, StrokeLayer};
use super::edit::selected_roots;
+ use super::opacitymask::percent;
use super::paint::paint_from;
use super::*;
use crate::EngineError;
@@@ -61,22 -22,14 +62,22 @@@ pub fn specs() -> Vec<CommandSpec>
"Appearance Item",
[],
None,
- "{index: paint-order item index, opacity?: 0..1 (values above 1 are percent), blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), ids?} edit one fill/stroke of each selected object's own appearance stack",
- has_selection,
- "{index, ids?, opacity?: 0..100, blend?, visible?, weight?, color?|none?|swatch?|gradient?} edit one fill/stroke of the appearance stack of `ids` (default: the selection)",
++ "{index: paint-order item index, ids? (default: the selection), opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill)} edit one fill/stroke of each target object's own appearance stack",
+ has_doc,
set_item
),
- cmd!("appearance.removeItem", "Remove Item", [], None, "{index}", has_selection, remove_item),
- cmd!("appearance.addEffect", "Add Effect", ["Effect"], None, "{effect: id, params?: {…}} append a live effect", has_selection, add_effect),
- cmd!("appearance.duplicateItem", "Duplicate Item", ["Window", "Appearance"], None, "{index}", has_selection, duplicate_item),
- cmd!("appearance.moveItem", "Reorder Appearance Item", [], None, "{from, to} (paint-order indices)", has_selection, move_item),
+ cmd!("appearance.removeItem", "Remove Item", [], None, "{index, ids?}", has_selection, remove_item),
+ cmd!(
+ "appearance.addEffect",
+ "Add Effect",
+ [],
+ None,
+ "same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?} → {ids, index, item}",
+ has_selection,
+ super::effectcmd::apply
+ ),
+ cmd!("appearance.duplicateItem", "Duplicate Item", ["Window", "Appearance"], None, "{index, ids?}", has_selection, duplicate_item),
+ cmd!("appearance.moveItem", "Reorder Appearance Item", [], None, "{from, to, ids?} (paint-order indices)", has_selection, move_item),
cmd!(
"appearance.copyFrom",
"Eyedropper",
@@@ -341,9 -95,12 +342,12 @@@ fn reduce_basic(s: &mut Session, p: &Va
}
fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
- let idx = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("appearance.setItem", "missing index"))? as usize;
+ let idx = index_param(p, "index", "appearance.setItem")?;
let paint = paint_from(s, p)?;
- let ids = paint_targets(s, p)?;
+ let ids = appearance_targets(s, p)?;
+ if ids.is_empty() {
+ return Err(bad("appearance.setItem", "select objects or give ids"));
+ }
let blend = str_param(p, "blend").and_then(BlendMode::parse);
s.edit("Appearance", |d, _| {
for id in &ids {
@@@ -361,10 -116,10 +365,10 @@@
}
};
if let Some(pa) = &paint {
- *pp = pa.clone();
+ *pp = super::gradient::place_paint(pa, p, bounds);
}
if let Some(o) = p.get("opacity").and_then(Value::as_f64) {
- *op = if o > 1.0 { o / 100.0 } else { o }.clamp(0.0, 1.0) as f32;
+ *op = percent(o);
}
if let Some(b) = blend {
*bl = b;
diff --cc crates/engine/src/cmd/fileio/encode.rs
index 8ccbb94a9,54a451700..3de0d5f6a
--- a/crates/engine/src/cmd/fileio/encode.rs
+++ b/crates/engine/src/cmd/fileio/encode.rs
@@@ -83,14 -83,24 +83,17 @@@ fn options<T: DeserializeOwned + Defaul
T::deserialize(p).map_err(|e| bad(C, format!("{} options: {e}", f.label)))
}
-/// Most pixels a raster export renders (1 GiB of RGBA).
-const MAX_PIXELS: f64 = 268_435_456.0;
+/// Most pixels a side of a WebP image can have (its sizes are stored in 14 bits).
+const WEBP_SIDE: f64 = 16383.0;
-/// Refuse a raster export the encoder can't write or memory can't hold (instead of writing an
-/// empty file or aborting).
-fn check_pixels(f: &Format, w: f64, h: f64) -> Result<()> {
- // WebP stores sizes in 14 bits, JPEG in 16.
- let side = if f.id == "webp" { 16383.0 } else { 65535.0 };
- if w.round() > side || h.round() > side || w * h > MAX_PIXELS {
+/// Refuse a raster export its format can't store (instead of writing an empty file). The
+/// renderer's own size limits are [`vectorcraft_render::raster_size`]'s.
+fn check_format_size(f: &Format, w: f64, h: f64) -> Result<()> {
+ if f.id == "webp" && (w.round() > WEBP_SIDE || h.round() > WEBP_SIDE) {
- return Err(bad(C, format!("{}×{} px is too large for {} (at most {WEBP_SIDE} px a side): lower the scale", w.round(), h.round(), f.label)));
+ return Err(bad(
+ C,
- format!(
- "{}×{} px is too large for {} (at most {side} px a side, {MAX_PIXELS} px in all): lower the scale",
- w.round(),
- h.round(),
- f.label
- ),
++ format!("{} × {} pixels is too large for {} (at most {WEBP_SIDE} pixels a side): lower the scale", w.round(), h.round(), f.label),
+ ));
}
Ok(())
}
diff --cc crates/engine/src/cmd/paint.rs
index 4da442fa8,ac23f3b71..7ad06d129
--- a/crates/engine/src/cmd/paint.rs
+++ b/crates/engine/src/cmd/paint.rs
@@@ -38,8 -34,8 +38,8 @@@ pub fn specs() -> Vec<CommandSpec>
"Transparency",
["Window", "Transparency"],
None,
- "{opacity?: 0..100, blend?: name, isolate?, knockout?, item?: appearance item index|null, ids?} opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects)",
- has_selection,
- "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?} for `ids`, the selection, or the object whose opacity mask is being edited",
++ "{ids?|id?, opacity?: 0..100, blend?: name, isolate?, knockout?, item?: appearance item index|null} for `ids`, the selection, or the object whose opacity mask is being edited; opacity and blend go to the targeted fill/stroke item (omitted: the Appearance panel's active item, else the objects)",
+ has_doc,
transparency
),
]
@@@ -154,41 -171,11 +154,42 @@@ fn default_paint(s: &mut Session, _: &V
}
fn transparency(s: &mut Session, p: &Value) -> Result<Value> {
+ const C: &str = "transparency.set";
- let item = item_target(s, p, C)?;
+ let ids = super::opacitymask::transparency_targets(s, p)?;
+ if ids.is_empty() {
- return Err(bad("transparency.set", "select objects or give ids"));
++ return Err(bad(C, "select objects or give ids"));
++ }
++ // While an opacity mask is edited the selection is its art, so the Appearance panel's active
++ // item (a row of that art) doesn't stand for the masked object.
++ let editing_mask = p.get("ids").is_none() && p.get("id").is_none() && s.doc()?.doc.mask_edit.is_some();
++ let item = if editing_mask && p.get("item").is_none() { ItemTarget::Top } else { item_target(s, p, C)? };
+ let mut q = p.as_object().cloned().unwrap_or_default();
+ q.remove("item");
- let opacity = q.remove("opacity").and_then(|v| v.as_f64()).map(|o| (o / 100.0).clamp(0.0, 1.0));
++ q.remove("id");
++ q.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
+ let ItemTarget::Item { index, explicit } = item else {
- if let Some(o) = opacity {
- q.insert("opacity".into(), json!(o));
- }
+ return s.execute("object.setProps", &Value::Object(q));
+ };
+ // Opacity and blend belong to the targeted fill/stroke; isolate/knockout stay object-level.
++ let item_ids = if editing_mask { ids } else { appearance_targets(s, p)? };
+ if explicit {
+ let d = &s.doc()?.doc;
- if !appearance_targets(s, p)?.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
++ if !item_ids.iter().any(|id| d.node(*id).is_some_and(|n| index < n.appearance.items.len())) {
+ return Err(bad(C, format!("no appearance item {index}")));
+ }
+ }
- let blend = q.remove("blend");
++ let (opacity, blend) = (q.remove("opacity"), q.remove("blend"));
+ if let Some(b) = &blend
+ && b.as_str().and_then(BlendMode::parse).is_none()
+ {
+ return Err(bad(C, format!("unknown blend mode {b}")));
+ }
+ if opacity.is_some() || blend.is_some() {
- let mut set = json!({ "index": index, "opacity": opacity, "blend": blend });
- for key in ["ids", "id"] {
- if let Some(v) = p.get(key) {
- set[key] = v.clone();
- }
- }
- s.execute("appearance.setItem", &set)?;
++ let ids: Vec<u64> = item_ids.iter().map(|id| id.0).collect();
++ s.execute("appearance.setItem", &json!({ "index": index, "ids": ids, "opacity": opacity, "blend": blend }))?;
+ }
- if q.keys().all(|k| k == "ids" || k == "id") {
++ if q.keys().all(|k| k == "ids") {
+ return ok();
}
- let mut q = if p.is_object() { p.clone() } else { json!({}) };
- q["ids"] = json!(ids.iter().map(|id| id.0).collect::<Vec<_>>());
- s.execute("object.setProps", &q)
+ s.execute("object.setProps", &Value::Object(q))
}
diff --cc crates/engine/src/tests_appearance.rs
index d55627a6a,000000000..c66a856ae
mode 100644,000000..100644
--- a/crates/engine/src/tests_appearance.rs
+++ b/crates/engine/src/tests_appearance.rs
@@@ -1,408 -1,0 +1,408 @@@
+//! Appearance stacks: the active item that paint, stroke, gradient and transparency edits target
+//! (`appearance.setActiveItem`, the `item` param).
+
+use serde_json::{Value, json};
+use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
+use vectorcraft_doc::{AppearanceItem, Node};
+
+use super::*;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ s
+}
+
+/// A selected 100×100 rectangle with the default appearance `[Fill white, Stroke black]`.
+fn rect(s: &mut Session, x: f64) -> NodeId {
+ let r = s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 100, "height": 100})).unwrap();
+ let id = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ id
+}
+
+fn node(s: &Session, id: NodeId) -> Node {
+ s.doc().unwrap().doc.node(id).unwrap().clone()
+}
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+fn stroke(n: &Node, i: usize) -> &vectorcraft_doc::StrokeLayer {
+ n.appearance.stroke_at(Some(i)).unwrap_or_else(|| panic!("item {i} is not a stroke"))
+}
+
+fn fill_paint(n: &Node, i: usize) -> &Paint {
+ &n.appearance.fill_at(Some(i)).unwrap_or_else(|| panic!("item {i} is not a fill")).paint
+}
+
+#[test]
+fn stroke_set_with_item_changes_only_that_stroke() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Stroke]
+ run(&mut s, "stroke.set", json!({"item": 1, "dash": [4, 2], "weight": 6}));
+ let n = node(&s, id);
+ assert_eq!(stroke(&n, 1).dash.as_ref().unwrap().pattern, vec![4.0, 2.0]);
+ assert_eq!(stroke(&n, 1).width, 6.0);
+ assert!(stroke(&n, 2).dash.is_none());
+ assert_eq!(stroke(&n, 2).width, 1.0);
+ run(&mut s, "stroke.setAdvanced", json!({"item": 1, "arrowScale": [50, 200]}));
+ let n = node(&s, id);
+ assert_eq!((stroke(&n, 1).arrow_scale, stroke(&n, 2).arrow_scale), ((50.0, 200.0), (100.0, 100.0)));
+ // An explicit item must be a stroke; nothing changes when it is not.
+ assert!(s.execute("stroke.set", &json!({"item": 0, "weight": 9})).is_err());
+ assert!(s.execute("stroke.set", &json!({"item": 7, "weight": 9})).is_err());
+ assert!(s.execute("stroke.set", &json!({"item": "top", "weight": 9})).is_err());
+ assert_eq!(stroke(&node(&s, id), 2).width, 1.0);
+ // Without an item the top stroke changes.
+ run(&mut s, "stroke.set", json!({"weight": 3}));
+ let n = node(&s, id);
+ assert_eq!((stroke(&n, 1).width, stroke(&n, 2).width), (6.0, 3.0));
+}
+
+#[test]
+fn edit_gradient_on_the_lower_fill() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({})); // [Fill, Stroke, Fill]
+ run(&mut s, "paint.editGradient", json!({"item": 0, "kind": "radial"}));
+ let n = node(&s, id);
+ let Paint::Gradient(g) = fill_paint(&n, 0) else { panic!("lower fill is not a gradient") };
+ assert_eq!(g.gradient.kind, GradientKind::Radial);
+ assert_eq!(*fill_paint(&n, 2), Paint::solid(Color::WHITE));
+ // The gradient vector of the lower fill, through the active item (the gradient tool's path).
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "paint.setGradientGeom", json!({"start": [100, 150], "end": [200, 150]}));
+ let n = node(&s, id);
+ let Paint::Gradient(g) = fill_paint(&n, 0) else { panic!() };
+ assert_eq!(g.geom.unwrap().end.x, 200.0);
+ assert_eq!(*fill_paint(&n, 2), Paint::solid(Color::WHITE));
+ // A stroke row makes the gradient vector a stroke gradient.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ run(&mut s, "paint.setGradientGeom", json!({"start": [100, 150], "end": [100, 250]}));
+ assert!(matches!(stroke(&node(&s, id), 1).paint, Paint::Gradient(_)));
+}
+
+#[test]
+fn active_item_targets_paint_and_proxies_and_clears_on_selection_change() {
+ let mut s = session();
+ let other = rect(&mut s, 250.0);
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({})); // [Fill, Stroke, Fill]
+ assert!(s.execute("appearance.setActiveItem", &json!({"index": 5})).is_err());
+ assert_eq!(run(&mut s, "appearance.setActiveItem", json!({"index": 0}))["index"], 0);
+ assert_eq!(s.appearance_item(), Some(0));
+ assert_eq!(inspect::document(&s)["paint"]["appearanceItem"], 0);
+ assert!(s.fill_active);
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ let n = node(&s, id);
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ assert_eq!(*fill_paint(&n, 2), Paint::solid(Color::WHITE));
+ // The stroke edits fall back to the top stroke while a fill row is active.
+ run(&mut s, "paint.setStroke", json!({"color": "#00ff00"}));
+ assert_eq!(stroke(&node(&s, id), 1).paint.color().unwrap().to_hex(), "#00ff00");
+ // A stroke row brings the Stroke proxy forward.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ assert!(!s.fill_active);
+ // Changing the selection clears it, also when the same object is selected again.
+ run(&mut s, "select.set", json!({"ids": [other.0]}));
+ assert_eq!(s.appearance_item(), None);
+ run(&mut s, "select.set", json!({"ids": [id.0]}));
+ assert_eq!(s.appearance_item(), None);
+ run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
+ let n = node(&s, id);
+ assert_eq!(fill_paint(&n, 2).color().unwrap().to_hex(), "#0000ff");
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ // Explicit ids never use the active item, and `null` forces the top one.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "paint.setFill", json!({"color": "#222222", "ids": [id.0]}));
+ assert_eq!(fill_paint(&node(&s, id), 2).color().unwrap().to_hex(), "#222222");
+ run(&mut s, "paint.setFill", json!({"color": "#111111", "item": null}));
+ let n = node(&s, id);
+ assert_eq!(fill_paint(&n, 2).color().unwrap().to_hex(), "#111111");
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ run(&mut s, "appearance.setActiveItem", json!({"index": null}));
+ assert_eq!(s.appearance_item(), None);
+}
+
+#[test]
+fn item_rows_follow_remove_and_move() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({})); // [Fill, Stroke, Fill]
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ run(&mut s, "appearance.moveItem", json!({"from": 1, "to": 2}));
+ assert_eq!(s.appearance_item(), Some(2));
+ assert!(matches!(node(&s, id).appearance.items[2], AppearanceItem::Stroke(_)));
+ run(&mut s, "appearance.removeItem", json!({"index": 0}));
+ assert_eq!(s.appearance_item(), Some(1));
+ run(&mut s, "appearance.removeItem", json!({"index": 1}));
+ assert_eq!(s.appearance_item(), None);
+}
+
+#[test]
+fn transparency_goes_to_the_targeted_item() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "transparency.set", json!({"item": 1, "opacity": 40, "blend": "multiply"}));
+ let n = node(&s, id);
+ assert_eq!((stroke(&n, 1).opacity, stroke(&n, 1).blend), (0.4, BlendMode::Multiply));
+ assert_eq!((n.opacity, n.blend), (1.0, BlendMode::Normal));
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ // Opacity and blend go to the active item, isolate stays on the object.
+ run(&mut s, "transparency.set", json!({"opacity": 1, "isolate": true}));
+ let n = node(&s, id);
+ assert!((n.appearance.items[0].opacity() - 0.01).abs() < 1e-6);
+ assert!(n.isolate);
+ assert_eq!(n.opacity, 1.0);
+ run(&mut s, "transparency.set", json!({"item": null, "opacity": 50}));
+ assert_eq!(node(&s, id).opacity, 0.5);
+ assert!(s.execute("transparency.set", &json!({"item": 9, "opacity": 50})).is_err());
+}
+
+#[test]
+fn group_rows_are_the_groups_own_stack() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ let b = rect(&mut s, 250.0);
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
+ run(&mut s, "appearance.addFill", json!({}));
+ assert_eq!(node(&s, g).appearance.items.len(), 1);
+ assert_eq!(node(&s, a).appearance.items.len(), 2);
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ assert_eq!(fill_paint(&node(&s, g), 0).color().unwrap().to_hex(), "#ff0000");
+ assert_eq!(*fill_paint(&node(&s, a), 0), Paint::solid(Color::WHITE));
+ // Without a targeted item, a group's fill edit still recolours its contents.
+ run(&mut s, "appearance.setActiveItem", json!({"index": null}));
+ run(&mut s, "paint.setFill", json!({"color": "#00ff00"}));
+ assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00");
+}
+
+#[test]
+fn text_items_take_item_paint() {
+ let mut s = session();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 50, "text": "Hi"}))["id"].as_u64().unwrap());
+ run(&mut s, "select.set", json!({"ids": [t.0]}));
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "paint.setFill", json!({"item": 0, "color": "#ff0000"}));
+ let n = node(&s, t);
+ assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000");
+ let vectorcraft_doc::NodeKind::Text(tx) = &n.kind else { panic!() };
+ assert_ne!(tx.first_style().fill, Paint::solid(Color::from_hex("#ff0000").unwrap()));
+}
+
+#[test]
+fn effects_land_on_the_targeted_item() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ let r = run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 1}));
+ assert_eq!((r["index"].clone(), r["item"].clone()), (json!(0), json!(1)));
+ let n = node(&s, id);
+ assert_eq!(stroke(&n, 1).effects.len(), 1);
+ assert!(n.appearance.effects.is_empty() && n.appearance.items[0].effects().is_empty());
+ run(&mut s, "edit.undo", json!({}));
+ assert!(stroke(&node(&s, id), 1).effects.is_empty());
+ assert!(s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 9})).is_err());
+ assert!(s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": -1})).is_err());
+ // The active item takes the Effect menu's effects (and its alias).
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "effect.apply", json!({"effect": "distort.twist"}));
+ run(&mut s, "appearance.addEffect", json!({"effect": "stylize.roundCorners"}));
+ let n = node(&s, id);
+ assert_eq!(n.appearance.items[0].effects().iter().map(|e| e.id.as_str()).collect::<Vec<_>>(), ["distort.twist", "stylize.roundCorners"]);
+ let l = run(&mut s, "effect.list", json!({}));
+ assert_eq!(l["activeItem"], 0);
+ assert_eq!(l["applied"][0]["items"][0]["kind"], "fill");
+ assert_eq!(l["applied"][0]["items"][0]["effects"].as_array().unwrap().len(), 2);
+ // Sub-row eye, duplicate and delete address the item's list.
+ run(&mut s, "effect.setParams", json!({"index": 1, "visible": false}));
+ run(&mut s, "effect.duplicate", json!({"index": 0}));
+ run(&mut s, "effect.remove", json!({"index": 2}));
+ let fx = node(&s, id).appearance.items[0].effects().clone();
+ assert_eq!(fx.iter().map(|e| (e.id.as_str(), e.visible)).collect::<Vec<_>>(), [("distort.twist", true), ("distort.twist", true)]);
+ assert!(s.execute("effect.remove", &json!({"index": 5})).is_err());
+ // `item: null` addresses the object's own effects.
+ run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "item": null}));
+ assert_eq!(node(&s, id).appearance.effects.len(), 1);
+}
+
+#[test]
+fn per_fill_offset_path_renders() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ run(&mut s, "paint.setStroke", json!({"none": true}));
+ let render = |s: &Session| {
+ vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default())
+ };
+ assert_eq!(render(&s).pixel(90, 150)[3], 0);
+ run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 20}, "item": 0}));
+ assert_eq!(node(&s, id).appearance.items[0].effects().len(), 1);
+ let px = render(&s).pixel(90, 150);
+ assert!(px[0] > 200 && px[3] > 200, "{px:?}");
+}
+
+#[test]
+fn text_fill_items_composite_with_their_opacity() {
+ let mut s = session();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 20, "y": 200, "text": "HIM", "size": 150}))["id"].as_u64().unwrap());
+ run(&mut s, "select.set", json!({"ids": [t.0]}));
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "appearance.setItem", json!({"index": 0, "color": "#ff0000"}));
+ let render = |s: &Session| {
+ vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default())
+ };
+ let opaque = render(&s);
+ // A pixel the red fill covers fully (over the black character fill).
+ let (x, y) = (0..400u32).flat_map(|y| (0..400u32).map(move |x| (x, y))).find(|&(x, y)| opaque.pixel(x, y) == [255, 0, 0, 255]).expect("red text");
- run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 0.5, "blend": "multiply"}));
++ run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 50, "blend": "multiply"}));
+ let px = render(&s).pixel(x, y);
+ // Half of red multiplied over black: black.
+ assert!(px[0] < 20 && px[3] == 255, "{px:?}");
+ run(&mut s, "appearance.setItem", json!({"index": 0, "blend": "normal"}));
+ let px = render(&s).pixel(x, y);
+ assert!((110..=145).contains(&px[0]) && px[1] < 10, "{px:?}");
+}
+
+#[test]
+fn add_fill_and_stroke_copy_the_top_ones() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
+ run(&mut s, "stroke.set", json!({"weight": 4}));
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Fill, Stroke]
+ let n = node(&s, id);
+ assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["fill", "stroke", "fill", "stroke"]);
+ assert_eq!(fill_paint(&n, 2).color().unwrap().to_hex(), "#ff0000");
+ assert_eq!(stroke(&n, 3).width, 4.0);
+ assert!(!n.appearance.is_basic());
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(node(&s, id).appearance.items.len(), 3);
+}
+
+#[test]
+fn set_item_and_remove_item() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.setItem", json!({"index": 1, "opacity": 50, "blend": "screen", "weight": 3, "color": "#0000ff"}));
+ let n = node(&s, id);
+ let st = stroke(&n, 1);
+ assert_eq!((st.opacity, st.blend, st.width), (0.5, BlendMode::Screen, 3.0));
+ assert_eq!(st.paint.color().unwrap().to_hex(), "#0000ff");
- run(&mut s, "appearance.setItem", json!({"index": 0, "visible": false, "opacity": 0.25}));
++ run(&mut s, "appearance.setItem", json!({"index": 0, "visible": false, "opacity": 25}));
+ let n = node(&s, id);
+ assert!(!n.appearance.items[0].visible() && n.appearance.items[0].opacity() == 0.25);
+ assert!(s.execute("appearance.setItem", &json!({})).is_err());
+ run(&mut s, "appearance.removeItem", json!({"index": 0}));
+ let n = node(&s, id);
+ assert_eq!(n.appearance.items.len(), 1);
+ assert!(n.appearance.fill().is_none() && n.appearance.stroke().is_some());
+}
+
+#[test]
+fn clear_and_reduce_to_basic() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addStroke", json!({}));
+ run(&mut s, "appearance.setItem", json!({"index": 2, "visible": false, "color": "#00ff00"}));
- run(&mut s, "appearance.setItem", json!({"index": 1, "opacity": 0.5}));
++ run(&mut s, "appearance.setItem", json!({"index": 1, "opacity": 50}));
+ run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 1}));
+ run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "item": null}));
+ run(&mut s, "transparency.set", json!({"opacity": 40, "blend": "multiply"}));
+ // Reduce keeps the topmost visible fill and stroke, plain, and the object's transparency.
+ run(&mut s, "appearance.reduceToBasic", json!({}));
+ let n = node(&s, id);
+ assert!(n.appearance.is_basic(), "{:?}", n.appearance);
+ assert_eq!(stroke(&n, 1).paint, Paint::solid(Color::BLACK));
+ assert_eq!((n.opacity, n.blend), (0.4, BlendMode::Multiply));
+ // Clear leaves one None fill and stroke, and resets the object's Opacity row.
+ run(&mut s, "appearance.clear", json!({}));
+ let n = node(&s, id);
+ assert_eq!(n.appearance, vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0));
+ assert_eq!((n.opacity, n.blend), (1.0, BlendMode::Normal));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(node(&s, id).opacity, 0.4);
+}
+
+#[test]
+fn graphic_style_apply_replaces_the_stack() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ run(&mut s, "appearance.addFill", json!({}));
+ run(&mut s, "effect.apply", json!({"effect": "distort.roughen"}));
+ let name = run(&mut s, "graphicStyle.new", json!({"name": "Rough"}))["name"].clone();
+ let b = rect(&mut s, 250.0);
+ run(&mut s, "graphicStyle.apply", json!({ "name": name }));
+ assert_eq!(node(&s, b).appearance, node(&s, a).appearance);
+ assert!(s.execute("graphicStyle.apply", &json!({"name": "nope"})).is_err());
+}
+
+#[test]
+fn an_active_row_of_the_other_kind_leaves_edits_on_the_painted_leaves() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ let b = rect(&mut s, 250.0);
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
+ run(&mut s, "appearance.addFill", json!({}));
+ // The group's own fill row is active: stroke edits still go to the members' strokes.
+ run(&mut s, "appearance.setActiveItem", json!({"index": 0}));
+ run(&mut s, "stroke.set", json!({"weight": 5}));
+ run(&mut s, "paint.setStroke", json!({"color": "#00ff00"}));
+ assert_eq!(node(&s, g).appearance.items.len(), 1, "no stroke row added to the group");
+ for id in [a, b] {
+ assert_eq!(stroke(&node(&s, id), 1).width, 5.0);
+ assert_eq!(stroke(&node(&s, id), 1).paint.color().unwrap().to_hex(), "#00ff00");
+ }
+}
+
+#[test]
+fn the_active_row_follows_only_edits_of_its_object() {
+ let mut s = session();
+ let other = rect(&mut s, 250.0);
+ rect(&mut s, 100.0);
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ run(&mut s, "appearance.removeItem", json!({"index": 0, "ids": [other.0]}));
+ run(&mut s, "appearance.duplicateItem", json!({"index": 0, "ids": [other.0]}));
+ assert_eq!(s.appearance_item(), Some(1));
+}
+
+#[test]
+fn item_transparency_is_one_step_and_checks_the_blend_mode() {
+ let mut s = session();
+ let id = rect(&mut s, 100.0);
+ run(&mut s, "appearance.setActiveItem", json!({"index": 1}));
+ let steps = |s: &Session| s.doc().unwrap().history.undo.len();
+ let before = steps(&s);
+ run(&mut s, "transparency.set", json!({"knockout": true}));
+ assert_eq!(steps(&s), before + 1, "isolate/knockout alone do not touch the item");
+ assert!(node(&s, id).knockout);
+ assert!(s.execute("transparency.set", &json!({"blend": "nope"})).is_err());
+ assert_eq!(stroke(&node(&s, id), 1).blend, BlendMode::Normal);
+}
+
+#[test]
+fn clear_and_reduce_keep_a_groups_stack_empty() {
+ let mut s = session();
+ let a = rect(&mut s, 100.0);
+ let b = rect(&mut s, 250.0);
+ let members = node(&s, a).appearance;
+ run(&mut s, "select.set", json!({"ids": [a.0, b.0]}));
+ let g = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap());
+ run(&mut s, "appearance.reduceToBasic", json!({}));
+ assert!(node(&s, g).appearance.items.is_empty());
+ run(&mut s, "appearance.addStroke", json!({}));
+ run(&mut s, "appearance.reduceToBasic", json!({}));
+ assert_eq!(node(&s, g).appearance.items.iter().map(AppearanceItem::kind_name).collect::<Vec<_>>(), ["stroke"]);
+ run(&mut s, "transparency.set", json!({"opacity": 50}));
+ run(&mut s, "appearance.clear", json!({}));
+ let n = node(&s, g);
+ assert!(n.appearance.items.is_empty() && n.opacity == 1.0);
+ // The members keep their own appearance.
+ assert_eq!(node(&s, a).appearance, members);
+}
diff --cc crates/ui-egui/src/panels/appearance.rs
index 1d7f86c09,3be3192e1..05ccd07df
--- a/crates/ui-egui/src/panels/appearance.rs
+++ b/crates/ui-egui/src/panels/appearance.rs
@@@ -327,45 -270,26 +327,45 @@@ fn target_index(rows: &[(usize, Rect)]
})
}
-fn sub_row(_app: &mut VectorcraftApp, ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug + Copy, label: &str, visible: bool, depth: usize) {
- let (r, _) = row(ui, false);
- eye(ui, r, (id, "eye"), visible, false);
- text(ui, r.left_center() + vec2(EYE_W + 24.0 + depth as f32 * 12.0, 0.0), label, false);
+/// The Opacity row of the object (`item: None`) or, indented, of fill/stroke `item`. Clicking it
+/// opens a popup with the shared opacity and blend controls (`transparency.set` on that item).
+fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, item: Option<usize>, opacity: f32, blend: BlendMode) {
+ let (r, resp) = row(ui, false);
+ eye(ui, r, ("ap-op-eye", item), true, false);
+ let lx = r.left() + EYE_W + 24.0 + if item.is_some() { 12.0 } else { 0.0 };
+ let clicked = link(ui, pos2(lx, r.center().y), ("ap-op-link", item), "Opacity:") || resp.clicked();
+ text(ui, pos2(lx + 56.0, r.center().y), &opacity_text(opacity, blend), false);
+ egui::Popup::menu(&resp)
+ .open_memory(clicked.then_some(egui::SetOpenCommand::Toggle))
+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
- .show(|ui| match widgets::opacity_blend(ui, ("ap-op", item), opacity, blend, true) {
++ .show(|ui| match widgets::opacity_blend(ui, ("ap-op", item), Some(opacity), Some(blend), true) {
+ Some(TransparencyEdit::Blend(b)) => {
+ app.run("transparency.set", json!({"item": item, "blend": b.label()})).ok();
+ }
+ Some(TransparencyEdit::Opacity(o, phase)) => live_run(app, "Opacity", "transparency.set", json!({"item": item, "opacity": o}), phase),
+ None => {}
+ });
}
-fn effect_row(app: &mut VectorcraftApp, ui: &mut Ui, k: usize, e: &Effect, selected: bool) {
+/// An effect row: of the object (`item: None`) or, indented under it, of fill/stroke `item`.
+fn effect_row(app: &mut VectorcraftApp, ui: &mut Ui, item: Option<usize>, k: usize, e: &Effect, selected: bool) {
let t = Tokens::get(ui.ctx());
- let open: bool = pstate(ui.ctx(), &format!("ap-fx-open-{k}"));
+ let open_key = format!("ap-fx-open-{item:?}-{k}");
+ let open: bool = pstate(ui.ctx(), &open_key);
+ let this = item.map_or(Sel::Effect(k), |i| Sel::ItemEffect(i, k));
let (r, resp) = row(ui, selected);
- if eye(ui, r, ("ap-fx-eye", k), e.visible, true) {
- app.run("effect.setParams", json!({"index": k, "visible": !e.visible})).ok();
+ if eye(ui, r, ("ap-fx-eye", item, k), e.visible, true) {
+ app.run("effect.setParams", json!({"item": item, "index": k, "visible": !e.visible})).ok();
}
- if chevron(ui, r, ("ap-fx-chev", k), open) {
- set_pstate(ui.ctx(), &format!("ap-fx-open-{k}"), !open);
+ let indent = if item.is_some() { 12.0 } else { 0.0 };
+ let r = Rect::from_min_max(pos2(r.left() + indent, r.top()), r.max);
+ if chevron(ui, r, ("ap-fx-chev", item, k), open) {
+ set_pstate(ui.ctx(), &open_key, !open);
}
let lx = r.left() + EYE_W + 24.0;
- if link(ui, pos2(lx, r.center().y), ("ap-fx-link", k), &effect_label(&e.id)) {
- set_pstate(ui.ctx(), &format!("ap-fx-open-{k}"), !open);
- set_pstate(ui.ctx(), "ap-sel", Sel::Effect(k));
+ if link(ui, pos2(lx, r.center().y), ("ap-fx-link", item, k), &effect_label(&e.id)) {
+ set_pstate(ui.ctx(), &open_key, !open);
+ select_row(app, ui.ctx(), this);
}
icons::paint(ui, "dc-fx", Rect::from_center_size(r.right_center() - vec2(14.0, 0.0), vec2(16.0, 16.0)), t.icon);
if resp.clicked() {
diff --cc crates/ui-egui/src/panels/transparency.rs
index c0a75dca0,bdd70fb97..d54d94a1b
--- a/crates/ui-egui/src/panels/transparency.rs
+++ b/crates/ui-egui/src/panels/transparency.rs
@@@ -5,35 -5,74 +5,58 @@@
use egui::{Sense, Stroke, StrokeKind, Ui, vec2};
use serde_json::json;
use vectorcraft_color::{BlendMode, Paint};
+ use vectorcraft_doc::{Node, NodeId, OpacityMask};
+ use vectorcraft_engine::cmd::TransparencyInfo;
- use super::{current_paints, current_transparency, first_selected, live_run, pstate, selection_len, set_pstate};
-use super::{current_paints, live_run, pstate, selection_len, set_pstate};
++use super::{current_paints, current_transparency, live_run, pstate, selection_len, set_pstate};
use crate::theme::Tokens;
-use crate::widgets::{self, Live, menu_item};
+use crate::widgets::{self, TransparencyEdit, menu_item};
use crate::{VectorcraftApp, icons};
+ /// The panel's values ([`vectorcraft_engine::Session::transparency_info`]) and its first target
+ /// (the selection, or the object whose mask is being edited), recomputed only when the document
+ /// or the selection changes.
+ fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option<Node>) {
+ type Key = (u64, u64, usize, Option<NodeId>, Option<NodeId>);
+ let Some(st) = app.session.active() else { return Default::default() };
+ let sel = &st.selection.objects;
+ let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied());
+ let id = egui::Id::new("tr-state");
+ if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option<Node>))>(id))
+ && k == key
+ {
+ return v;
+ }
+ let info = app.session.transparency_info();
+ let first = info.ids.first().and_then(|id| st.doc.node(*id)).cloned();
+ let v = (info, first);
+ ctx.data_mut(|d| d.insert_temp(id, (key, v.clone())));
+ v
+ }
+
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
// While editing a mask the panel shows the masked object (the selection is its mask art).
let editing = app.session.active().and_then(|d| d.doc.mask_edit);
- let n = match editing {
- Some(me) => app.session.active().and_then(|d| d.doc.node(me.object).cloned()),
- None => first_selected(app),
- };
+ let (info, n) = state(app, ui.ctx());
let has = n.is_some();
- let (isolate, knockout) = n.as_ref().map_or((false, false), |n| (n.isolate, n.knockout));
- // Opacity and blend of the Appearance panel's active item, else of the object.
- let (op, blend) = match editing {
- None => current_transparency(app),
- Some(_) => n.as_ref().map(|n| (n.opacity, n.blend)),
- }
- .unwrap_or((1.0, BlendMode::Normal));
- // Values the targets don't share show blank; with no target, the defaults for new art.
- let (blend, op) = if has { (info.blend.map_or("", BlendMode::label), info.opacity) } else { (BlendMode::Normal.label(), Some(100.0)) };
+ let (isolate, knockout) = (info.isolate.unwrap_or(false), info.knockout.unwrap_or(false));
- ui.horizontal(|ui| {
- let labels: Vec<&str> = BlendMode::ALL.iter().map(|b| b.label()).collect();
- ui.add_enabled_ui(has, |ui| {
- if let Some(i) = widgets::dropdown(ui, "tr-blend", blend, &labels, 104.0) {
- app.run("transparency.set", json!({"blend": labels[i]})).ok();
- }
- });
- widgets::dim_label(ui, "Opacity:");
- ui.spacing_mut().item_spacing.x = 0.0;
- ui.add_enabled_ui(has, |ui| {
- if let Some(o) = widgets::mixed_field(ui, "tr-op", op, "%", 0, 50.0) {
- app.run("transparency.set", json!({"opacity": o.clamp(0.0, 100.0)})).ok();
- }
- });
- let (r, resp) = ui.allocate_exact_size(vec2(18.0, 26.0), if has { Sense::click() } else { Sense::hover() });
- ui.painter().rect_stroke(r, 2, Stroke::new(1.0, t.input_border), StrokeKind::Inside);
- icons::paint(ui, "chevron-right", r.shrink2(vec2(3.0, 7.0)), if has { t.icon } else { t.text_disabled });
- egui::Popup::menu(&resp).show(|ui| {
- let mut o = op.unwrap_or(100.0);
- let r = ui.add(egui::Slider::new(&mut o, 0.0..=100.0).show_value(false));
- let phase = if r.drag_stopped() || (r.changed() && !r.dragged()) {
- Live::Released
- } else if r.changed() {
- Live::Dragging
- } else {
- Live::Idle
- };
- live_run(app, "Opacity", "transparency.set", json!({"opacity": o.round()}), phase);
- });
- });
++ // Opacity and blend of the Appearance panel's active item (not while a mask is edited: the
++ // panel then shows the masked object), else of the targets, blank where they differ; with no
++ // target, the defaults for new art.
++ let item = editing.is_none().then(|| app.session.appearance_item()).flatten().and_then(|_| current_transparency(app));
++ let (op, blend) = match item {
++ Some((o, b)) => (Some(o), Some(b)),
++ None if has => (info.opacity.map(|o| (o / 100.0) as f32), info.blend),
++ None => (Some(1.0), Some(BlendMode::Normal)),
++ };
+ match widgets::opacity_blend(ui, "tr", op, blend, has) {
+ Some(TransparencyEdit::Blend(b)) => {
+ app.run("transparency.set", json!({"blend": b.label()})).ok();
+ }
+ Some(TransparencyEdit::Opacity(o, phase)) => live_run(app, "Opacity", "transparency.set", json!({ "opacity": o }), phase),
+ None => {}
+ }
widgets::divider(ui);
// Thumbnails and the opacity-mask controls.
let hide_thumbs: bool = pstate(ui.ctx(), "tr-hide-thumbs");
diff --cc crates/ui-egui/src/widgets.rs
index 881996f8b,e598e68c8..bf6cf86f9
--- a/crates/ui-egui/src/widgets.rs
+++ b/crates/ui-egui/src/widgets.rs
@@@ -269,125 -283,19 +283,126 @@@ pub fn fill_stroke_proxy(ui: &mut Ui, f
/// A compact dropdown. Returns the chosen index.
pub fn dropdown(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, current: &str, options: &[&str], width: f32) -> Option<usize> {
- let t = Tokens::get(ui.ctx());
- let mut chosen = None;
- let resp = egui::Frame::NONE.fill(t.input).stroke(Stroke::new(1.0, t.input_border)).corner_radius(CornerRadius::same(3)).show(ui, |ui| {
- egui::ComboBox::from_id_salt(ui.id().with(id)).selected_text(egui::RichText::new(current).size(12.0)).width(width - 4.0).show_ui(ui, |ui| {
- for (i, o) in options.iter().enumerate() {
- if ui.selectable_label(*o == current, *o).clicked() {
- chosen = Some(i);
- }
+ combo(ui, id, current, width, |ui| {
+ let mut chosen = None;
+ for (i, o) in options.iter().enumerate() {
+ if ui.selectable_label(*o == current, *o).clicked() {
+ chosen = Some(i);
}
+ }
+ chosen
+ })
+}
+
+/// The recessed combo box of [`dropdown`] showing `current`; `list` draws the options and returns
+/// the chosen one.
+fn combo<R>(
+ ui: &mut Ui,
+ id: impl std::hash::Hash + std::fmt::Debug,
+ current: &str,
+ width: f32,
+ list: impl FnOnce(&mut Ui) -> Option<R>,
+) -> Option<R> {
+ let t = Tokens::get(ui.ctx());
+ egui::Frame::NONE
+ .fill(t.input)
+ .stroke(Stroke::new(1.0, t.input_border))
+ .corner_radius(CornerRadius::same(3))
+ .show(ui, |ui| {
+ egui::ComboBox::from_id_salt(ui.id().with(id))
+ .selected_text(egui::RichText::new(current).size(12.0))
+ .width(width - 4.0)
+ .show_ui(ui, list)
+ .inner
+ .flatten()
})
+ .inner
+}
+
+/// Whether the blend-mode list draws a separator above `BlendMode::ALL[i]`: where a
+/// [`BlendMode::group`] starts.
+pub fn blend_separator_before(i: usize) -> bool {
+ i > 0 && i < BlendMode::ALL.len() && BlendMode::ALL[i].group() != BlendMode::ALL[i - 1].group()
+}
+
+/// The blend-mode dropdown, its groups separated (Normal | darken | lighten | contrast | inversion
- /// | component modes). Returns the chosen mode.
- pub fn blend_dropdown(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, current: BlendMode, width: f32) -> Option<BlendMode> {
- combo(ui, id, current.label(), width, |ui| {
++/// | component modes). `None` (objects that differ) shows blank. Returns the chosen mode.
++pub fn blend_dropdown(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, current: Option<BlendMode>, width: f32) -> Option<BlendMode> {
++ combo(ui, id, current.map_or("", BlendMode::label), width, |ui| {
+ let mut chosen = None;
+ for (i, m) in BlendMode::ALL.into_iter().enumerate() {
+ if blend_separator_before(i) {
+ ui.separator();
+ }
- if ui.selectable_label(m == current, m.label()).clicked() {
++ if ui.selectable_label(Some(m) == current, m.label()).clicked() {
+ chosen = Some(m);
+ }
+ }
+ chosen
+ })
+}
+
+/// The blend mode an effect parameter names (`"mode": "multiply"`), which editors show as a
+/// [`blend_param_dropdown`].
+pub fn blend_param(key: &str, value: &serde_json::Value) -> Option<BlendMode> {
+ value.as_str().filter(|_| key == "mode").and_then(BlendMode::parse)
+}
+
+/// [`blend_dropdown`] for a blend-mode parameter; returns the chosen mode's parameter value.
+pub fn blend_param_dropdown(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, current: BlendMode) -> Option<serde_json::Value> {
- blend_dropdown(ui, id, current, 120.0).map(|m| serde_json::Value::String(m.label().to_ascii_lowercase()))
++ blend_dropdown(ui, id, Some(current), 120.0).map(|m| serde_json::Value::String(m.label().to_ascii_lowercase()))
+}
+
+/// An edit made with [`opacity_blend`].
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum TransparencyEdit {
+ Blend(BlendMode),
+ /// Opacity in percent, with the slider's drag phase (`Released` for a typed value).
+ Opacity(f64, Live),
+}
+
+/// The transparency controls shared by the Transparency panel and the Appearance panel's Opacity
+/// popups: the grouped blend-mode dropdown, the opacity percent field and its slider popup.
++/// `opacity` (0..1) and `blend` are `None` where the objects differ (shown blank).
+pub fn opacity_blend(
+ ui: &mut Ui,
+ id: impl std::hash::Hash + std::fmt::Debug + Copy,
- opacity: f32,
- blend: BlendMode,
++ opacity: Option<f32>,
++ blend: Option<BlendMode>,
+ enabled: bool,
+) -> Option<TransparencyEdit> {
+ let t = Tokens::get(ui.ctx());
+ let mut edit = None;
+ ui.horizontal(|ui| {
+ ui.add_enabled_ui(enabled, |ui| {
+ if let Some(m) = blend_dropdown(ui, (id, "blend"), blend, 104.0) {
+ edit = Some(TransparencyEdit::Blend(m));
+ }
+ });
+ dim_label(ui, "Opacity:");
+ ui.spacing_mut().item_spacing.x = 0.0;
+ ui.add_enabled_ui(enabled, |ui| {
- if let Some(o) = plain_field(ui, (id, "opacity"), opacity as f64 * 100.0, "%", 0, 50.0) {
++ if let Some(o) = mixed_field(ui, (id, "opacity"), opacity.map(|o| o as f64 * 100.0), "%", 0, 50.0) {
+ edit = Some(TransparencyEdit::Opacity(o.clamp(0.0, 100.0), Live::Released));
+ }
+ });
+ let (r, resp) = ui.allocate_exact_size(vec2(18.0, 26.0), if enabled { Sense::click() } else { Sense::hover() });
+ ui.painter().rect_stroke(r, 2, Stroke::new(1.0, t.input_border), StrokeKind::Inside);
+ icons::paint(ui, "chevron-right", r.shrink2(vec2(3.0, 7.0)), if enabled { t.icon } else { t.text_disabled });
+ egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
- let mut o = opacity * 100.0;
++ let mut o = opacity.unwrap_or(1.0) * 100.0;
+ let r = ui.add(egui::Slider::new(&mut o, 0.0..=100.0).show_value(false));
+ let phase = if r.drag_stopped() || (r.changed() && !r.dragged()) {
+ Live::Released
+ } else if r.changed() {
+ Live::Dragging
+ } else {
+ return;
+ };
+ edit = Some(TransparencyEdit::Opacity(o.round() as f64, phase));
+ });
});
- let _ = resp;
- chosen
+ edit
}
/// The 3×3 reference point locator. Returns a new index when clicked.