diff --git a/ASSETS.md b/ASSETS.md
index 0e4e4aa4fe..029a978153 100644
--- a/ASSETS.md
+++ b/ASSETS.md
@@ -221,6 +221,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | |
| `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
diff --git a/ROADMAP.md b/ROADMAP.md
index 4d8f84de90..c4a6edc8fb 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -145,6 +145,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
+- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
diff --git a/assets/icons/dc-quick-pen.svg b/assets/icons/dc-quick-pen.svg
new file mode 100644
index 0000000000..e87a486046
--- /dev/null
+++ b/assets/icons/dc-quick-pen.svg
@@ -0,0 +1 @@
+
diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs
index 1728b7e323..11d2b0664d 100644
--- a/crates/doc/src/appearance/layers.rs
+++ b/crates/doc/src/appearance/layers.rs
@@ -195,12 +195,14 @@ impl StrokeLayer {
wheel: None,
}
}
+ /// The least weight an arrowhead is drawn at, in points ([`Self::arrow_weight`]).
+ pub const LEAST_ARROW_WEIGHT: f64 = 0.25;
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
- /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
+ /// [`Self::LEAST_ARROW_WEIGHT`]. A head of weight `hw` fits a box about `4·hw` long and wide (see
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
- (self.width * pct / 100.0).max(0.25)
+ (self.width * pct / 100.0).max(Self::LEAST_ARROW_WEIGHT)
}
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs
index 18b226c676..7a39d6cbb2 100644
--- a/crates/doc/src/appearance/stroke_style.rs
+++ b/crates/doc/src/appearance/stroke_style.rs
@@ -68,6 +68,10 @@ pub struct CustomArrowhead {
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
/// as the built-in heads are, and a unit is the head's weight.
pub path: PathData,
+ /// Where the stroke ends under the head, in head units back from the tip, when the head says
+ /// so ([`Self::with_stop`]); `None`: halfway along its length ([`Self::stop`]).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub stop: Option,
}
#[derive(Deserialize)]
@@ -75,11 +79,17 @@ struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
+ #[serde(default)]
+ stop: Option,
}
impl From for CustomArrowhead {
fn from(d: CustomArrowheadData) -> Self {
- CustomArrowhead::new(d.name, d.path)
+ let head = CustomArrowhead::new(d.name, d.path);
+ match d.stop {
+ Some(stop) => head.with_stop(stop),
+ None => head,
+ }
}
}
@@ -94,7 +104,17 @@ impl CustomArrowhead {
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
pub fn new(name: String, path: PathData) -> Self {
let path = if Self::fits(&path) { path } else { PathData::default() };
- CustomArrowhead { name, path }
+ CustomArrowhead { name, path, stop: None }
+ }
+ /// The head with the stroke ending `stop` head units back from its tip (an arrowhead an
+ /// Illustrator file defines draws its line to a point of its own). A stop that is not finite,
+ /// is negative or is farther than [`Self::MAX_UNITS`] is left out: the stroke then ends
+ /// halfway along the head.
+ /// A head whose outline was dropped ([`Self::new`]) draws nothing and keeps no stop.
+ pub fn with_stop(mut self, stop: f64) -> Self {
+ let fits = !self.path.subpaths.is_empty() && stop.is_finite() && (0.0..=Self::MAX_UNITS).contains(&stop);
+ self.stop = fits.then_some(stop);
+ self
}
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
/// finite points within [`Self::MAX_UNITS`] only.
@@ -116,10 +136,10 @@ impl CustomArrowhead {
pub fn half_width(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
}
- /// Where the stroke ends under the head, in head units back from the tip: halfway along the
- /// head's length.
+ /// Where the stroke ends under the head, in head units back from the tip: its own stop
+ /// ([`Self::with_stop`]), else halfway along the head's length.
pub fn stop(&self) -> f64 {
- self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
+ self.stop.unwrap_or_else(|| self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0))
}
}
diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs
index caad4f6edc..ab0ba559f0 100644
--- a/crates/doc/src/appearance/tests.rs
+++ b/crates/doc/src/appearance/tests.rs
@@ -383,6 +383,15 @@ fn custom_arrowheads_carry_their_art_and_measure_it() {
assert_eq!(head.half_width(), 2.0);
let Arrowhead::Custom(c) = &head else { panic!("custom") };
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
+ // A head with a stop of its own (an Illustrator file's arrowhead) keeps it, saved and read back.
+ let stopped = (**c).clone().with_stop(0.5);
+ assert_eq!(stopped.stop(), 0.5);
+ let back: CustomArrowhead = serde_json::from_value(serde_json::to_value(&stopped).unwrap()).unwrap();
+ assert_eq!(back, stopped);
+ assert!(!serde_json::to_string(&**c).unwrap().contains("stop"), "a head without one writes none");
+ for odd in [f64::NAN, -0.5, CustomArrowhead::MAX_UNITS + 1.0] {
+ assert_eq!((**c).clone().with_stop(odd).stop(), 1.5, "{odd} is left out");
+ }
// Saved with the stroke, art and all, beside the built-in heads' names.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
@@ -404,7 +413,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() {
let mut path = c.path.clone();
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
// A file can hold what `new` drops: reading it drops it too.
- let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
+ let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path, stop: None }).unwrap();
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
@@ -415,7 +424,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() {
let mut hollow = c.path.clone();
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
- let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
+ let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow, stop: None }).unwrap();
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
}
diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs
index d188bcafd6..1047e4d0dd 100644
--- a/crates/effects/src/stroke/arrow.rs
+++ b/crates/effects/src/stroke/arrow.rs
@@ -5,7 +5,8 @@
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are
-//! custom heads, whose stroke ends halfway along their length.
+//! custom heads, whose stroke ends at their own stop or else halfway along their length
+//! ([`vectorcraft_doc::CustomArrowhead::stop`]).
use std::borrow::Cow;
diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs
index 1b14e25391..6d2c7fd18f 100644
--- a/crates/engine/src/cmd/appearance.rs
+++ b/crates/engine/src/cmd/appearance.rs
@@ -278,6 +278,28 @@ impl ItemTarget {
}
}
+ /// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
+ /// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
+ /// ([`super::paint::live_paint_parts_skipped`]).
+ pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result> {
+ Ok(self.targets_and_skipped(s, p, fill)?.0)
+ }
+
+ /// [`ItemTarget::targets_for`], and whether it left out any object inside a Live Paint group: a
+ /// group with no part of the edited kind was still given or selected, so the edit does not go
+ /// to new art.
+ pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec, bool)> {
+ let mut ids = self.targets(s, p)?;
+ let mut skipped_any = false;
+ if self == ItemTarget::Top {
+ let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
+ let before = ids.len();
+ ids.retain(|id| !skipped.contains(id));
+ skipped_any = ids.len() != before;
+ }
+ Ok((ids, skipped_any))
+ }
+
/// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits
/// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted
/// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs
index 63ae0a3e4c..885fd35988 100644
--- a/crates/engine/src/cmd/draw2.rs
+++ b/crates/engine/src/cmd/draw2.rs
@@ -28,6 +28,7 @@ mod commands;
mod common;
mod cut;
mod freehand;
+mod quickpen;
mod smooth;
pub use commands::specs;
diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs
index 45171f62a1..e4846367b5 100644
--- a/crates/engine/src/cmd/draw2/commands.rs
+++ b/crates/engine/src/cmd/draw2/commands.rs
@@ -1,6 +1,7 @@
use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment};
use super::cut::{erase_region, erase_segments, knife, split};
use super::freehand::{blob, freehand};
+use super::quickpen::quick_pen;
use super::smooth::{join_scrub, smooth_region};
use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection};
@@ -33,6 +34,15 @@ pub fn specs() -> Vec {
has_doc,
curvature_edit
),
+ cmd!(
+ "path.quickPen",
+ "Quick Pen",
+ [],
+ None,
+ "{start?: [x, y] (a new path starts there), id? (or: draw on this path), subpath?: index (0), keep?: count (default: all its points; the points after the first `keep` are replaced), pieces?: [{x, y, action?: \"line\" (default)|\"continuousArc\"|\"sharpArc\", turn?: 1..359 degrees (180), flip?: bool}] (at most 10000), closed?: bool} draw a path of straight lines and circular arcs as the Quick Pen tool does, each piece from the path's last point to x, y: a line; a continuous arc, which leaves its start in the direction the path arrives in (with no direction, the first piece of a path, it is drawn as a sharp-corner arc; with its end straight ahead or straight behind, as a line); a sharp-corner arc, which turns through `turn` degrees and bulges to the left of the direction drawn (with flip, to the right). A piece that ends where the path does adds nothing. closed: a last piece that ends on the first point joins it, otherwise a straight segment closes the path. A new path takes the current paint (a black stroke when it has neither fill nor stroke); the path is selected, as one undo step → {id}. Without id, `start` must be given; with id, the subpath must be open and `start` is refused",
+ has_doc,
+ quick_pen
+ ),
cmd!(
"path.removeAnchor",
"Delete Anchor Point",
diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs
new file mode 100644
index 0000000000..84640bc876
--- /dev/null
+++ b/crates/engine/src/cmd/draw2/quickpen.rs
@@ -0,0 +1,96 @@
+//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs.
+
+use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke};
+
+use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound};
+use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or};
+
+const C: &str = "path.quickPen";
+/// The most pieces one request takes.
+const MAX_PIECES: usize = 10_000;
+
+/// The `pieces` param.
+fn pieces(p: &Value) -> Result> {
+ let list = match p.get("pieces") {
+ None | Some(Value::Null) => return Ok(vec![]),
+ Some(Value::Array(list)) if list.len() <= MAX_PIECES => list,
+ Some(_) => return Err(bad(C, "`pieces` must be a list of at most 10000 pieces")),
+ };
+ list.iter()
+ .map(|v| {
+ let to = point_entry(v, C)?;
+ if !within_input_bound(to) {
+ return Err(bad(C, "x and y must be finite"));
+ }
+ let stroke = match v.get("action") {
+ None | Some(Value::Null) => Stroke::Line,
+ Some(a) => a.as_str().and_then(Stroke::parse).ok_or_else(|| {
+ let key = "action";
+ bad(C, format!("`{key}` must be one of {}", Stroke::ALL.map(Stroke::name).join(", ")))
+ })?,
+ };
+ let turn = number_or(v, "turn", qp::DEFAULT_TURN, C)?;
+ if !(qp::MIN_TURN..=qp::MAX_TURN).contains(&turn) {
+ let (key, min, max) = ("turn", qp::MIN_TURN, qp::MAX_TURN);
+ return Err(bad(C, format!("{key} must be a number from {min} to {max}")));
+ }
+ let flip = switch_or(v, "flip", false, C)?;
+ Ok(Piece { to, stroke, turn, flip })
+ })
+ .collect()
+}
+
+pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result {
+ let pieces = pieces(p)?;
+ let closed = switch_or(p, "closed", false, C)?;
+ let start_given = p.get("start").is_some_and(|v| !v.is_null());
+ let either = "give either `start` for a new path or `id`, not both";
+ let Some(id) = object_param(p, "id", C)? else {
+ let start = match p.get("start") {
+ Some(v) if start_given => point_entry(v, C)?,
+ _ => return Err(bad(C, either)),
+ };
+ if !within_input_bound(start) {
+ return Err(bad(C, "x and y must be finite"));
+ }
+ if ["subpath", "keep"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) {
+ return Err(bad(C, "`subpath` and `keep` need `id`"));
+ }
+ let sp = qp::build(&SubPath::new(vec![vectorcraft_geom::Anchor::corner(start)], false), &pieces, closed);
+ let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
+ let ap = &mut look.appearance;
+ if ap.stroke_paint().is_none() && ap.fill_paint().is_none() {
+ ap.set_stroke(Paint::solid(Color::BLACK));
+ }
+ return add_look(s, "Quick Pen", path_kind(PathData::single(sp)), look, None);
+ };
+ if start_given {
+ return Err(bad(C, either));
+ }
+ let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
+ let d = &s.doc()?.doc;
+ if !d.is_editable(id) {
+ return Err(bad(C, "the path is locked or hidden"));
+ }
+ let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?;
+ let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?;
+ if sp.closed {
+ return Err(bad(C, "the subpath is closed"));
+ }
+ let n = sp.anchors.len();
+ let keep = usize_opt(p, "keep", C)?.unwrap_or(n);
+ if keep == 0 || keep > n {
+ let (key, min, max) = ("keep", 1, n);
+ return Err(bad(C, format!("{key} must be a number from {min} to {max}")));
+ }
+ let base = SubPath::new(sp.anchors.get_range(..keep).unwrap_or_default(), false);
+ let out = qp::build(&base, &pieces, closed);
+ let top = super::super::path::compound_or_self(d, id);
+ s.edit("Quick Pen", |d, sel| {
+ let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?;
+ *slot = out;
+ sel.set([top]);
+ Ok(())
+ })?;
+ Ok(json!({ "id": id.0 }))
+}
diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs
index 71a5e36ccf..b238dd865a 100644
--- a/crates/engine/src/cmd/freeform.rs
+++ b/crates/engine/src/cmd/freeform.rs
@@ -19,7 +19,7 @@ pub fn specs() -> Vec {
"Add Freeform Point",
[],
None,
- "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
+ "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}",
has_doc,
add_point
),
@@ -28,7 +28,7 @@ pub fn specs() -> Vec {
"Edit Freeform Point",
[],
None,
- "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
+ "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
has_doc,
set_point
),
@@ -37,7 +37,7 @@ pub fn specs() -> Vec {
"Delete Freeform Point",
[],
None,
- "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
+ "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
has_doc,
delete_point
),
@@ -46,7 +46,7 @@ pub fn specs() -> Vec {
"Add Freeform Line",
[],
None,
- "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
+ "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
has_doc,
add_line
),
@@ -55,7 +55,7 @@ pub fn specs() -> Vec {
"Split Freeform Line",
[],
None,
- "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
+ "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
has_doc,
split_line
),
@@ -182,8 +182,9 @@ fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
let item = item_target(s, p, cmd)?;
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
let item = item.of_kind(s, !stroke);
- // The art of a graph design in a series keeps the design's gradient.
- let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets(s, p)?, cmd)?;
+ // The art of a graph design in a series keeps the design's gradient; a Live Paint group's fill is on its faces and its
+ // stroke on its edges.
+ let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets_for(s, p, !stroke)?, cmd)?;
if ids.is_empty() {
return Err(bad(cmd, "select an object with a freeform gradient"));
}
diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs
index df75e2f8dd..2a90441934 100644
--- a/crates/engine/src/cmd/gradient.rs
+++ b/crates/engine/src/cmd/gradient.rs
@@ -24,7 +24,7 @@ pub fn specs() -> Vec {
"Gradient",
["Window", "Gradient"],
None,
- "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected or the Live Paint Bucket's gradient: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)",
+ "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected or the Live Paint Bucket's gradient: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)",
has_doc,
edit_gradient
),
@@ -33,7 +33,7 @@ pub fn specs() -> Vec {
"Gradient Vector",
[],
None,
- "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label",
+ "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label; without item, a Live Paint group's faces take a fill edit and its edges take a stroke edit",
has_doc,
set_gradient_geom
),
@@ -92,6 +92,9 @@ fn select_stop(s: &mut Session, p: &Value) -> Result {
pub(crate) struct StopOwner {
doc: Option,
object: Option,
+ /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
+ /// first in the selection shows the next object's.
+ source: Option,
part: bool,
fill: bool,
item: Option,
@@ -104,6 +107,7 @@ impl StopOwner {
Self {
doc: s.active,
object: st.and_then(|d| d.selection.objects.first().copied()),
+ source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
fill: s.fill_active,
item: s.appearance_item(),
@@ -549,10 +553,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result {
check_switches(p, &["reverse", "dither"], C)?;
check_numbers(p, &["angle"], C)?;
let item = item.of_kind(s, !stroke);
- let ids = item.targets(s, p)?;
- // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
- // not one for new art.
- let selected = !ids.is_empty();
+ let (ids, skipped) = item.targets_and_skipped(s, p, !stroke)?;
+ // Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts
+ // of the other kind left out above: the stroke mode is then not one for new art.
+ let selected = !ids.is_empty() || skipped;
// The default gradient for new art (and the bucket's) is fitted to each object, so it has no aspect of its own.
if !selected && p.get("aspect").is_some() {
return Err(bad(C, "`aspect` needs objects to place the gradient on: give ids or select objects"));
@@ -792,7 +796,10 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result {
let item = item.of_kind(s, !stroke);
let targets = match item {
ItemTarget::Top => {
- leaf_targets(s, &super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)?
+ let roots = super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?;
+ // A Live Paint group's fill gradient is on its faces and its stroke gradient on its edges.
+ let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
+ leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
}
_ => item.targets(s, p)?,
};
diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs
index 23b74f2fa6..d9d0905140 100644
--- a/crates/engine/src/cmd/newart.rs
+++ b/crates/engine/src/cmd/newart.rs
@@ -228,9 +228,11 @@ impl Session {
if !self.prefs.new_art_basic {
return;
}
- let has_paint = self
- .proxy_source(false)
- .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some());
+ // A Live Paint group with edges and no faces shows only a stroke.
+ let has_paint = [false, true].into_iter().any(|stroke| {
+ self.proxy_source(stroke)
+ .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some())
+ });
if !has_paint {
return;
}
diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs
index 6115e18b81..071c5f9862 100644
--- a/crates/engine/src/cmd/paint.rs
+++ b/crates/engine/src/cmd/paint.rs
@@ -4,7 +4,9 @@ use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
-use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
+use vectorcraft_doc::appearance::{FillLayer, StrokeLayer};
+use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
+use vectorcraft_tools::builder::{edges, faces, is_live_paint};
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
@@ -25,7 +27,7 @@ pub fn specs() -> Vec {
"Fill",
[],
None,
- "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
+ "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -34,7 +36,7 @@ pub fn specs() -> Vec {
"Stroke",
[],
None,
- "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
+ "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
has_doc,
|s, p| { set_paint(s, p, false) }
),
@@ -43,7 +45,7 @@ pub fn specs() -> Vec {
"Swap Fill and Stroke",
[],
Some("Shift+X"),
- "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
+ "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
has_doc,
swap
),
@@ -52,7 +54,7 @@ pub fn specs() -> Vec {
"Default Fill and Stroke",
[],
Some("D"),
- "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
+ "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
has_doc,
default_paint
),
@@ -100,7 +102,7 @@ pub fn proxy_specs() -> Vec {
"Invert",
[],
None,
- "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
+ "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -109,7 +111,7 @@ pub fn proxy_specs() -> Vec {
"Complement",
[],
None,
- "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}",
+ "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
@@ -158,7 +160,7 @@ pub fn proxy_specs() -> Vec {
"Fill and Stroke",
[],
None,
- "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
+ "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
always,
proxies
),
@@ -182,10 +184,11 @@ impl Session {
/// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the
/// first selected object's own stack) for the proxy of its kind, else the first selected
- /// object's (a group's first painted object's; type: its first run's), else the defaults for
- /// new art. When the object whose fill the proxy shows is a gradient mesh with points picked
- /// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid
- /// fill color changes.
+ /// object's (a group's first painted object's; a Live Paint group's first face's fill and first
+ /// edge's stroke, or the next selected object's when it has no face or edge; type: its first
+ /// run's), else the defaults for new art. When the object whose fill the proxy shows is a
+ /// gradient mesh with points picked ([`Session::fill_mesh_points`]), the fill is its first
+ /// picked point's color, which a solid fill color changes.
pub fn proxy_paints(&self) -> (Paint, Paint) {
let points = self.fill_mesh_points();
let show = |stroke: bool| match self.proxy_source(stroke) {
@@ -215,9 +218,20 @@ impl Session {
if first.appearance.item_of_kind(item, !stroke).is_some() {
return Some((Cow::Borrowed(first), item));
}
- let mut nodes = vec![];
- painted(first, true, &mut nodes);
- nodes.first().map(|n| (Cow::Borrowed(*n), None))
+ // A Live Paint group without faces (or edges) shows the next selected object's paint; any other
+ // object without a painted object shows the defaults for new art.
+ for id in st.selection.subjects() {
+ let Some(n) = st.doc.node(*id) else { continue };
+ let mut nodes = vec![];
+ painted(n, true, stroke, &mut nodes);
+ if let Some(n) = nodes.first() {
+ return Some((Cow::Borrowed(*n), None));
+ }
+ if !is_live_paint(n) {
+ return None;
+ }
+ }
+ None
}
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
@@ -258,21 +272,35 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
}
}
+/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
+pub(crate) fn live_paint_parts(n: &Node) -> Vec {
+ if !is_live_paint(n) {
+ return vec![];
+ }
+ faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
+}
+
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
-/// other containers inside them), a compound path for its parts.
-pub(crate) fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
+/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
+/// faces in the fill proxy (`stroke` false) and for its edges in the stroke proxy, the parts a fill
+/// or a stroke given to it changes ([`live_paint_parts_skipped`]).
+pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'a Node>) {
// A ruler guide has no paints.
if n.is_ruler_guide() {
return;
}
+ if is_live_paint(n) {
+ out.extend(if stroke { edges(n) } else { faces(n) }.into_iter().map(|part| &**part));
+ return;
+ }
let expand = match n.kind {
NodeKind::Group { .. } | NodeKind::Layer { .. } => true,
NodeKind::Compound { .. } => false,
_ => !top && n.is_container(),
};
if expand {
- n.children().into_iter().flatten().for_each(|c| painted(c, false, out));
+ n.children().into_iter().flatten().for_each(|c| painted(c, false, stroke, out));
} else {
out.push(n);
}
@@ -301,18 +329,31 @@ impl DocState {
}
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
- let (mut selected, mut nodes) = (vec![], vec![]);
+ let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
+ // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
+ let mut covered = std::collections::HashSet::new();
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
#[cfg(test)]
tests::note_gathered();
selected.push(n);
- painted(n, true, &mut nodes);
+ if covered.contains(&n.id) {
+ continue;
+ }
+ covered.extend(live_paint_parts(n));
+ painted(n, true, false, &mut fills);
+ painted(n, true, true, &mut strokes);
}
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
- let set = if item.is_some() { &selected } else { &nodes };
+ let set = if item.is_some() {
+ &selected
+ } else if stroke {
+ &strokes
+ } else {
+ &fills
+ };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
@@ -568,7 +609,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
}
// Resolve the requested targets before mutating defaults or the active proxy.
let item = item_target(s, p, cmd)?.of_kind(s, fill);
- let selected = item.targets(s, p)?;
+ let selected = item.targets_for(s, p, fill)?;
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
let of = super::appearance::reference_of(s, p, item, cmd)?;
let paint = if span {
@@ -717,6 +758,68 @@ pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result Vec<(NodeId, Vec, Vec)> {
+ fn find<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
+ let group = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. });
+ if is_live_paint(n) {
+ out.push(n);
+ } else if (group || !top) && !n.is_compound_shape() && !matches!(n.kind, NodeKind::Compound { .. }) {
+ n.children().into_iter().flatten().for_each(|c| find(c, false, out));
+ }
+ }
+ let mut found = vec![];
+ for n in roots.iter().filter_map(|r| d.node(*r)) {
+ find(n, true, &mut found);
+ }
+ let mut seen = std::collections::HashSet::new();
+ found.retain(|g| seen.insert(g.id));
+ // A given or selected compound shape or compound path (or one inside a given or selected object) paints its members,
+ // also when one of them is given as well. A Live Paint group given inside one that is not given stays a Live Paint group.
+ let owns = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_compound_shape() || matches!(n.kind, NodeKind::Compound { .. }));
+ let given: std::collections::HashSet = roots.iter().copied().collect();
+ found.retain(|g| {
+ !d.ancestry(g.id).is_some_and(|up| {
+ let outer = up.iter().position(|a| given.contains(a)).unwrap_or(up.len());
+ up.iter().skip(outer).any(|a| *a != g.id && owns(a))
+ })
+ });
+ let kept: std::collections::HashSet = super::appearance::drop_design_art(d, found.iter().map(|g| g.id).collect()).into_iter().collect();
+ let ids = |parts: Vec<&std::sync::Arc>| parts.into_iter().map(|part| part.id).collect();
+ found.into_iter().filter(|g| kept.contains(&g.id)).map(|g| (g.id, ids(faces(g)), ids(edges(g)))).collect()
+}
+
+/// Every object inside the Live Paint groups `groups` (faces, edges and the hidden source paths).
+fn inside_live_paint(d: &Document, groups: &[(NodeId, Vec, Vec)]) -> std::collections::HashSet {
+ let mut out = std::collections::HashSet::new();
+ for n in groups.iter().filter_map(|(g, _, _)| d.node(*g)) {
+ n.walk(&mut |c| {
+ if c.id != n.id {
+ out.insert(c.id);
+ }
+ });
+ }
+ out
+}
+
+/// The objects inside the Live Paint groups in `roots` (or inside them) that a fill (`fill`) or a
+/// stroke given to the whole group leaves as they are: a fill paints the group's faces only, and a
+/// stroke its edges only. Their edges (faces) and hidden source paths are left out.
+pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: bool) -> std::collections::HashSet {
+ let groups = live_paint_groups(d, roots);
+ let mut out = inside_live_paint(d, &groups);
+ for (_, faces, edges) in &groups {
+ for id in if fill { faces } else { edges } {
+ out.remove(id);
+ }
+ }
+ out
+}
+
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1021,20 +1124,62 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option
}
}
+/// The paint every one of `parts` has on top as its fill (`fill`) or stroke, swatch link included
+/// and gradient placement left out ([`unplaced`]: each part fits it to its own bounds), or None
+/// when they differ or there are none. A freeform gradient's points and their colors belong to the
+/// part they sit on, so a freeform gradient on any part counts as a paint the parts do not share.
+fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option {
+ let mut paints = parts.iter().filter_map(|id| d.node(*id)).map(|n| if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() });
+ let first = paints.next()?;
+ let freeform =
+ |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some());
+ if freeform(&first) {
+ return None;
+ }
+ let first = unplaced(&first);
+ paints.all(|p| !freeform(&p) && unplaced(&p) == first).then_some(first)
+}
+
fn swap(s: &mut Session, p: &Value) -> Result {
let bucket = bucket_color_params(s, p, "paint.swap")?;
let p = bucket.as_ref().unwrap_or(p);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
- let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
+ // A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share.
+ let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?);
+ let inside = inside_live_paint(&s.doc()?.doc, &groups);
+ let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect());
// Only design art was given or selected: nothing changes, the defaults included.
- if given && ids.is_empty() {
+ if given && ids.is_empty() && groups.is_empty() {
return ok();
}
- if !ids.is_empty() {
+ if !ids.is_empty() || !groups.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
+ // A group whose faces' fills (or edges' strokes) differ or are freeform gradients, or that has no face or no edge,
+ // keeps its paint.
+ let swaps: Vec<(&[NodeId], &[NodeId], Paint, Paint)> = groups
+ .iter()
+ .filter_map(|(_, faces, edges)| {
+ Some((faces.as_slice(), edges.as_slice(), shared_paint(&before, faces, true)?, shared_paint(&before, edges, false)?))
+ })
+ .collect();
+ let parts: Vec = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect();
super::overprint::edit_counted(s, "Swap Fill and Stroke", |d| {
+ for (faces, edges, fill, stroke) in &swaps {
+ for id in *faces {
+ if let Some(n) = d.node_mut(*id) {
+ n.appearance.set_fill(stroke.clone());
+ }
+ }
+ for id in *edges {
+ if let Some(n) = d.node_mut(*id) {
+ restore_unpainted_stroke(&mut n.appearance, None, fill);
+ n.appearance.set_stroke(fill.clone());
+ }
+ }
+ }
+ let parts_changed = super::appearance::count_changed(d, &before, &parts);
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
if let NodeKind::Text(t) = &mut n.kind {
@@ -1054,7 +1199,7 @@ fn swap(s: &mut Session, p: &Value) -> Result {
// The swap writes the paint of the topmost fill and stroke, not their opacity.
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false);
let labels = super::graph::capture_label_changes(&before, d, &ids, false, None);
- Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
+ Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels))
})?;
}
if s.paint.stroke.is_none() && !s.paint.fill.is_none() && s.paint.stroke_width == 0.0 {
@@ -1064,22 +1209,44 @@ fn swap(s: &mut Session, p: &Value) -> Result {
ok()
}
+/// The weight of the stroke [`paint.default`](default_paint) gives the edges of a whole Live Paint group.
+const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5;
+
fn default_paint(s: &mut Session, p: &Value) -> Result {
let bucket = bucket_color_params(s, p, "paint.default")?;
let p = bucket.as_ref().unwrap_or(p);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
- let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
+ // A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke.
+ let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?);
+ let inside = inside_live_paint(&s.doc()?.doc, &groups);
+ let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect());
// Only design art was given or selected: nothing changes, the defaults included.
- if given && ids.is_empty() {
+ if given && ids.is_empty() && groups.is_empty() {
return ok();
}
- if !ids.is_empty() {
+ if !ids.is_empty() || !groups.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
let style = super::newart::redefined_default_style(&before).cloned();
+ let parts: Vec = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect();
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
+ for (_, faces, edges) in &groups {
+ let face = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::None))], ..Appearance::default() };
+ let edge = Appearance {
+ items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), LIVE_PAINT_DEFAULT_WEIGHT))],
+ ..Appearance::default()
+ };
+ for (ids, look) in [(faces, &face), (edges, &edge)] {
+ for id in ids {
+ if let Some(n) = d.node_mut(*id) {
+ n.appearance = look.clone().into();
+ }
+ }
+ }
+ }
+ let parts_changed = super::appearance::count_changed(d, &before, &parts);
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
match &mut n.kind {
@@ -1106,10 +1273,20 @@ fn default_paint(s: &mut Session, p: &Value) -> Result {
st.stroke = Paint::None;
});
let lines = super::graph::capture_line_fill_stroke_rows(d, &ids);
- Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines))
+ Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels || lines))
})?;
}
- super::newart::reset(s);
+ if ids.is_empty() && !groups.is_empty() {
+ // With only whole Live Paint groups given or selected, new art takes what their parts took, and nothing else.
+ s.paint = vectorcraft_tools::PaintDefaults {
+ fill: Paint::None,
+ stroke: Paint::solid(Color::BLACK),
+ stroke_width: LIVE_PAINT_DEFAULT_WEIGHT,
+ ..Default::default()
+ };
+ } else {
+ super::newart::reset(s);
+ }
ok()
}
@@ -1215,11 +1392,20 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
if roots.is_empty() {
return Ok(json!({ "changed": 0 }));
}
- let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
- // The fill or stroke the proxy shows of each group among the roots, before the edit.
+ // A Live Paint group's fill is its faces' fills and its stroke its edges' strokes, also with `target: "contents"`;
+ // like any group, it recolors rows of its own as well.
+ let parts_skipped = live_paint_parts_skipped(d, &ids, !stroke);
+ let roots: Vec = roots.into_iter().filter(|id| !parts_skipped.contains(id)).collect();
+ if roots.is_empty() {
+ return Ok(json!({ "changed": 0 }));
+ }
+ let mut art: std::collections::HashSet = super::appearance::design_art_in(d, &roots).into_iter().collect();
+ art.extend(parts_skipped.iter().copied());
+ // The fill or stroke the proxy shows of each group among the roots, before the edit (a Live Paint group shows
+ // its faces' or edges').
let own = |d: &Document, id: NodeId| {
d.node(id)
- .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
+ .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !is_live_paint(n))
.and_then(|n| n.proxy_paint_only(stroke, None))
.cloned()
};
@@ -1237,7 +1423,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
shown_at = Some((*id, None));
break;
}
- if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
+ let leaves = leaf_targets(s, &[*id])?.into_iter().filter(|leaf| !parts_skipped.contains(leaf)).collect();
+ if let Some(leaf) = super::appearance::drop_design_art(d, leaves).first() {
shown_at = Some((*leaf, None));
break;
}
diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs
index 3da5d73d9e..77e061e993 100644
--- a/crates/engine/src/cmd/paint/tests.rs
+++ b/crates/engine/src/cmd/paint/tests.rs
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
-use super::{painted, picked_colors, proxy_paint, same_in_proxy};
+use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
@@ -38,17 +38,28 @@ fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -
return (false, false);
}
let ids: HashSet = st.selection.objects.iter().copied().collect();
- let (mut selected, mut nodes) = (vec![], vec![]);
+ let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
+ let mut covered = HashSet::new();
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
- painted(n, true, &mut nodes);
+ if !covered.contains(&n.id) {
+ covered.extend(live_paint_parts(n));
+ painted(n, true, false, &mut fills);
+ painted(n, true, true, &mut strokes);
+ }
}
});
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
- let set = if item.is_some() { &selected } else { &nodes };
+ let set = if item.is_some() {
+ &selected
+ } else if stroke {
+ &strokes
+ } else {
+ &fills
+ };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs
index 7925c841d4..e09e362550 100644
--- a/crates/engine/src/cmd/plugin_call/reviewed.rs
+++ b/crates/engine/src/cmd/plugin_call/reviewed.rs
@@ -463,6 +463,7 @@ pub(super) const ALLOWED: &[&str] = &[
"path.mirrorCut",
"path.moveAnchor",
"path.moveAnchors",
+ "path.quickPen",
"path.rectCut",
"path.removeAnchor",
"path.removeAnchors",
diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs
index f43a63853e..f1e47b889a 100644
--- a/crates/engine/src/cmd/stroke.rs
+++ b/crates/engine/src/cmd/stroke.rs
@@ -8,9 +8,10 @@ use vectorcraft_doc::{
Unit, WidthProfile,
};
use vectorcraft_geom::PathData;
+use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
-use super::paint::painted;
+use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -22,7 +23,7 @@ pub fn specs() -> Vec {
"Stroke Options",
["Window", "Stroke"],
None,
- "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
+ "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
@@ -31,7 +32,7 @@ pub fn specs() -> Vec {
"Stroke Weight Up",
[],
Some("Cmd+Alt+."),
- "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
+ "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
has_doc,
|s, p| stroke_step(s, p, true)
),
@@ -49,7 +50,7 @@ pub fn specs() -> Vec {
"Stroke Options",
[],
None,
- "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none)",
+ "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
has_doc,
stroke_advanced
),
@@ -210,20 +211,25 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool {
/// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of
/// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other
-/// targets reach their painted leaves, as before.
+/// targets reach their painted leaves, as before (a Live Paint group's edges, not its faces).
fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result> {
let picked = super::targets(s, p)?;
let d = &s.doc()?.doc;
+ // A Live Paint group's stroke is its edges' strokes, also when it has a stroke row of its own.
let own = |id: &vectorcraft_doc::NodeId| {
d.node(*id).is_some_and(|n| {
- matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
+ matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
+ && !n.is_compound_shape()
+ && n.appearance.stroke().is_some()
+ && !is_live_paint(n)
})
};
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
+ let faces = live_paint_parts_skipped(d, &rest, false);
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
let mut seen: std::collections::HashSet = out.iter().copied().collect();
for id in super::leaf_targets(s, &rest)? {
- if seen.insert(id) {
+ if !faces.contains(&id) && seen.insert(id) {
out.push(id);
}
}
@@ -246,11 +252,13 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result {
} else {
item.targets(s, p)?
};
- let new_art = bucket || no_targets(&ids, p);
- let given = !ids.is_empty();
+ // A Live Paint group without edges was still selected or given: the options do not go to new art.
+ let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
+ let new_art = bucket || (no_targets(&ids, p) && !live_paint);
+ let given = !ids.is_empty() || live_paint;
// The art of a graph design in a series keeps the design's stroke.
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
- // With only design art, the weight for new art stays as it is too.
+ // With only design art, or only Live Paint groups without edges, the weight for new art stays as it is too.
let only_design_art = given && ids.is_empty();
if item == ItemTarget::Top {
// Images and symbol instances take no stroke from the panel.
@@ -388,8 +396,8 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result {
let bucket = bucket_p.is_some();
let p = bucket_p.as_ref().unwrap_or(p);
let item = item_target(s, p, c)?.of_kind(s, false);
- let ids = if bucket { vec![] } else { item.targets(s, p)? };
- if bucket || no_targets(&ids, p) {
+ let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? };
+ if bucket || (no_targets(&ids, p) && !skipped) {
let w = step_weight(s.paint.stroke_width, unit, up);
s.paint.stroke_width = w;
if let Some(st) = s.new_art_stroke_mut() {
@@ -428,8 +436,9 @@ impl Session {
/// The stroke the Stroke panel, the Control bar and the Properties panel show, picked as the
/// Stroke proxy picks its paint: the Appearance panel's active item when it is a stroke, else
- /// the first selected object's (a group's first painted object's) top stroke, type's first
- /// run's character stroke; with an object of a dynamic symbol instance selected
+ /// the first selected object's (a group's first painted object's, a Live Paint group's first
+ /// edge's, or the next selected object's when a Live Paint group has no edge) top stroke, type's
+ /// first run's character stroke; with an object of a dynamic symbol instance selected
/// ([`DocState::selected_symbol_part`]), that object's as the instance draws it; with nothing
/// selected, the next object drawn's ([`Session::new_art_stroke`]), and so while the Live Paint
/// Bucket is the active tool (the stroke it paints with). None without a document or the
@@ -447,9 +456,20 @@ impl Session {
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
return first.appearance.stroke_at(Some(i)).cloned();
}
- let mut nodes = vec![];
- painted(first, true, &mut nodes);
- node_stroke(nodes.first()?)
+ // A Live Paint group without edges shows the next selected object's stroke; any other object
+ // without a painted object shows none.
+ for id in &st.selection.objects {
+ let Some(n) = st.doc.node(*id) else { continue };
+ let mut nodes = vec![];
+ painted(n, true, true, &mut nodes);
+ if let Some(n) = nodes.first() {
+ return node_stroke(n);
+ }
+ if !is_live_paint(n) {
+ return None;
+ }
+ }
+ None
}
/// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush
@@ -508,12 +528,13 @@ impl DocState {
let part = self.selected_symbol_part();
let mut nodes = vec![];
if let Some(part) = &part {
- painted(part, true, &mut nodes);
+ painted(part, true, true, &mut nodes);
} else {
- for id in &self.selection.objects {
- if let Some(n) = self.doc.node(*id) {
- painted(n, true, &mut nodes);
- }
+ let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
+ // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
+ let covered: std::collections::HashSet = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
+ for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
+ painted(n, true, true, &mut nodes);
}
}
let mut strokes = vec![];
@@ -594,8 +615,8 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result {
let bucket = bucket_p.is_some();
let p = bucket_p.as_ref().unwrap_or(p);
let item = item_target(s, p, C)?.of_kind(s, false);
- let ids = if bucket { vec![] } else { item.targets(s, p)? };
- let new_art = bucket || no_targets(&ids, p);
+ let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? };
+ let new_art = bucket || (no_targets(&ids, p) && !skipped);
// The art of a graph design in a series keeps the design's stroke.
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
let arrows_and_profile = |st: &mut StrokeLayer| {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index d023d66088..815a33eeae 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -155,6 +155,7 @@ mod printps;
mod printtiling;
mod proxyitems;
mod puppetwarp;
+mod quickpen;
mod rasterfilters;
mod rastersettings;
mod recolor;
diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs
index 294d14d917..6c3cd26d8d 100644
--- a/crates/engine/src/tests/build.rs
+++ b/crates/engine/src/tests/build.rs
@@ -3836,6 +3836,419 @@ fn live_paint_fill_skips_hidden_faces() {
assert!(!node(&s, hidden).visible);
}
+/// The appearance of each face and each edge of Live Paint group `g`.
+fn part_looks(s: &Session, g: NodeId) -> (Vec, Vec) {
+ use vectorcraft_tools::builder::{edges, faces};
+ let n = node(s, g);
+ let looks = |parts: Vec<&Arc>| parts.iter().map(|p| (*p.appearance).clone()).collect();
+ (looks(faces(&n)), looks(edges(&n)))
+}
+
+/// The appearance of each hidden source path of Live Paint group `g`.
+fn sources_looks(s: &Session, g: NodeId) -> Vec {
+ let n = node(s, g);
+ let src = vectorcraft_tools::builder::sources(&n).unwrap();
+ src.children().unwrap().iter().map(|c| (*c.appearance).clone()).collect()
+}
+
+/// With a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group
+/// paints its faces and leaves its edges as they are, and a stroke paints its edges and leaves its
+/// faces as they are. The Fill and Stroke proxies show the faces' fill and the edges' stroke.
+#[test]
+fn live_paint_group_fill_goes_to_faces_and_stroke_to_edges() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let (faces0, edges0) = part_looks(&s, g);
+ let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
+ let sources0 = sources_looks(&s, g);
+ assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap()["objects"], faces0.len());
+ let (faces1, edges1) = part_looks(&s, g);
+ assert!(faces1.iter().all(|f| f.fill_paint() == magenta));
+ assert_eq!(edges1, edges0, "edges take no fill");
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["fillMixed"], false);
+ assert_eq!(p["fill"], serde_json::to_value(&magenta).unwrap());
+ let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
+ assert_eq!(s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap()["objects"], edges0.len());
+ assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their paint");
+ let (faces2, edges2) = part_looks(&s, g);
+ assert!(edges2.iter().all(|e| e.stroke_paint() == blue));
+ assert_eq!(faces2, faces1, "faces take no stroke");
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["strokeMixed"], false);
+ assert_eq!(p["stroke"], serde_json::to_value(&blue).unwrap());
+ // The same with the group given by id, and inside a selected group.
+ s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#00ff00"})).unwrap();
+ let (faces3, edges3) = part_looks(&s, g);
+ assert_eq!(edges3, edges2, "edges take no fill given by id");
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ assert!(faces3.iter().all(|f| f.fill_paint() == green));
+ s.execute("object.group", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
+ let (faces4, edges4) = part_looks(&s, g);
+ assert_eq!(faces4, faces3, "faces of a grouped Live Paint group take no stroke");
+ assert!(edges4.iter().all(|e| e.stroke_paint() == Paint::solid(Color::from_hex("#ff0000").unwrap())));
+ // The bucket then paints one face, and nothing in the group draws a fill over it.
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#ffff00"})).unwrap();
+ let face = NodeId(r["face"].as_u64().unwrap());
+ assert_eq!(node(&s, face).appearance.fill_paint(), Paint::solid(Color::from_hex("#ffff00").unwrap()));
+ assert!(part_looks(&s, g).1.iter().all(|e| e.fill_paint().is_none()));
+}
+
+/// Swap Fill and Stroke on a whole selected Live Paint group gives its faces the stroke its edges
+/// share and its edges the fill its faces share; with faces of different fills, or without faces,
+/// it leaves the group as it is.
+#[test]
+fn live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ // The faces are red and blue: nothing on the group changes, in no undo step.
+ let (faces0, edges0) = part_looks(&s, g);
+ let depth = history_state(&s).0;
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), (faces0, edges0));
+ assert_eq!(history_state(&s).0, depth);
+ // One fill on every face: the faces take the edges' black, the edges the faces' red, at their weight.
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.execute("stroke.set", &json!({"weight": 2})).unwrap();
+ s.execute("paint.swap", &json!({})).unwrap();
+ let (faces1, edges1) = part_looks(&s, g);
+ assert!(faces1.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK)));
+ assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0)) && e.stroke_width() == 2.0));
+ assert!(edges1.iter().all(|e| e.fill_paint().is_none()), "edges take no fill");
+ assert_eq!(sources_looks(&s, g), sources0);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "one undo step");
+ // A gradient placed on each face's own bounds is one shared fill: the edges take it, fitted to each edge.
+ s.execute("paint.setFill", &json!({"gradient": {"aspect": 50}})).unwrap();
+ let placed: Vec = part_looks(&s, g).0.iter().map(|f| f.fill_paint()).collect();
+ assert!(placed.iter().all(|p| matches!(p, Paint::Gradient(gr) if gr.geom.is_some())) && placed[0] != placed[1]);
+ s.execute("paint.swap", &json!({})).unwrap();
+ let (faces2, edges2) = part_looks(&s, g);
+ assert!(faces2.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK)));
+ assert!(edges2.iter().all(|e| matches!(e.stroke_paint(), Paint::Gradient(gr) if gr.geom.is_none() && gr.freeform.is_none())));
+ // A freeform gradient's points belong to its face: faces with freeform fills keep their paint, in no undo step.
+ s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
+ assert!(
+ part_looks(&s, g)
+ .0
+ .iter()
+ .all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.gradient.kind == vectorcraft_color::GradientKind::Freeform))
+ );
+ let looks = part_looks(&s, g);
+ let depth = history_state(&s).0;
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), looks);
+ assert_eq!(history_state(&s).0, depth);
+ // A group with edges and no faces keeps its paint.
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ assert!(part_looks(&s, edges_only).0.is_empty());
+ s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
+ let looks = part_looks(&s, edges_only);
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, edges_only), looks);
+}
+
+/// Default Fill and Stroke on a whole selected Live Paint group leaves its faces with no fill and
+/// gives its edges a 0.5 pt black stroke, and new art takes the same; other art selected with it
+/// takes the white fill and 1 pt black stroke.
+#[test]
+fn live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ let (faces, edges) = part_looks(&s, g);
+ assert!(faces.iter().all(|f| f.fill_paint().is_none() && f.stroke_paint().is_none()));
+ assert!(edges.iter().all(|e| e.stroke_paint() == Paint::solid(Color::BLACK) && e.stroke_width() == 0.5 && e.fill_paint().is_none()));
+ assert_eq!(sources_looks(&s, g), sources0);
+ assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, Paint::solid(Color::BLACK), 0.5));
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!((p["fillMixed"].clone(), p["strokeMixed"].clone()), (json!(false), json!(false)));
+ // The next shape drawn has no fill and a 0.5 pt black stroke.
+ let next = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
+ let look = node(&s, next).appearance.clone();
+ assert!(!look.has_visible_fill());
+ assert_eq!((look.stroke_paint(), look.stroke_width()), (Paint::solid(Color::BLACK), 0.5));
+ // With a plain rectangle selected too, the rectangle and new art take the white fill and 1 pt black stroke.
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ s.execute("paint.setFill", &json!({"ids": [r.0], "color": "#00ff00"})).unwrap();
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::WHITE));
+ assert_eq!(part_looks(&s, g), (faces.clone(), edges.clone()));
+ assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::solid(Color::WHITE), 1.0));
+ // A redefined Default Graphic Style goes to other art; the parts still take no fill and a 0.5 pt black stroke.
+ s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
+ s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.execute("stroke.set", &json!({"weight": 3})).unwrap();
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), (faces, edges), "the parts do not take the redefined style");
+ assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()));
+}
+
+/// Invert on a whole selected Live Paint group recolors its faces' fills and leaves its edges and
+/// hidden source paths as they are.
+#[test]
+fn live_paint_group_invert_recolors_the_faces_fill() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ let (_, edges0) = part_looks(&s, g);
+ s.execute("paint.invert", &json!({"stroke": false})).unwrap();
+ let (faces, edges) = part_looks(&s, g);
+ assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
+ assert_eq!(edges, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+ // The same with `target: "contents"`, for the stroke.
+ s.execute("paint.invert", &json!({"stroke": true, "target": "contents"})).unwrap();
+ let (faces1, edges1) = part_looks(&s, g);
+ assert_eq!(faces1, faces);
+ assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::WHITE)));
+ assert_eq!(sources_looks(&s, g), sources0);
+ // A gradient edit of the fill goes to the faces only.
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap();
+ let (faces2, edges2) = part_looks(&s, g);
+ assert!(faces2.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(_))));
+ assert_eq!(edges2, edges1, "edges take no fill gradient");
+ assert_eq!(sources_looks(&s, g), sources0);
+ // Selecting a Live Paint group with edges and no faces gives new art its edges' stroke.
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ s.execute("paint.setStroke", &json!({"ids": [edges_only.0], "color": "#00ff00"})).unwrap();
+ s.execute("select.none", &json!({})).unwrap();
+ s.paint.stroke = Paint::None;
+ s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
+ assert_eq!(s.paint.stroke, Paint::solid(Color::from_hex("#00ff00").unwrap()));
+}
+
+/// A gradient vector or freeform point edit of a whole selected Live Paint group's fill changes its
+/// faces' gradients and leaves its edges and hidden source paths as they are.
+#[test]
+fn live_paint_group_gradient_vector_and_freeform_edits_change_its_faces() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ let (_, edges0) = part_looks(&s, g);
+ let face_ids: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id.0).collect();
+ let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "start": [0, 0], "end": [100, 0]})).unwrap();
+ let mut changed: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
+ changed.sort_unstable();
+ let mut faces = face_ids.clone();
+ faces.sort_unstable();
+ assert_eq!(changed, faces, "only the faces take the vector");
+ assert_eq!(part_looks(&s, g).1, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+ s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
+ s.execute("paint.freeform.addPoint", &json!({"stroke": false, "at": [25, 50], "color": "#00ff00"})).unwrap();
+ assert!(part_looks(&s, g).0.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.freeform.is_some())));
+ assert_eq!(part_looks(&s, g).1, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+}
+
+/// The Live Paint rules stop where a paint command stops: a Live Paint group in a compound shape or
+/// a blend keeps its parts' paint when the compound shape or blend takes the default, Invert
+/// remembers the faces' color the proxy shows, and a Live Paint group without faces lets the Fill
+/// proxy show the next selected object's fill, while an empty plain group does not.
+#[test]
+fn live_paint_group_rules_stop_where_paint_commands_stop() {
+ let mut s = session();
+ let g = live(&mut s);
+ let looks = part_looks(&s, g);
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ let c = NodeId(s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap()["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), looks, "a compound shape's member keeps its paint");
+ s.execute("paint.default", &json!({"ids": [c.0, g.0]})).unwrap();
+ assert_eq!(part_looks(&s, g), looks, "a compound shape's member given as well keeps its paint");
+ // Given alone, the member is a Live Paint group: a fill paints its faces and leaves its edges.
+ s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#ff00ff"})).unwrap();
+ let (faces, edges) = part_looks(&s, g);
+ assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::from_hex("#ff00ff").unwrap())));
+ assert_eq!(edges, looks.1, "the edges of a member given alone take no fill");
+
+ // A Live Paint group selected with one of its edges: the edge counts with the group.
+ let mut s = session();
+ let g = live(&mut s);
+ let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
+ s.execute("select.set", &json!({"ids": [g.0, edge.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fillMixed"], false);
+ assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge selected with its group takes no fill");
+ // The same for an edge given in `ids` with its group.
+ s.execute("paint.setFill", &json!({"ids": [g.0, edge.0], "color": "#0000ff"})).unwrap();
+ assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge given with its group takes no fill");
+
+ // The same for a blend's key.
+ let mut s = session();
+ let g = live(&mut s);
+ let looks = part_looks(&s, g);
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ let b = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), looks, "a blend's key keeps its paint");
+
+ // A Live Paint group inside a selected group: Invert recolors its faces' fills only.
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ let (_, edges0) = part_looks(&s, g);
+ s.execute("object.group", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.invert", &json!({"stroke": false})).unwrap();
+ assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
+ assert_eq!(part_looks(&s, g).1, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.edit("t", |d, _| {
+ d.node_mut(g).unwrap().appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("paint.invert", &json!({"stroke": false})).unwrap();
+ // Like any group's, the group's own row is recolored too; the color remembered is the faces' one the proxy shows.
+ assert_eq!(node(&s, g).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 1.0, 0.0)));
+ assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
+ assert_eq!(s.last_solid, Color::rgb(0.0, 1.0, 1.0));
+
+ let mut s = session();
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ assert!(part_looks(&s, edges_only).0.is_empty());
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ set_fill(&mut s, r, Color::from_hex("#00ff00").unwrap());
+ s.execute("select.set", &json!({"ids": [edges_only.0, r.0]})).unwrap();
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#00ff00").unwrap())).unwrap());
+ // The edges-only group shows its edges' stroke in the Stroke panel.
+ let edge_width = part_looks(&s, edges_only).1[0].stroke_width();
+ assert_eq!(s.shown_stroke().map(|st| st.width), Some(edge_width));
+
+ // Any other object with nothing painted in it first in the selection (a group left empty) shows
+ // the defaults for new art, not the next object's paint.
+ let inner = rect(&mut s, 0.0, 300.0, 50.0, 50.0);
+ let empty = NodeId(s.execute("object.group", &json!({"ids": [inner.0]})).unwrap()["id"].as_u64().unwrap());
+ s.edit("t", |d, _| {
+ d.children_mut(Some(empty)).unwrap().clear();
+ Ok(())
+ })
+ .unwrap();
+ s.execute("stroke.set", &json!({"ids": [r.0], "weight": 7})).unwrap();
+ s.paint.fill = Paint::None;
+ s.execute("select.set", &json!({"ids": [empty.0, r.0]})).unwrap();
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["fill"], serde_json::to_value(Paint::None).unwrap());
+ assert!(s.shown_stroke().is_none());
+}
+
+/// Stroke panel edits of a whole selected Live Paint group (a weight, a step up or down, options)
+/// change its edges and leave its faces as they are, and the panel shows the edges' stroke.
+#[test]
+fn live_paint_group_stroke_panel_edits_change_its_edges() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let (faces0, edges0) = part_looks(&s, g);
+ assert_eq!(s.execute("stroke.set", &json!({"weight": 5})).unwrap()["objects"], edges0.len());
+ let (faces1, edges1) = part_looks(&s, g);
+ assert_eq!(faces1, faces0, "faces take no stroke weight");
+ assert!(edges1.iter().all(|e| e.stroke().is_some_and(|st| st.width == 5.0)));
+ assert_eq!(s.shown_stroke().map(|st| st.width), Some(5.0));
+ assert!(!s.doc().unwrap().stroke_mixed().weight);
+ s.execute("stroke.weightUp", &json!({})).unwrap();
+ s.execute("stroke.set", &json!({"cap": "round"})).unwrap();
+ let (faces2, edges2) = part_looks(&s, g);
+ assert_eq!(faces2, faces0, "faces take no stroke step or cap");
+ assert!(edges2.iter().all(|e| e.stroke().is_some_and(|st| st.width == 6.0 && st.cap == LineCap::Round)));
+ // A stroke on the faces (from a file, say) leaves the panel showing the edges' stroke.
+ let face_ids: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id).collect();
+ s.edit("t", |d, _| {
+ for id in &face_ids {
+ let face = d.node_mut(*id).unwrap();
+ face.appearance.set_stroke(Paint::solid(Color::BLACK));
+ face.appearance.stroke_at_mut(None).unwrap().width = 2.0;
+ }
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0));
+ assert!(!s.doc().unwrap().stroke_mixed().weight);
+ // A face selected with its group counts with the group, whose stroke is its edges'.
+ s.execute("select.set", &json!({"ids": [g.0, face_ids[0].0]})).unwrap();
+ assert!(!s.doc().unwrap().stroke_mixed().weight);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ // A stroke row on the group itself: a weight still goes to the edges the panel shows.
+ s.edit("t", |d, _| {
+ d.node_mut(g).unwrap().appearance.set_stroke(Paint::solid(Color::BLACK));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("stroke.set", &json!({"weight": 3})).unwrap();
+ assert!(part_looks(&s, g).1.iter().all(|e| e.stroke_width() == 3.0));
+ assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
+}
+
+/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
+/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
+/// leaves the settings for new art as they are.
+#[test]
+fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
+ let mut s = session();
+ let g = live(&mut s);
+ let edge_ids: Vec = vectorcraft_tools::builder::edges(&node(&s, g)).iter().map(|e| e.id).collect();
+ s.edit("t", |d, _| {
+ d.children_mut(Some(g)).unwrap().retain(|c| !edge_ids.contains(&c.id));
+ Ok(())
+ })
+ .unwrap();
+ assert!(part_looks(&s, g).1.is_empty());
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let looks = part_looks(&s, g);
+ let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
+ s.execute("stroke.set", &json!({"cap": "round"})).unwrap();
+ s.execute("stroke.set", &json!({"weight": 4})).unwrap();
+ s.execute("stroke.weightUp", &json!({})).unwrap();
+ s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
+ assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
+ assert_eq!(part_looks(&s, g), looks);
+
+ let mut s = session();
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
+ let looks = part_looks(&s, edges_only);
+ let paint0 = s.paint.clone();
+ s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap();
+ assert_eq!(s.paint, paint0, "new art keeps its fill");
+ assert_eq!(part_looks(&s, edges_only), looks);
+}
+
/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of
/// `xs`.
fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId {
diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs
new file mode 100644
index 0000000000..66283183b9
--- /dev/null
+++ b/crates/engine/src/tests/quickpen.rs
@@ -0,0 +1,300 @@
+//! The Quick Pen tool driven through the session, and `path.quickPen`.
+
+use serde_json::{Value, json};
+use vectorcraft_doc::{NodeId, NodeKind};
+use vectorcraft_geom::{PathData, Point, SubPath};
+use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
+
+use crate::tooling::ViewInfo;
+use crate::*;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
+ s
+}
+
+fn view() -> ViewInfo {
+ ViewInfo { smart_guides: false, ..Default::default() }
+}
+
+fn undo_steps(s: &Session) -> usize {
+ s.doc().unwrap().history.undo.len()
+}
+
+fn paths(s: &Session) -> Vec<(NodeId, PathData)> {
+ let mut v = vec![];
+ s.doc().unwrap().doc.walk(|n| {
+ if let NodeKind::Path { path, .. } = &n.kind {
+ v.push((n.id, path.clone()));
+ }
+ });
+ v
+}
+
+fn only_path(s: &Session) -> SubPath {
+ let all = paths(s);
+ assert_eq!(all.len(), 1, "one path");
+ all[0].1.subpaths[0].clone()
+}
+
+fn pt(x: f64, y: f64) -> Point {
+ Point::new(x, y)
+}
+
+fn press(s: &mut Session, pts: &[(f64, f64)]) {
+ let v = view();
+ s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
+ for &(x, y) in &pts[1..] {
+ s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
+ }
+ let l = pts[pts.len() - 1];
+ s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap();
+}
+
+fn click(s: &mut Session, x: f64, y: f64) {
+ press(s, &[(x, y)]);
+}
+
+fn key(s: &mut Session, k: ToolKey) {
+ s.tool_key(k, Mods::default(), view()).unwrap();
+}
+
+fn quick_pen(s: &mut Session) {
+ s.select_tool("quickPen", view()).unwrap();
+}
+
+/// Clicks draw lines; Alt tapped alone switches to the next action, so the next clicks draw a
+/// continuous arc and a sharp-corner half circle. Each piece is one undo step.
+#[test]
+fn clicks_draw_lines_and_arcs_one_undo_step_each() {
+ let mut s = session();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ let undo = undo_steps(&s);
+ click(&mut s, 200.0, 100.0);
+ assert_eq!(undo_steps(&s), undo + 1);
+ key(&mut s, ToolKey::AltTap);
+ assert_eq!(s.tool_options()["action"], "continuousArc");
+ click(&mut s, 300.0, 200.0);
+ key(&mut s, ToolKey::AltTap);
+ assert_eq!(s.tool_options()["action"], "sharpArc");
+ click(&mut s, 300.0, 300.0);
+ assert_eq!(undo_steps(&s), undo + 3);
+ let sp = only_path(&s);
+ assert!(!sp.closed);
+ let ends: Vec = sp.anchors.iter().map(|a| a.p).collect();
+ assert_eq!(ends.first(), Some(&pt(100.0, 100.0)));
+ assert_eq!(ends.last(), Some(&pt(300.0, 300.0)));
+ // Line (2 points), quarter circle (1 more), half circle in two quarters (2 more).
+ assert_eq!(ends.len(), 5);
+ // The continuous arc left (200, 100) heading right, as the line arrived.
+ let joint = sp.anchors.get(1).unwrap();
+ assert!((joint.h_out - joint.p).y.abs() < 1e-9 && joint.h_out.x > joint.p.x);
+ // The half circle on (300, 200)–(300, 300) bulges to the left of the way it was drawn
+ // (downward, so to the right on the page): its middle point is at x = 350.
+ assert!(sp.anchors.get(3).unwrap().p.distance(pt(350.0, 250.0)) < 1e-9);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(only_path(&s).anchors.len(), 3);
+}
+
+/// C flips the last sharp-corner arc, and [ and ] make it 15° smaller or larger, each as one
+/// undo step; the next arc keeps the new size. C is not taken while the last piece is a line.
+#[test]
+fn c_flips_and_brackets_size_the_last_sharp_arc() {
+ let mut s = session();
+ quick_pen(&mut s);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
+ click(&mut s, 100.0, 300.0);
+ click(&mut s, 300.0, 300.0);
+ assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 200.0)) < 1e-9, "above the chord");
+ assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
+ let undo = undo_steps(&s);
+ key(&mut s, ToolKey::Letter('c'));
+ assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "below once flipped");
+ assert_eq!(undo_steps(&s), undo + 1);
+ key(&mut s, ToolKey::BracketLeft);
+ assert_eq!(s.tool_options()["turn"], 165.0);
+ let sp = only_path(&s);
+ // A 165° arc is two segments; its middle point lies on the chord's perpendicular bisector,
+ // still below.
+ assert_eq!(sp.anchors.len(), 3);
+ let mid = sp.anchors.get(1).unwrap().p;
+ assert!((mid.x - 200.0).abs() < 1e-9 && mid.y > 300.0);
+ assert_eq!(undo_steps(&s), undo + 2);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap();
+ click(&mut s, 400.0, 300.0);
+ assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
+}
+
+/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
+/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
+#[test]
+fn an_alt_tap_during_a_drag_switches_the_piece_and_drawing_goes_on() {
+ let mut s = session();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 200.0, 100.0);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "continuousArc"})).unwrap();
+ // A quarter circle that arrives at (300, 200) heading down.
+ click(&mut s, 300.0, 200.0);
+ let joint = only_path(&s).anchors.len() - 1;
+ let v = view();
+ s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 300.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 210.0, 310.0), v).unwrap();
+ assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Smooth);
+ key(&mut s, ToolKey::AltTap);
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 300.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 300.0), v).unwrap();
+ assert_eq!(s.tool_options()["action"], "sharpArc");
+ assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Corner);
+ click(&mut s, 100.0, 300.0);
+ assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(100.0, 300.0), "the same path");
+}
+
+/// A click on the first point closes the path; the next click starts a new one.
+#[test]
+fn a_click_on_the_first_point_closes_the_path() {
+ let mut s = session();
+ quick_pen(&mut s);
+ for (x, y) in [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (101.0, 101.0)] {
+ click(&mut s, x, y);
+ }
+ let sp = only_path(&s);
+ assert!(sp.closed);
+ assert_eq!(sp.anchors.len(), 3);
+ click(&mut s, 400.0, 400.0);
+ assert_eq!(paths(&s).len(), 2);
+}
+
+/// Escape ends the path: the next click starts a new path. A press dragged places the piece
+/// where it is let go.
+#[test]
+fn escape_ends_the_path_and_a_drag_places_the_piece() {
+ let mut s = session();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ press(&mut s, &[(150.0, 100.0), (180.0, 120.0), (250.0, 150.0)]);
+ assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
+ assert!(s.tool_ends_on_escape(view()));
+ key(&mut s, ToolKey::Escape);
+ assert!(!s.tool_ends_on_escape(view()));
+ click(&mut s, 500.0, 500.0);
+ assert_eq!(paths(&s).len(), 2);
+}
+
+/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
+/// over the edit, and the next click starts a new path instead of rebuilding the old one.
+#[test]
+fn an_edit_from_outside_ends_the_path() {
+ let mut s = session();
+ quick_pen(&mut s);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
+ click(&mut s, 100.0, 300.0);
+ click(&mut s, 300.0, 300.0);
+ let (id, _) = paths(&s)[0].clone();
+ s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 320, "y": 280})).unwrap();
+ assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
+ click(&mut s, 500.0, 500.0);
+ let all = paths(&s);
+ assert_eq!(all.len(), 2, "a new path");
+ assert_eq!(all[0].1.subpaths[0].anchors.last().unwrap().p, pt(320.0, 280.0), "the edit stays");
+ // The same for a point of a path the tool went on from, and for the first point of a new path.
+ for new in [true, false] {
+ let mut s = session();
+ let id = if new {
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 200.0, 100.0);
+ paths(&s)[0].0
+ } else {
+ let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap();
+ let id = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ quick_pen(&mut s);
+ click(&mut s, 200.0, 100.0);
+ click(&mut s, 200.0, 200.0);
+ id
+ };
+ s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
+ click(&mut s, 400.0, 400.0);
+ assert_eq!(paths(&s).len(), 2, "a new path (new: {new})");
+ assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.first().unwrap().p, pt(90.0, 90.0));
+ }
+}
+
+/// A click on an end of an open path goes on drawing from it, in the same path; from its start,
+/// the path is reversed first.
+#[test]
+fn a_click_on_an_open_end_continues_the_path() {
+ let mut s = session();
+ let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap();
+ let id = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 100.0, 200.0);
+ let all = paths(&s);
+ assert_eq!(all.len(), 1);
+ assert_eq!(all[0].0, id);
+ let ends: Vec = all[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
+ assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]);
+}
+
+/// `path.quickPen` makes a new path with the current paint, or a black stroke without any.
+#[test]
+fn path_quick_pen_makes_a_stroked_path() {
+ let mut s = session();
+ s.execute("paint.setStroke", &json!({"none": true})).unwrap();
+ s.execute("paint.setFill", &json!({"none": true})).unwrap();
+ let r = s
+ .execute(
+ "path.quickPen",
+ &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100, "action": "sharpArc", "turn": 90, "flip": true}]}),
+ )
+ .unwrap();
+ let id = r["id"].as_u64().unwrap();
+ let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
+ assert!(!n.appearance.stroke_paint().is_none(), "a black stroke");
+ assert_eq!(n.path_data().unwrap().subpaths[0].anchors.len(), 3);
+}
+
+/// Bad params are refused and change nothing.
+#[test]
+fn path_quick_pen_refuses_bad_params() {
+ let mut s = session();
+ let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}]})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ let before = paths(&s);
+ let bad: [Value; 11] = [
+ json!({}),
+ json!({"pieces": []}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "arc"}]}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "sharpArc", "turn": 0}]}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "turn": 360}]}),
+ json!({"start": [0, 0], "pieces": [{"x": "1", "y": 1}]}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "flip": "yes"}]}),
+ json!({"start": [0, 0], "keep": 1}),
+ json!({"id": id, "keep": 0}),
+ json!({"id": id, "keep": 3}),
+ json!({"id": id, "start": [0, 0]}),
+ ];
+ for p in bad {
+ assert!(s.execute("path.quickPen", &p).is_err(), "{p}");
+ }
+ assert!(s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": vec![json!({"x": 1, "y": 1}); 10_001]})).is_err());
+ s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap();
+ assert!(s.execute("path.quickPen", &json!({"id": id, "pieces": [{"x": 5, "y": 5}]})).is_err(), "closed");
+ assert_eq!(paths(&s).len(), before.len());
+}
+
+/// With `id` and `keep`, the points after the first `keep` are replaced by the pieces.
+#[test]
+fn path_quick_pen_replaces_the_points_after_keep() {
+ let mut s = session();
+ let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ s.execute("path.quickPen", &json!({"id": id, "keep": 2, "pieces": [{"x": 200, "y": 0}]})).unwrap();
+ let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect();
+ assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]);
+}
diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs
index 27ce315d92..b5c069c749 100644
--- a/crates/engine/tests/import_fuzz.rs
+++ b/crates/engine/tests/import_fuzz.rs
@@ -8465,3 +8465,51 @@ proptest! {
prop_assert_eq!(paths, 2, "{:?}", notes);
}
}
+
+proptest! {
+ #![proptest_config(config())]
+
+ /// A stroke's arrowheads (#8188): its arrowhead entries with any scale of any kind, naming a
+ /// symbol the file defines, one it doesn't or one named in Chinese, the symbol's art any run of
+ /// paths (frames, samples of the line, heads, open and closed, filled, stroked or neither), at
+ /// any weight, the style section cut anywhere, the line drawn as any look. Read as a `.ai` and
+ /// as an EPS, then rendered.
+ #[test]
+ fn ai_arrowhead_strokes_never_panic(
+ scale in prop_oneof![arb_num(), Just("50".to_string())],
+ kind in prop::sample::select(vec!["Real", "Int", "Bool"]),
+ named in prop::sample::select(vec!["W", "Missing", "\u{6954}"]),
+ both in any::(),
+ art in prop::collection::vec(prop::sample::select(vec![
+ "-10 5 m\n10 5 L\n10 -5 L\n-10 -5 L\nn\n",
+ "0 G\n1 w\n-9 0 m\n4 0 l\nS\n",
+ "0 G\n0.5 w\n-9 0 m\n4 0 l\nS\n",
+ "0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n",
+ "0 G\n1 w\n2 3 m\n8 0 l\n2 -3 l\nS\n",
+ "0 g\n1e300 0 m\n-1e300 1 l\nf\n",
+ "0 g\n0 0 m\n0 0 l\nf\n",
+ ]), 0..6),
+ width in arb_num(),
+ cut in 0usize..2000,
+ look in prop::sample::select(vec!["0 G\n2 w\n0 50 m\n96 50 l\nS\n0 g\n94 53 m\n100 50 l\n94 47 l\nf\n", "0 G\n2 w\n0 50 m\n100 50 l\nS\n", ""]),
+ ) {
+ use vectorcraft_testkit::ai;
+ let symbol = format!("%AI5_Begin_NonPrinting\n%AI14_BeginSymbol\n(W)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n%AI10_EndSymbol\n%AI5_End_NonPrinting--\n", art.concat());
+ let start = if both { format!("{scale} /{kind} (BSArrowBeginScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowBeginSymbol) ,\n") } else { String::new() };
+ let styles = format!(
+ "%AI9_BeginArtStyles\n/KnownStyle :\n(Arrowed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
+ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
+ /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/Dictionary : /NotRecorded ,\n\
+ {start}{scale} /{kind} (BSArrowEndScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowEndSymbol) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\
+ /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\
+ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n\
+ %AI9_BeginArtStyleList\n(Arrowed)\n%AI9_EndArtStyleList\n"
+ );
+ let styles: String = styles.chars().take(cut).collect();
+ let line = format!("0 Ae\nu\n{look}U\n%_0 50 m\n%_100 50 L\n%_N\n1 (Arrowed) XW\n");
+ let data = ai::editing_data(200.0, 100.0, &format!("{symbol}{styles}{}", ai::layer("L", &line)));
+ survive("arrowhead strokes", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
+ let eps = ai::eps(data.as_bytes(), ai::page_ps());
+ survive("arrowhead strokes in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
+ }
+}
diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs
index c630c9cf43..4c574ce3bb 100644
--- a/crates/eps/src/import/ai.rs
+++ b/crates/eps/src/import/ai.rs
@@ -17,6 +17,7 @@
//! objects and points. Anything it doesn't read is an error: the caller opens the file the way it
//! did before (the printed page, or the PDF), with a warning saying why.
+mod arrowhead;
mod blend;
mod brush;
mod envelope;
diff --git a/crates/eps/src/import/ai/arrowhead.rs b/crates/eps/src/import/ai/arrowhead.rs
new file mode 100644
index 0000000000..f1a30c08af
--- /dev/null
+++ b/crates/eps/src/import/ai/arrowhead.rs
@@ -0,0 +1,244 @@
+//! Arrowheads a file defines: the art of a symbol that a stroke's arrowhead entry names
+//! ([`super::style::StrokeArrows`]), read into a head ([`head`]).
+//!
+//! Not publicly documented. As the files have it, an arrowhead symbol's art (y down here, as the
+//! document's symbols are) points right along a straight, level sample of the line it ends: an
+//! open stroked path with no fill whose anchors and handles all lie on that line, 1 pt wide. The
+//! sample ends where the line stops under the head. The rest of the art that paints is the head;
+//! its tip is its rightmost point, and a symbol unit is one point on a 1 pt stroke at 100 %, so a
+//! unit is the head's weight as it is for VectorCraft's own heads. Art that paints nothing (the
+//! frame of the symbol's box, hidden or fully transparent art) is left out.
+
+use vectorcraft_doc::{AppearanceItem, CustomArrowhead, Node, NodeKind, StrokeLayer};
+use vectorcraft_geom::{Affine, FillRule, PathData, Point};
+
+/// The most anchors an arrowhead symbol's art is read with, outlined strokes included, before its
+/// shapes are united.
+const MAX_ART_ANCHORS: usize = 65_536;
+/// How deep the groups of an arrowhead symbol's art are read.
+const MAX_DEPTH: usize = 16;
+
+/// The head that symbol art `art` (in the document's symbol space) draws, named `name`. `None` when
+/// the art doesn't have exactly one sample of the line, its sample isn't 1 pt wide, it holds
+/// anything but paths, compound paths and groups (a clip group, say), has an effect, a brush, an
+/// opacity mask, partial opacity or a group with fills or strokes of its own, paints no head, or is
+/// too detailed for one; or when the
+/// line would stop past the head's tip or farther back than a head can reach
+/// ([`CustomArrowhead::MAX_UNITS`]).
+pub(super) fn head(name: &str, art: &Node) -> Option {
+ let mut parts = Parts::default();
+ match &art.kind {
+ // The members of the symbol's group are its art's top level, where the sample is.
+ NodeKind::Group { children, clip: false } if art.visible && plain(art) && !paints(art) => {
+ for c in children {
+ parts.member(c, true, 1)?;
+ }
+ }
+ _ => parts.member(art, true, 0)?,
+ }
+ let [(axis, line_end)] = parts.lines.as_slice() else { return None };
+ if parts.shapes.is_empty() {
+ return None;
+ }
+ let refs: Vec<(&PathData, FillRule)> = parts.shapes.iter().map(|(p, r)| (p, *r)).collect();
+ let area = vectorcraft_pathops::try_unite_all(&refs).ok()?;
+ let b = area.bounds().filter(|b| b.is_finite() && b.height() > 1e-9)?;
+ let tip = b.x1;
+ // Head units: x back from the tip, y across to the right of the way the head points (down).
+ let h = CustomArrowhead::new(name.to_string(), area.transformed(Affine::new([-1.0, 0.0, 0.0, 1.0, tip, -axis])));
+ let h = h.with_stop(tip - line_end);
+ (!h.path.subpaths.is_empty() && h.stop.is_some()).then_some(h)
+}
+
+/// What an arrowhead symbol's art is made of.
+#[derive(Default)]
+struct Parts {
+ /// Each sample of the line: the line's y, and the x where the sample ends.
+ lines: Vec<(f64, f64)>,
+ /// The areas the head paints.
+ shapes: Vec<(PathData, FillRule)>,
+ anchors: usize,
+}
+
+impl Parts {
+ /// Read `n`, a member of the art (`top`: of its top level) `depth` groups down. `None` when it
+ /// is something [`head`] doesn't read.
+ fn member(&mut self, n: &Node, top: bool, depth: usize) -> Option<()> {
+ if depth > MAX_DEPTH {
+ return None;
+ }
+ // Hidden or fully transparent art paints nothing.
+ if !n.visible || n.opacity <= 0.0 {
+ return Some(());
+ }
+ if !plain(n) {
+ return None;
+ }
+ match &n.kind {
+ NodeKind::Group { children, clip: false } => {
+ if paints(n) {
+ return None;
+ }
+ children.iter().try_for_each(|c| self.member(c, false, depth + 1))
+ }
+ NodeKind::Path { guide: true, .. } => Some(()),
+ NodeKind::Path { path, rule, .. } => self.painted(n, path, *rule, top),
+ NodeKind::Compound { children, rule } => {
+ let mut subpaths = vec![];
+ for c in children {
+ subpaths.extend(c.path_data()?.subpaths.iter().cloned());
+ }
+ self.painted(n, &PathData::new(subpaths), *rule, false)
+ }
+ _ => None,
+ }
+ }
+
+ /// Read the fills and strokes of path or compound path `n`, its outline `path` filled under
+ /// `rule` (`top`: a member of the art's top level, which may be the sample of the line).
+ fn painted(&mut self, n: &Node, path: &PathData, rule: FillRule, top: bool) -> Option<()> {
+ self.room(path.anchor_count())?;
+ let mut filled = false;
+ let mut strokes: Vec<&StrokeLayer> = vec![];
+ for item in &n.appearance.items {
+ match item {
+ AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none() => {
+ if !f.effects.is_empty() || f.opacity < 1.0 {
+ return None;
+ }
+ filled = true;
+ }
+ AppearanceItem::Stroke(s) if s.visible && s.opacity > 0.0 && !s.paint.is_none() && s.width > 0.0 => {
+ if !s.effects.is_empty() || s.brush.is_some() || s.opacity < 1.0 {
+ return None;
+ }
+ strokes.push(s);
+ }
+ _ => {}
+ }
+ }
+ if top
+ && !filled
+ && let [line] = strokes.as_slice()
+ && let Some(sample) = sample_line(path)
+ {
+ // The sample is 1 pt, the weight of a head at one unit; another weight (art stored
+ // at another scale, as a Large Canvas file's) gives the units no known size.
+ if (line.width - 1.0).abs() > 1e-6 {
+ return None;
+ }
+ self.lines.push(sample);
+ return Some(());
+ }
+ if filled {
+ self.shapes.push((path.clone(), rule));
+ }
+ for s in strokes {
+ let outline = vectorcraft_effects::stroke::outline_region(path, rule, s);
+ self.room(outline.anchor_count())?;
+ if !outline.subpaths.is_empty() {
+ self.shapes.push((outline, FillRule::NonZero));
+ }
+ }
+ Some(())
+ }
+
+ /// Count `anchors` more; `None` past [`MAX_ART_ANCHORS`].
+ fn room(&mut self, anchors: usize) -> Option<()> {
+ self.anchors = self.anchors.saturating_add(anchors);
+ (self.anchors <= MAX_ART_ANCHORS).then_some(())
+ }
+}
+
+/// Does `n` draw as its shapes alone: fully opaque, with no effects and no opacity mask applied?
+/// A head is one opaque shape, so partly transparent or masked art isn't read as one.
+fn plain(n: &Node) -> bool {
+ n.opacity >= 1.0 && n.appearance.effects.is_empty() && n.extras().mask.as_ref().is_none_or(|m| m.disabled)
+}
+
+/// Does `n` (a group) have fills or strokes of its own that paint?
+fn paints(n: &Node) -> bool {
+ n.appearance.items.iter().any(|i| match i {
+ AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(),
+ AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none(),
+ })
+}
+
+/// `path` as a sample of the line, when it is one open subpath of two anchors or more whose anchors
+/// and handles all lie level with its first anchor: that y, and the x where it ends (its
+/// rightmost anchor).
+fn sample_line(path: &PathData) -> Option<(f64, f64)> {
+ let [sub] = path.subpaths.as_slice() else { return None };
+ if sub.closed || sub.anchors.len() < 2 {
+ return None;
+ }
+ let y = sub.anchors.first()?.p.y;
+ let level = |q: Point| q.x.is_finite() && (q.y - y).abs() <= 1e-6 * (1.0 + y.abs());
+ if !y.is_finite() || !sub.anchors.iter().all(|a| level(a.p) && level(a.h_in) && level(a.h_out)) {
+ return None;
+ }
+ Some((y, sub.anchors.iter().map(|a| a.p.x).fold(f64::NEG_INFINITY, f64::max)))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use vectorcraft_color::{Color, Paint};
+ use vectorcraft_doc::{Appearance, Node, NodeId, OpacityMask};
+ use vectorcraft_geom::{PathData, Point, SubPath};
+
+ use super::head;
+
+ fn path(id: u64, points: &[(f64, f64)], closed: bool, appearance: Appearance) -> Arc {
+ let points: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect();
+ Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, closed)), appearance))
+ }
+
+ /// A 1 pt sample of the line from x = −9 to 4 on y = 0.
+ fn sample() -> Arc {
+ path(1, &[(-9.0, 0.0), (4.0, 0.0)], false, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))
+ }
+
+ /// A filled wedge from x = 2 back to its tip at x = 8, 3 either side.
+ fn wedge() -> Arc {
+ path(2, &[(2.0, -3.0), (8.0, 0.0), (2.0, 3.0)], true, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))
+ }
+
+ fn art(members: Vec>) -> Node {
+ Node::group(NodeId(10), members)
+ }
+
+ #[test]
+ fn a_wedge_and_its_sample_make_a_head() {
+ let h = head("W", &art(vec![sample(), wedge()])).expect("a head");
+ assert_eq!(h.stop(), 4.0);
+ }
+
+ #[test]
+ fn partly_transparent_or_masked_art_makes_no_head() {
+ // The head would come in opaque and whole, with the bounds of the art.
+ let half = |n: Arc| Arc::new(Node { opacity: 0.5, ..(*n).clone() });
+ let mut faint_fill = (*wedge()).clone();
+ let mut ap = (*faint_fill.appearance).clone();
+ if let Some(f) = ap.fill_mut() {
+ f.opacity = 0.5;
+ }
+ faint_fill.appearance = ap.into();
+ let mut masked = (*wedge()).clone();
+ masked.extras_mut().mask = Some(Box::new(OpacityMask { art: sample(), clip: true, invert: false, disabled: false, linked: true }));
+ let cases = [
+ ("a head at half opacity", art(vec![sample(), half(wedge())])),
+ ("a fill at half opacity", art(vec![sample(), Arc::new(faint_fill)])),
+ ("a group at half opacity", art(vec![sample(), half(Arc::new(art(vec![wedge()])))])),
+ ("the art at half opacity", Node { opacity: 0.5, ..art(vec![sample(), wedge()]) }),
+ ("a head with an opacity mask", art(vec![sample(), Arc::new(masked.clone())])),
+ ];
+ for (why, a) in cases {
+ assert!(head("W", &a).is_none(), "{why}");
+ }
+ // A disabled mask isn't applied.
+ masked.extras_mut().mask.as_mut().unwrap().disabled = true;
+ assert!(head("W", &art(vec![sample(), Arc::new(masked)])).is_some());
+ }
+}
diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs
index b354022258..11ebe2aac6 100644
--- a/crates/eps/src/import/ai/read.rs
+++ b/crates/eps/src/import/ai/read.rs
@@ -124,8 +124,8 @@ use vectorcraft_color::swatch::Swatch;
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::cmyk::Inks;
use vectorcraft_doc::{
- Appearance, AppearanceItem, Artboard, ColorMode, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin,
- LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit,
+ Appearance, AppearanceItem, Artboard, ColorMode, CustomArrowhead, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor,
+ LineCap, LineJoin, LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit,
};
use vectorcraft_geom::{AnchorKind, FillRule, PathData};
@@ -544,6 +544,10 @@ struct Reader<'a> {
symbol_bounds: HashMap,
/// The symbols read, by their name in the file → their name in the document.
symbol_names: HashMap,
+ /// The heads of the arrowhead symbols the art styles' strokes name, by the symbol's name in
+ /// the file (`None`: not a symbol read, or not one read as a head), read with the styles
+ /// ([`Reader::read_arrowheads`]).
+ arrowheads: HashMap>>,
/// The names the symbols read have in the document, and for each name read more than once,
/// the number its next copy is tried with.
symbol_taken: HashSet,
@@ -843,6 +847,7 @@ impl<'a> Reader<'a> {
unread: Vec::new(),
symbol_bounds: HashMap::new(),
symbol_names: HashMap::new(),
+ arrowheads: HashMap::new(),
symbol_taken: HashSet::new(),
symbol_suffix: HashMap::new(),
symbol_art_bounds: HashMap::new(),
diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs
index 46743e9d70..2a14ce1c24 100644
--- a/crates/eps/src/import/ai/read/containers.rs
+++ b/crates/eps/src/import/ai/read/containers.rs
@@ -752,6 +752,8 @@ impl<'a> Reader<'a> {
if std::mem::replace(&mut self.symbols_checked, true) {
return;
}
+ // The symbols are all read now: the heads of those defined after the styles.
+ self.read_arrowheads();
// Each symbol's name in the file (none for one named as an earlier one), and the names its
// instances use.
let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect();
diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs
index 67b3e799e2..55adb56a7c 100644
--- a/crates/eps/src/import/ai/read/directives.rs
+++ b/crates/eps/src/import/ai/read/directives.rs
@@ -128,6 +128,7 @@ impl<'a> Reader<'a> {
// section inside it would replace the file's own.
if self.subreader_depth == 0 {
self.styles = crate::import::ai::style::art_styles_in(section, &mut self.names);
+ self.read_arrowheads();
}
return Ok(());
}
@@ -398,6 +399,7 @@ impl<'a> Reader<'a> {
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.styles = std::mem::take(&mut self.styles);
+ sub.arrowheads = std::mem::take(&mut self.arrowheads);
sub.nodes = self.nodes;
sub.template = self.template;
self.lend_budgets(&mut sub);
@@ -408,6 +410,7 @@ impl<'a> Reader<'a> {
self.names.absorb(std::mem::take(&mut sub.names));
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
+ self.arrowheads = std::mem::take(&mut sub.arrowheads);
// Unread art in the definition, hidden or not, leaves the tile incomplete.
let whole = read.is_ok()
&& sub.unsupported.is_empty()
@@ -429,6 +432,7 @@ impl<'a> Reader<'a> {
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.styles = std::mem::take(&mut self.styles);
+ sub.arrowheads = std::mem::take(&mut self.arrowheads);
sub.nodes = self.nodes;
sub.template = self.template;
self.lend_budgets(&mut sub);
@@ -444,6 +448,7 @@ impl<'a> Reader<'a> {
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
+ self.arrowheads = std::mem::take(&mut sub.arrowheads);
self.names.absorb(std::mem::take(&mut sub.names));
let whole = read.is_ok()
&& sub.unsupported.is_empty()
@@ -597,6 +602,7 @@ impl<'a> Reader<'a> {
sub.gradients = std::mem::take(&mut self.gradients);
sub.global_names = std::mem::take(&mut self.global_names);
sub.styles = std::mem::take(&mut self.styles);
+ sub.arrowheads = std::mem::take(&mut self.arrowheads);
sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles);
sub.v7_patterns.clone_from(&self.v7_patterns);
sub.nodes = self.nodes;
@@ -607,6 +613,7 @@ impl<'a> Reader<'a> {
self.gradients = std::mem::take(&mut sub.gradients);
self.global_names = std::mem::take(&mut sub.global_names);
self.styles = std::mem::take(&mut sub.styles);
+ self.arrowheads = std::mem::take(&mut sub.arrowheads);
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
self.names.absorb(std::mem::take(&mut sub.names));
// Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or
@@ -788,6 +795,7 @@ impl<'a> Reader<'a> {
// version 7 form, lent.
sub.gradients = std::mem::take(&mut self.gradients);
sub.styles = std::mem::take(&mut self.styles);
+ sub.arrowheads = std::mem::take(&mut self.arrowheads);
sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles);
sub.v7_patterns = std::mem::take(&mut self.v7_patterns);
sub.global_names = std::mem::take(&mut self.global_names);
@@ -799,6 +807,7 @@ impl<'a> Reader<'a> {
self.nodes = sub.nodes;
self.gradients = std::mem::take(&mut sub.gradients);
self.styles = std::mem::take(&mut sub.styles);
+ self.arrowheads = std::mem::take(&mut sub.arrowheads);
self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles);
self.v7_patterns = std::mem::take(&mut sub.v7_patterns);
self.global_names = std::mem::take(&mut sub.global_names);
diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs
index 2eee5a0a15..29463daa85 100644
--- a/crates/eps/src/import/ai/read/document.rs
+++ b/crates/eps/src/import/ai/read/document.rs
@@ -455,6 +455,8 @@ pub fn graphic_styles(data: &[u8], large_canvas: bool, names: &mut obj::Names) -
r.large_canvas = large_canvas.then_some(1.0);
// The styles come before the art, so an error in the art leaves them read.
let _ = r.run();
+ // No layer checks the symbols here: the heads of those defined after the styles.
+ r.read_arrowheads();
let styles = r.graphic_styles().0;
let used: Vec<&str> = styles.iter().map(|s| s.name.as_str()).collect();
names.absorb_among(std::mem::take(&mut r.names), &used);
@@ -1183,7 +1185,7 @@ impl<'a> Reader<'a> {
continue;
}
let Some(st) = self.styles.get(&name) else { continue };
- let Some(mut appearance) = appearance_from_art_style(st, &self.gradients) else { continue };
+ let Some(mut appearance) = appearance_from_art_style(st, &self.gradients, &self.arrowheads) else { continue };
// A Large Canvas copy's styles are at its art's scale ([`Self::ensure_space`]).
if let Some(s) = self.large_canvas.filter(|s| *s != 1.0) {
appearance.scale_strokes(s);
diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs
index 101d924d60..65875c5a52 100644
--- a/crates/eps/src/import/ai/read/ops.rs
+++ b/crates/eps/src/import/ai/read/ops.rs
@@ -2,9 +2,12 @@ use super::containers::close;
use super::document::slot_of;
use super::types::{BLENDS, FLIP, Frame, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, line_width};
use super::{
- Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, HashMap, HashSet,
- Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint,
+ Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, CustomArrowhead, Dash, FillLayer, FillRule, Global, Gradient, GradientDef,
+ HashMap, HashSet, Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V,
+ obj, paint,
};
+use vectorcraft_doc::{ArrowAlign, Arrowhead};
+use vectorcraft_geom::PathData;
impl<'a> Reader<'a> {
// ---- operators -------------------------------------------------------------------------
@@ -707,6 +710,30 @@ impl<'a> Reader<'a> {
self.note_state();
}
+ /// Read the heads of the arrowhead symbols the art styles' strokes name into
+ /// [`Reader::arrowheads`] ([`crate::import::ai::arrowhead::head`]), each symbol once. Called
+ /// when the styles are read and again when the symbols have all been read ([`Self::check_symbols`]),
+ /// for a file that defines its symbols after its styles: a name with no symbol read yet is
+ /// left for then.
+ pub(super) fn read_arrowheads(&mut self) {
+ use crate::import::ai::style::StyleItem;
+ for st in self.styles.values() {
+ for item in &st.items {
+ let StyleItem::Stroke { arrows: Some(arrows), .. } = item else { continue };
+ for name in arrows.symbols() {
+ if self.arrowheads.contains_key(name) {
+ continue;
+ }
+ let symbol = self.symbol_names.get(name).and_then(|named| self.doc.symbols.iter().find(|s| &s.name == named));
+ if let Some(s) = symbol {
+ let head = crate::import::ai::arrowhead::head(name, &s.art).map(Arc::new);
+ self.arrowheads.insert(name.to_string(), head);
+ }
+ }
+ }
+ }
+ }
+
/// Brings [`Reader::brushes_kept`] up to date with the brushes and brush art read so far.
fn note_brushes_kept(&mut self) {
use super::super::brush;
@@ -818,6 +845,7 @@ impl<'a> Reader<'a> {
brushes: &self.brush_drafts,
kept: &self.brushes_kept.kept,
bending: &self.brushes_kept.bending,
+ arrowheads: &self.arrowheads,
space,
},
)
@@ -1061,6 +1089,8 @@ struct StylePaints<'a> {
kept: &'a [bool],
/// The art an Art brush draws as the file does, with its length ([`super::super::brush::bending_art`]).
bending: &'a HashMap,
+ /// The heads of the arrowhead symbols strokes name ([`Reader::arrowheads`]).
+ arrowheads: &'a HashMap>>,
space: Affine,
}
@@ -1411,7 +1441,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
return None;
}
}
- stroke_layer(item)?
+ stroke_layer(item, paints.arrowheads)?
}
};
if let Some(look) = st.looks.get(n) {
@@ -1430,6 +1460,88 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
if !slot && st.effects.iter().any(|e| e.id == "distort.zigZag") && !draws_look_outline(object, &appearance, look) {
return None;
}
+ heads_placed(object, look, appearance, paints.space)
+}
+
+/// What `appearance` paints on path or compound path `object`: its fills' outline and its strokes'
+/// areas, heads included, measured exactly (a node's visual bounds allow a head its whole reach on
+/// every side). `None` for another object or an appearance that paints nothing.
+fn painted_bounds(object: &Node, appearance: &Appearance) -> Option {
+ let (path, rule) = match &object.kind {
+ NodeKind::Path { path, rule, .. } => (path.clone(), *rule),
+ NodeKind::Compound { children, rule } => {
+ (PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule)
+ }
+ _ => return None,
+ };
+ let mut out = None;
+ for item in &appearance.items {
+ let painted = match item {
+ AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(),
+ AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(),
+ _ => None,
+ };
+ out = vectorcraft_geom::union_opt(out, painted);
+ }
+ out
+}
+
+/// `appearance` (on `object`, whose drawn look is `look`, in a space `space` takes to the
+/// document) with its strokes' arrowheads placed as the look draws them: the tips on the ends of
+/// the path, or past them by the line's length under each head (Extend), whichever gives the
+/// object the look's bounds within a quarter of the least distance a head moves between the two
+/// (at least 0.05 pt, at most 0.5 pt). `None`
+/// when neither does (the file draws the heads elsewhere: on other subpaths, say), or when both do
+/// and any head moves 0.2 pt or more between them (the bounds can't tell which the file draws).
+fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: Affine) -> Option {
+ let k = space.determinant().abs().sqrt();
+ let k = if k.is_finite() && k > 0.0 { k } else { 1.0 };
+ // How far each head moves between the placements (its line's length under it): the least and
+ // the most.
+ let (mut shift, mut most) = (f64::INFINITY, 0.0f64);
+ for item in &appearance.items {
+ let AppearanceItem::Stroke(s) = item else { continue };
+ for (head, end) in [(&s.start_arrow, false), (&s.end_arrow, true)] {
+ if let Some(Arrowhead::Custom(c)) = head {
+ let moves = c.stop() * s.arrow_weight(end) * k;
+ (shift, most) = (shift.min(moves), most.max(moves));
+ }
+ }
+ }
+ if shift.is_infinite() {
+ return Some(appearance);
+ }
+ let want = look.visual_bounds()?;
+ // Well under the distance between the placements, and under half a point: a look without
+ // those heads, or with them elsewhere, is off by more.
+ let tolerance = (shift / 4.0).clamp(0.05, 0.5);
+ let mut fits = vec![];
+ for align in [ArrowAlign::Tip, ArrowAlign::Extend] {
+ for item in &mut appearance.items {
+ if let AppearanceItem::Stroke(s) = item {
+ s.arrow_align = align;
+ }
+ }
+ let mut scaled = appearance.clone();
+ scaled.scale_strokes(k);
+ let got = painted_bounds(object, &scaled)?;
+ let off = [got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().fold(0.0f64, |m, d| m.max(d.abs()));
+ if off <= tolerance {
+ fits.push(align);
+ }
+ }
+ // Both fit when the bounds can't tell the placements apart (the end inside the bounds of the
+ // line's other segments), unless every head moves so little that either draws alike.
+ let align = match fits.as_slice() {
+ [one] => *one,
+ [first, _] if most < 0.2 => *first,
+ _ => return None,
+ };
+ for item in &mut appearance.items {
+ if let AppearanceItem::Stroke(s) = item {
+ s.arrow_align = align;
+ }
+ }
Some(appearance)
}
@@ -1559,7 +1671,11 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo
/// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]).
/// A style keeps only its gradients' names and angles, so each one's gradient, by VectorCraft's own
/// rule, is fitted to the bounds of whatever object the style is applied to, at its angle.
-pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, gradients: &HashMap) -> Option {
+pub(super) fn appearance_from_art_style(
+ st: &crate::import::ai::style::ArtStyle,
+ gradients: &HashMap,
+ arrowheads: &HashMap>>,
+) -> Option {
use crate::import::ai::style::StyleItem;
if !st.plain {
return None;
@@ -1574,7 +1690,7 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle,
StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())),
// A graphic style's brush isn't checked against the file's brushes: it is left out.
StyleItem::Stroke { brush: Some(_), .. } => return None,
- StyleItem::Stroke { .. } => stroke_layer(item)?,
+ StyleItem::Stroke { .. } => stroke_layer(item, arrowheads)?,
StyleItem::Gradient { name, angle } => AppearanceItem::Fill(FillLayer::new(named_gradient(name.as_deref()?, *angle, gradients)?)),
StyleItem::Pattern { .. } => return None,
};
@@ -1665,7 +1781,7 @@ pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Pain
.collect();
// No gradient is taken by name: on an object, one that isn't its own is placed where its drawn
// look has it.
- let mut appearance = appearance_from_art_style(&st, &HashMap::new())?;
+ let mut appearance = appearance_from_art_style(&st, &HashMap::new(), &HashMap::new())?;
for (item, brush) in appearance.items.iter_mut().zip(brushes) {
if let (AppearanceItem::Stroke(s), Some(brush)) = (item, brush) {
s.brush = Some(brush);
@@ -1680,12 +1796,27 @@ pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool {
!parsed.style.moves_outline() || moves_with(object, &parsed.style)
}
-/// A style's stroke as an appearance item (`None` for a fill).
-fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option {
- let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush } = item else { return None };
+/// A style's stroke as an appearance item, its arrowheads the heads of `arrowheads` by symbol
+/// name, each tip on its end of the path (where [`heads_placed`] finds the file draws them on an
+/// object; a graphic style keeps that). `None` for a fill, or for a stroke
+/// whose arrowhead symbol has no head there or whose head's weight would be under the least one
+/// draws at ([`StrokeLayer::arrow_weight`]), so the head would draw larger than in the file.
+fn stroke_layer(item: &crate::import::ai::style::StyleItem, arrowheads: &HashMap>>) -> Option {
+ let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush, arrows } = item else {
+ return None;
+ };
let mut layer = StrokeLayer::new(paint.clone(), line_width(*width));
(layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile, layer.align) = (*cap, *join, *miter, dash.clone(), profile.clone(), *align);
layer.brush = brush.as_ref().map(|(name, _)| name.clone());
+ if let Some(arrows) = arrows {
+ let head = |end: &Option<(String, f64)>| -> Option<(Option, f64)> {
+ let Some((name, pct)) = end else { return Some((None, 100.0)) };
+ let head = arrowheads.get(name)?.clone()?;
+ (layer.width * pct / 100.0 >= StrokeLayer::LEAST_ARROW_WEIGHT).then_some((Some(Arrowhead::Custom(head)), *pct))
+ };
+ let ((start, start_pct), (end, end_pct)) = (head(&arrows.start)?, head(&arrows.end)?);
+ (layer.start_arrow, layer.end_arrow, layer.arrow_scale, layer.arrow_align) = (start, end, (start_pct, end_pct), ArrowAlign::Tip);
+ }
Some(AppearanceItem::Stroke(layer))
}
@@ -1914,6 +2045,7 @@ mod tests {
brushes: &brushes,
kept: &[true],
bending: &bending,
+ arrowheads: &HashMap::new(),
space: Affine::IDENTITY,
};
let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]);
@@ -1960,6 +2092,7 @@ mod tests {
brushes: &[],
kept: &[],
bending: &bending,
+ arrowheads: &HashMap::new(),
space: Affine::IDENTITY,
};
let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]);
diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs
index 4941fd62b8..d8ddfd5e4f 100644
--- a/crates/eps/src/import/ai/style.rs
+++ b/crates/eps/src/import/ai/style.rs
@@ -230,6 +230,8 @@ impl ArtStyle {
}
}
+// A stroke takes about 300 bytes and the other items about 100; a style holds a few of each.
+#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub(super) enum StyleItem {
Fill(Paint),
@@ -258,9 +260,35 @@ pub(super) enum StyleItem {
align: StrokeAlign,
/// A brush: its name, and its settings for this object.
brush: Option<(String, PathBrush)>,
+ /// Its arrowheads, as symbols of the file (`None`: it has none).
+ arrows: Option>,
},
}
+/// A stroke's arrowheads: each end's symbol (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)`
+/// or `(BSArrowEndSymbol)` in the stroke's dictionary) by its name in the file, with its scale in
+/// percent (`BSArrowBeginScale`, `BSArrowEndScale`; 100 without one). The symbol's art is the head
+/// and a sample of the line it ends, which `read::ops` reads into a head once the symbols are read.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub(super) struct StrokeArrows {
+ pub start: Option<(String, f64)>,
+ pub end: Option<(String, f64)>,
+}
+
+impl StrokeArrows {
+ /// The names of the symbols, start first.
+ pub fn symbols(&self) -> impl Iterator {
+ [&self.start, &self.end].into_iter().flatten().map(|(name, _)| name.as_str())
+ }
+}
+
+/// The arrowhead entries of a stroke's dictionary that [`stroke_arrows`] reads. Beside heads, any
+/// other entry whose key starts with `BSArrow` isn't read, so the stroke keeps its drawn look.
+const ARROW_ENTRIES: [&str; 4] = ["BSArrowBeginSymbol", "BSArrowEndSymbol", "BSArrowBeginScale", "BSArrowEndScale"];
+
+/// The scales an arrowhead takes, in percent.
+const ARROW_SCALES: std::ops::RangeInclusive = 1.0..=1000.0;
+
/// A fill's or stroke's own state in the stack.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct ItemLook {
@@ -320,6 +348,9 @@ struct Filter {
/// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and
/// plug-in name.
plugin_object: Option<(String, String)>,
+ /// The symbols its dictionary refers to (`/GObjRef : (name) /SymbolArt ; (key) ,`): each one's
+ /// name, by key.
+ symbols: HashMap,
/// `mode opacity … Xy`.
xy: Option<(usize, f32)>,
/// `… isolate knockout … Xy`.
@@ -352,6 +383,7 @@ impl Default for Filter {
pattern: None,
fill_last: LastPaint::None,
plugin_object: None,
+ symbols: HashMap::new(),
xy: None,
xy_group: None,
data: None,
@@ -533,6 +565,11 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap dict_array = Some(vec![]),
+ // A symbol the dictionary refers to: `/GObjRef : (name) /SymbolArt ; (key) ,`.
+ b"SymbolArt" => {
+ symbol_entry(&mut lex, &mut operands, &mut other_entry, names, filters.last_mut().filter(|_| in_basic));
+ continue;
+ }
b"PluginObject" if in_basic => {
let mut texts = operands.iter().rev().filter_map(|v| names.text(v));
if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) {
@@ -891,6 +928,7 @@ impl OnePaint {
profile: None,
align: StrokeAlign::Center,
brush: None,
+ arrows: None,
}),
_ => return Err(()),
}
@@ -1485,11 +1523,68 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result