Live Paint: a Bucket drag from an edge strokes every edge it crosses

A press on an edge (Shift with Paint Fills alone, or a plain press with
Paint Strokes on) now starts a drag, as a press on a face does. The drag
paints the edge and every visible edge of the same group that it crosses
or comes within 0.0001 pt of, between pointer events and on the release,
as one undo step; Escape cancels it. Edges of other groups and hidden
edges keep their strokes, a drag over edges that already have the stroke
records no undo step, and a drag that starts on a face still fills only
faces. A double-click after such a drag joins through the edges the drag
stroked as the paint they had before it.

livePaint.strokeEdge takes the drag's points and continuation as
livePaint.fill does, and both refuse them with scope connected or
samePaint.

Help page: https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html
This commit is contained in:
dotCooCoo
2026-11-16 05:32:00 -08:00
parent 7452b6f383
commit ebeffa15ab
9 changed files with 475 additions and 76 deletions
+1 -1
View File
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Live Paint Bucket (Stroke)",
[],
None,
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; also paints every edge of the group, hidden edges skipped, that the polyline crosses or comes within 0.0001 pt of), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), through?: [id…] (scope connected only; at most 4096 of the group's edges, each given once, counted as drawing with stroke paint match whatever they draw with, such as another edge a double-click's clicks painted; any other id is an error), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached has its strokes replaced by one stroke with the paint and width, shown, fully opaque and blending normally, in the place of its topmost stroke and with the dashes, caps and arrowheads of its topmost shown stroke (a new stroke above the fills when it has none; none leaves one stroke of none), and its fills stay as they are; when every edge it reaches already has only that one stroke (at any width for none), nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
has_doc,
lp_stroke_edge
),
+49 -22
View File
@@ -409,43 +409,61 @@ fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
/// The drag path of `livePaint.fill` or `livePaint.strokeEdge` (command `c`) pressed at `start`:
/// `points` followed by each chunk of `continuation`, where every chunk holds 1 to
/// [`b::LP_FILL_CHUNK_POINTS`] finite canvas points and starts at the last point of the chunk
/// before it (`points` at `start`). None when `points` is left out. With a `scope` other than
/// `one`, `points` is an error.
fn path_param(p: &Value, c: &str, start: Point, scope: LpScope) -> Result<Option<Vec<Vec<Point>>>> {
if scope != LpScope::One && p.get("points").is_some() {
return Err(bad(C, "scope applies to a click: leave out points"));
return Err(bad(c, "scope applies to a click: leave out points"));
}
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
let values = input
.as_array()
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
.ok_or_else(|| bad(c, "each path chunk must contain 1 to 4096 points"))?;
let points: Vec<_> = values
.iter()
.map(|point| {
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(c, "points must be [x,y] pairs"))?;
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(c, "point x must be a number"))?;
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(c, "point y must be a number"))?;
let point = Point::new(x, y);
if !finite(point) {
return Err(bad(C, "points must be finite canvas points"));
return Err(bad(c, "points must be finite canvas points"));
}
Ok(point)
})
.collect::<Result<_>>()?;
if points.first() != Some(&start) {
return Err(bad(C, "path chunks must share their boundary point"));
return Err(bad(c, "path chunks must share their boundary point"));
}
Ok(points)
};
let points = p.get("points");
let Some(points) = p.get("points") else {
return if p.get("continuation").is_some() { Err(bad(c, "continuation requires points")) } else { Ok(None) };
};
let continuation = match p.get("continuation") {
None => &[][..],
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
Some(_) => return Err(bad(C, "continuation requires points")),
Some(input) => input.as_array().ok_or_else(|| bad(c, "continuation must be an array of path chunks"))?.as_slice(),
};
let mut chunks: Vec<Vec<Point>> = Vec::with_capacity(continuation.len() + 1);
let mut last = start;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
chunks.push(chunk);
}
Ok(Some(chunks))
}
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "livePaint.fill";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
crate::cmd::paint::check_keep_model(p, C)?;
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
let group = object_param(p, "group", C)?;
@@ -472,7 +490,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
}
}
if let Some(points) = points {
if let Some(chunks) = &path {
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
// Use the existing region-crossing probes, so even a face narrower than the distance
// between pointer events is filled. Reversing matches visible_face_at's front first.
@@ -488,11 +506,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let map = b::BuilderMap { regions, ..Default::default() };
let mut last = pt;
for input in std::iter::once(points).chain(continuation) {
let chunk = parse_chunk(input, last)?;
last = chunk.last().copied().unwrap_or(last);
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
for chunk in chunks {
targets.extend(map.hits_along(chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
}
}
Ok((fid, targets))
@@ -567,6 +582,7 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
let scope = scope_param(p, C)?;
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
let path = path_param(p, C, pt, scope)?;
let through: Vec<NodeId> = match p.get("through") {
None => vec![],
Some(_) if scope != LpScope::Connected => return Err(bad(C, "through applies to scope \"connected\"")),
@@ -590,7 +606,18 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
let eid = start.id;
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
let targets = match scope {
LpScope::One => vec![eid],
// A drag also reaches every edge of the group that is not hidden and that its path
// crosses or touches.
LpScope::One => std::iter::once(eid)
.chain(
path.as_deref()
.map(|chunks| b::visible_edges_along(n, chunks))
.unwrap_or_default()
.into_iter()
.map(|e| e.id)
.filter(|id| *id != eid),
)
.collect(),
LpScope::Connected => b::connected_edges_through(n, eid, &like, &through),
LpScope::SamePaint => std::iter::once(eid)
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
+131
View File
@@ -5198,6 +5198,137 @@ fn live_paint_bucket_drag_rejects_invalid_points_atomically() {
}
}
/// The edge of `g` through (`x`, 25), halfway up the squares of [`live_squares`].
fn vertical_edge(s: &Session, g: NodeId, x: f64) -> NodeId {
vectorcraft_tools::builder::edge_near(&node(s, g), Point::new(x, 25.0), 0.5).map(|e| e.id).unwrap_or_else(|| panic!("an edge at x {x}"))
}
/// A Shift-drag from an edge strokes every visible edge of that group the drag crosses, between
/// pointer events and on the release too, as one undo step that Escape cancels; hidden edges and
/// another group's edges keep their strokes.
#[test]
fn live_paint_bucket_drag_strokes_crossed_edges_as_one_undo() {
for cancel in [false, true] {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0, 150.0, 200.0]);
let other = live_squares(&mut s, &[300.0]);
let black = Paint::solid(Color::rgb(0.0, 0.0, 0.0));
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all: Vec<NodeId> = [g, other].iter().flat_map(|g| edges_in(&s, *g, Rect::new(-1.0, -1.0, 351.0, 51.0))).collect();
paint_parts(&mut s, &all, &black, &[]);
let hidden = vertical_edge(&s, g, 100.0);
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
Ok(())
})
.unwrap();
let before = s.doc().unwrap().doc.clone();
let depth = s.doc().unwrap().history.undo.len();
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green.clone();
s.paint.stroke_width = 3.0;
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 25.0).with_mods(shift), v).unwrap();
// Past the hidden edge and the edge at 150, then back across it, between pointer events.
s.pointer(&PointerEvent::new(PointerKind::Drag, 160.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 140.0, 30.0).with_mods(shift), v).unwrap();
if cancel {
assert!(s.tool_busy());
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
assert!(!s.tool_busy());
}
// The release crosses the edges at 200 and 250 and goes on into the other group.
s.pointer(&PointerEvent::new(PointerKind::Up, 325.0, 25.0).with_mods(shift), v).unwrap();
if cancel {
assert!(s.doc().unwrap().doc == before, "Escape cancels the whole drag");
assert_eq!(s.doc().unwrap().history.undo.len(), depth);
continue;
}
let stroke = |s: &Session, id: NodeId| {
let n = node(s, id);
(n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width))
};
for x in [50.0, 150.0, 200.0, 250.0] {
assert_eq!(stroke(&s, vertical_edge(&s, g, x)), (green.clone(), Some(3.0)), "edge at {x}");
}
for (group, x) in [(g, 0.0), (g, 100.0), (other, 300.0), (other, 350.0)] {
assert_eq!(stroke(&s, vertical_edge(&s, group, x)), (black.clone(), Some(1.0)), "edge at {x}");
}
for e in edges_in(&s, g, Rect::new(-1.0, -1.0, 201.0, 1.0)) {
assert_eq!(stroke(&s, e).0, black, "a top edge is not crossed");
}
assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before, "one Undo restores every edge");
}
}
/// A stroke drag over edges that already have the stroke records no undo step and keeps the redo
/// steps.
#[test]
fn live_paint_bucket_stroke_drag_no_op_keeps_history() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0]);
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let all = edges_in(&s, g, Rect::new(-1.0, -1.0, 101.0, 51.0));
paint_parts(&mut s, &all, &green, &[]);
paint_parts(&mut s, &all, &green, &[]);
s.execute("edit.undo", &json!({})).unwrap();
let before = s.doc().unwrap().doc.clone();
let (undo, redo) = (s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len());
assert_eq!(redo, 1);
let v = ViewInfo::default();
s.select_tool("livePaintBucket", v).unwrap();
s.paint.stroke = green;
s.paint.stroke_width = 1.0;
let shift = Mods { shift: true, ..Default::default() };
s.pointer(&PointerEvent::new(PointerKind::Down, 0.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 60.0, 25.0).with_mods(shift), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 110.0, 25.0).with_mods(shift), v).unwrap();
assert!(s.doc().unwrap().doc == before);
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().history.redo.len()), (undo, redo));
}
/// `livePaint.strokeEdge` with `points` paints the crossed edges, counting the edge at the point;
/// a malformed path or a scope other than "one" with `points` is an error that changes nothing.
#[test]
fn live_paint_stroke_drag_rejects_invalid_points_atomically() {
let mut s = session();
let g = live_squares(&mut s, &[0.0, 50.0, 100.0]);
let before = s.doc().unwrap().doc.clone();
let stroke = |s: &mut Session, extra: Value| {
let mut p = json!({"group": g.0, "point": [50.0, 25.0], "color": "#00ff00"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("livePaint.strokeEdge", &p)
};
for points in
[json!([]), json!([[51.0, 25.0]]), json!([[50.0, 25.0], [null, 0]]), json!([[50.0, 25.0], [1e30, 0]]), json!(vec![[50.0, 25.0]; 4097])]
{
assert!(stroke(&mut s, json!({ "points": points })).is_err(), "{points}");
assert_eq!(s.doc().unwrap().doc, before);
}
for continuation in [json!(null), json!([[[51.0, 25.0], [125.0, 25.0]]]), json!([vec![[50.0, 25.0]; 4097]])] {
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0]], "continuation": continuation })).is_err(), "{continuation}");
assert_eq!(s.doc().unwrap().doc, before);
}
assert!(stroke(&mut s, json!({ "continuation": [[[50.0, 25.0]]] })).is_err());
for scope in ["connected", "samePaint"] {
assert!(stroke(&mut s, json!({ "points": [[50.0, 25.0], [125.0, 25.0]], "scope": scope })).is_err(), "{scope}");
}
assert_eq!(s.doc().unwrap().doc, before);
// A path in two chunks reaches the edges at 50, 100 and 150, not the one at 0.
let r = stroke(&mut s, json!({ "points": [[50.0, 25.0], [90.0, 25.0]], "continuation": [[[90.0, 25.0], [160.0, 25.0]]] })).unwrap();
assert_eq!(r["count"], 3);
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
for x in [50.0, 100.0, 150.0] {
assert_eq!(node(&s, vertical_edge(&s, g, x)).appearance.stroke_paint(), green, "edge at {x}");
}
assert_ne!(node(&s, vertical_edge(&s, g, 0.0)).appearance.stroke_paint(), green);
}
#[test]
fn live_paint_bucket_tool_fills_face() {
let mut s = session();