From 6c74a77a6d460a73f762cac8e06631a56a1f6b28 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 12:13:13 -0800 Subject: [PATCH] Eraser: an Alt-drag erases everything inside a marquee, a square with Shift With Alt held at the press, an Eraser drag draws a marquee from the press point to the pointer instead of a stroke, and the release erases everything inside it. Alt+Shift keeps the marquee square on its larger side, Escape cancels it, and a click or a drag along one axis erases nothing. path.eraseRegion takes {rect: [x, y, width, height]} in place of points. Closed paths lose the rectangle's area; open paths are cut where they cross its edges, found from the exact crossings, so a narrow rectangle across a long segment still cuts it. A width or height of 0 or less, a non-finite value, or points and rect together is an error, and nothing erased adds no undo step. Docs: docs/mcp.md, docs/ui-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/cut.rs | 82 +++++++++++++++++++++++-- crates/engine/src/tests/draw2.rs | 78 +++++++++++++++++++++++ crates/tools/src/draw2/gesture.rs | 74 ++++++++++++++++++++++ crates/tools/src/draw2/gesture/tests.rs | 76 +++++++++++++++++++++++ docs/mcp.md | 9 +++ docs/ui-parity.md | 1 + 7 files changed, 315 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 49e277e5a0..38ac35c61a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -92,7 +92,7 @@ pub fn specs() -> Vec { "Eraser", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} or {rect: [x, y, width, height] (pt; the Eraser's Alt-drag marquee)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing. `rect` in place of `points` erases everything inside the rectangle: closed paths lose its area, and open paths are cut where they cross its edges; the tip's size, angle, roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or `points` and `rect` together is an error. When nothing is erased, no undo step is added", has_doc, erase_region ), diff --git a/crates/engine/src/cmd/draw2/cut.rs b/crates/engine/src/cmd/draw2/cut.rs index 64b8bdee16..fca15e46c5 100644 --- a/crates/engine/src/cmd/draw2/cut.rs +++ b/crates/engine/src/cmd/draw2/cut.rs @@ -3,9 +3,10 @@ use super::common::{ samples_param, sibling_with, size_pressure, target_paths, usize_opt, }; use super::{ - Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session, + Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Rect, Result, Session, SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po, }; +use kurbo::{CubicBez, Line, PathSeg}; use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation}; use vectorcraft_doc::StrokeLayer; use vectorcraft_tools::draw2::MIN_BRUSH_SIZE; @@ -46,8 +47,8 @@ pub(in super::super) fn components(pd: &PathData) -> Vec { /// The pieces of `sp` where `remove(point)` is false. `None` when nothing is removed. Each segment /// is sampled at least every `step` pt (and at least 24 times), so a removed stretch at least -/// `step` long is found. -fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { +/// `step` long is found, and also at the parameters `extra` gives for it. +fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let nseg = sp.segment_count(); if nseg == 0 { return sp.anchors.first().filter(|a| remove(a.p)).map(|_| vec![]); @@ -64,6 +65,13 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio let edge = (c.p1 - c.p0).hypot().max((c.p2 - c.p1).hypot()).max((c.p3 - c.p2).hypot()); let wanted = (3.0 * edge / step).ceil(); let samples = if wanted.is_finite() && wanted > K as f64 { (wanted as usize).min(MAX_SAMPLES) } else { K }; + let mut ts: Vec = (1..=samples).map(|k| k as f64 / samples as f64).collect(); + let more = extra(c); + if !more.is_empty() { + ts.extend(more.into_iter().filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0)); + ts.sort_by(f64::total_cmp); + ts.dedup(); + } let mut prev_t = 0.0; let mut prev_rm = remove(c.eval(0.0)); let mut start = if prev_rm { None } else { Some(0.0) }; @@ -73,8 +81,7 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio runs.push(std::mem::take(&mut cur)); } } - for k in 1..=samples { - let t = k as f64 / samples as f64; + for t in ts { let rm = remove(c.eval(t)); if rm != prev_rm { let (mut lo, mut hi) = (prev_t, t); @@ -146,10 +153,15 @@ fn cut_subpath(sp: &SubPath, step: f64, remove: &dyn Fn(Point) -> bool) -> Optio /// every `step` pt (`f64::INFINITY` for the fixed sampling). Returns the new geometry per output /// object (one object per piece when the path had a single subpath), or None if unchanged. pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool) -> Option> { + erase_outline_at(pd, step, remove, &|_| vec![]) +} + +/// [`erase_outline`], also sampling each segment at the parameters `extra` gives for it. +fn erase_outline_at(pd: &PathData, step: f64, remove: &dyn Fn(Point) -> bool, extra: &dyn Fn(CubicBez) -> Vec) -> Option> { let mut changed = false; let mut subs = vec![]; for sp in &pd.subpaths { - match cut_subpath(sp, step, remove) { + match cut_subpath(sp, step, remove, extra) { Some(pieces) => { changed = true; subs.extend(pieces); @@ -274,6 +286,12 @@ pub(super) fn knife(s: &mut Session, p: &Value) -> Result { pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.eraseRegion"; + if let Some(rect) = p.get("rect").filter(|v| !v.is_null()) { + if p.get("points").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "give `points` or `rect`, not both")); + } + return erase_rect(s, marquee_param(rect, C)?); + } let samples = samples_param(p, "points", C)?; let size = number_or(p, "size", 10.0, C)?; if !(size.is_finite() && size > 0.0) { @@ -325,6 +343,58 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result { apply_plan(s, "Eraser", plan) } +/// `path.eraseRegion`'s `rect: [x, y, width, height]`: four finite numbers, with a width and a +/// height above 0. +fn marquee_param(v: &Value, cmd: &str) -> Result { + const SHAPE: &str = "rect is [x, y, width, height] in points, with a width and a height above 0"; + let n: Vec = match v.as_array() { + Some(a) if a.len() == 4 => a.iter().map(Value::as_f64).collect::>().ok_or_else(|| bad(cmd, SHAPE))?, + _ => return Err(bad(cmd, SHAPE)), + }; + let [x, y, w, h] = [n[0], n[1], n[2], n[3]]; + if !(n.iter().all(|v| v.is_finite()) && w > 0.0 && h > 0.0 && (x + w).is_finite() && (y + h).is_finite()) { + return Err(bad(cmd, SHAPE)); + } + Ok(Rect::new(x, y, x + w, y + h)) +} + +/// `path.eraseRegion` with a marquee: everything inside `r` is erased from the paths (selected, or +/// all). Closed paths lose the rectangle's area, and open paths are cut where they cross its edges. +fn erase_rect(s: &mut Session, r: Rect) -> Result { + let region = + PathData::single(SubPath::polyline(&[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)], true)); + let inside = |q: Point| q.x >= r.x0 && q.x <= r.x1 && q.y >= r.y0 && q.y <= r.y1; + // An open path is sampled at least every half of the rectangle's shorter side, and also where + // each segment crosses the rectangle's edges and halfway between those crossings, so a stretch + // inside the rectangle is found however long the segment is. + let step = r.width().min(r.height()) / 2.0; + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + let crossings = |c: CubicBez| { + let mut ts: Vec = (0..4) + .flat_map(|k| PathSeg::Cubic(c).intersect_line(Line::new(corners[k], corners[(k + 1) % 4]))) + .map(|x| x.segment_t) + .filter(|t| t.is_finite() && *t > 0.0 && *t < 1.0) + .collect(); + ts.sort_by(f64::total_cmp); + let mids: Vec = [0.0].iter().chain(&ts).zip(ts.iter().chain(&[1.0])).map(|(a, b)| 0.5 * (a + b)).collect(); + ts.extend(mids); + ts + }; + let st = s.doc()?; + let mut plan: Vec<(NodeId, Vec)> = vec![]; + for (id, pd, rule) in fill_targets(&st.doc, &st.selection, r)? { + if pd.is_closed() { + if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 { + continue; + } + plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference)))); + } else if let Some(pieces) = erase_outline_at(&pd, step, &inside, &crossings) { + plan.push((id, pieces)); + } + } + apply_plan(s, "Eraser", plan) +} + /// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and /// `sizeMode`. const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 45ff1f84c1..7698b9d2a7 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -1337,6 +1337,84 @@ fn eraser_removes_small_shape_entirely() { assert!(paths(&s).is_empty()); } +/// `path.eraseRegion {rect}` (the Eraser's Alt-drag marquee) erases everything inside the +/// rectangle: a closed shape loses its area, an open path is cut where it crosses the edges, a +/// shape wholly inside goes, and only the selected paths take part when something is selected. One +/// undo step puts everything back, and a rectangle that touches nothing adds no undo step. +#[test] +fn erase_region_rect_erases_everything_inside_it() { + let filled = |s: &Session, x: f64, y: f64| { + paths(s).iter().any(|(_, pd)| pd.is_closed() && vectorcraft_geom::hit::fill_contains(&pd.to_bezpath(), FillRule::NonZero, Point::new(x, y))) + }; + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + rect(&mut s, 180.0, 140.0, 10.0, 10.0); + line(&mut s, 50.0, 150.0, 350.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let undo = undo_steps(&s); + let r = s.execute("path.eraseRegion", &json!({"rect": [150, 120, 100, 60]})).unwrap(); + assert!(!r["ids"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(undo_steps(&s), undo + 1); + assert!(!filled(&s, 200.0, 150.0) && !filled(&s, 185.0, 145.0), "the area inside is erased, the small square with it"); + assert!(filled(&s, 120.0, 150.0) && filled(&s, 200.0, 250.0) && filled(&s, 200.0, 110.0), "the rest stays filled"); + let ps = paths(&s); + assert_eq!(ps.iter().filter(|(_, pd)| pd.is_closed()).count(), 1, "the square keeps the rectangle as a hole: {ps:?}"); + let open: Vec = ps.iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2, "the line is cut in two: {open:?}"); + assert!(open.iter().all(|l| (l - 100.0).abs() < 0.01), "{open:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(paths(&s).len(), 3); + assert!(filled(&s, 200.0, 160.0) && filled(&s, 185.0, 145.0)); + // A rectangle away from the art erases nothing and adds no undo step. + let undo = undo_steps(&s); + assert_eq!(s.execute("path.eraseRegion", &json!({"rect": [500, 500, 10, 10]})).unwrap(), json!({"ids": []})); + assert_eq!(undo_steps(&s), undo); + // With the line selected, only the line is erased. + let ln = paths(&s).into_iter().find(|(_, pd)| !pd.is_closed()).unwrap().0; + s.execute("select.set", &json!({"ids": [ln.0]})).unwrap(); + let closed: Vec = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + s.execute("path.eraseRegion", &json!({"rect": [90, 100, 30, 100]})).unwrap(); + let after: Vec = paths(&s).into_iter().filter(|(_, pd)| pd.is_closed()).map(|(_, pd)| pd).collect(); + assert_eq!(after, closed, "the unselected squares are unchanged"); + let open: Vec = paths(&s).iter().filter(|(_, pd)| !pd.is_closed()).map(|(_, pd)| pd.length()).collect(); + assert_eq!(open.len(), 2); + assert!((open.iter().sum::() - 270.0).abs() < 0.01, "{open:?}"); +} + +/// A narrow `path.eraseRegion {rect}` across a long open path cuts it, wherever the rectangle +/// falls between the samples the path's length would give. +#[test] +fn erase_region_rect_cuts_a_long_line_with_a_narrow_rectangle() { + let mut s = session(); + line(&mut s, 0.0, 100.0, 10000.0, 100.0); + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.eraseRegion", &json!({"rect": [5000.3, 90, 1, 20]})).unwrap(); + let mut open: Vec = paths(&s).iter().map(|(_, pd)| pd.length()).collect(); + open.sort_by(f64::total_cmp); + assert_eq!(open.len(), 2, "{open:?}"); + assert!((open[0] - 4998.7).abs() < 0.01 && (open[1] - 5000.3).abs() < 0.01, "{open:?}"); +} + +/// `path.eraseRegion` refuses a `rect` that is not four finite numbers with a width and a height +/// above 0, and `rect` given with `points`, and changes nothing. +#[test] +fn erase_region_rect_refuses_bad_values() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let shape = "rect is [x, y, width, height] in points, with a width and a height above 0"; + for p in [ + json!({"rect": [10, 10, 0, 20]}), + json!({"rect": [10, 10, 20, -5]}), + json!({"rect": [10, 10, 20]}), + json!({"rect": [10, "10", 20, 20]}), + json!({"rect": [1e308, 0, 1e308, 20]}), + json!({"rect": {"x": 10, "y": 10, "width": 20, "height": 20}}), + ] { + refuses_with(&mut s, "path.eraseRegion", &p, shape); + } + refuses_with(&mut s, "path.eraseRegion", &json!({"rect": [10, 10, 20, 20], "points": [[0, 0]]}), "give `points` or `rect`, not both"); +} + /// #4495: the Eraser cuts a compound path as one shape: its hole stays empty, the erased area is /// empty, and the rest stays filled, with either fill rule. A notch inside the ring keeps one /// compound path; a drag through the whole ring leaves compound paths whose holes stay holes. diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index a1f1785923..b732fef063 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -22,6 +22,8 @@ //! has moved, switches the Blob Brush to the Smooth tool: the drag smooths the selected paths. //! Alt held at a Paintbrush press with a selected path also smooths; Alt pressed after its stroke //! begins closes the path on release. +//! Alt held at the Eraser's press draws a marquee instead of a stroke, a square while Shift is +//! held, and the release erases everything inside it. //! Alt held at the Knife's press makes it cut along the straight line from the press point to the //! pointer, even if Alt is released during the drag. Shift on each drag or release constrains that //! line to 45° steps from the canvas axes. @@ -163,6 +165,11 @@ pub struct GestureTool { /// The pointer has moved from the press point, by any distance (a move too short to add a /// point counts). moved: bool, + /// Active Eraser drag draws a marquee (Alt held at the press): the release erases the + /// rectangle from the press point to the pointer, a square while Shift is held. + marquee: bool, + /// Shift was held at the last event of the Eraser's marquee drag. + square: bool, /// Active Pencil drag draws a straight line (Shift or Alt held at the press), or active Knife /// drag cuts along one (Alt held at the press): the stroke is the press point and the pointer. straight: bool, @@ -867,6 +874,8 @@ impl GestureTool { smooth_fidelity: SMOOTH_FIDELITY, smoothing: false, moved: false, + marquee: false, + square: false, straight: false, unconstrained: false, shift_line: None, @@ -980,6 +989,11 @@ impl GestureTool { self.id == "blobBrush" && m.alt && !self.moved } + /// Would a press with `m` held draw the Eraser's marquee? Alt held at the press. + fn alt_marquee(&self, m: Mods) -> bool { + self.id == "eraser" && m.alt + } + /// Shift keeps an active straight Knife cut at 45° steps; without Shift it follows the pointer. /// Releasing Alt does not end a straight cut. fn knife_shift(&mut self, m: Mods) { @@ -1043,6 +1057,43 @@ impl GestureTool { ] } + /// The Eraser's marquee: the rectangle from the press point to the pointer, or with Shift held + /// the square on the larger of its sides, in the direction the pointer went. `None` outside a + /// marquee drag. + fn marquee_rect(&self) -> Option { + let (&a, &b) = (self.points.first()?, self.points.last()?); + if !self.marquee { + return None; + } + let d = b - a; + let b = if self.square { + let side = d.x.abs().max(d.y.abs()); + a + Vec2::new(side.copysign(d.x), side.copysign(d.y)) + } else { + b + }; + Some(Rect::from_points(a, b)) + } + + /// A drag or the release of the Eraser's marquee: the marquee runs from the press point to the + /// pointer, and the release erases it. `None` for any other event. + fn marquee_pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { + if !(self.active && self.marquee && matches!(ev.kind, PointerKind::Drag | PointerKind::Up)) { + return None; + } + self.square = ev.mods.shift; + self.points.truncate(1); + self.points.push(ev.pos); + if !matches!(ev.kind, PointerKind::Up) { + return Some(vec![]); + } + let out = self.finish(cx, ev.mods); + self.active = false; + self.marquee = false; + self.clear(); + Some(out) + } + /// Forget the stroke. fn clear(&mut self) { self.moved = false; @@ -1329,6 +1380,13 @@ impl GestureTool { } return vec![]; } + if let Some(r) = self.marquee_rect() { + // A click, or a drag along one axis, encloses no area: nothing is erased. + if r.width() <= 0.0 || r.height() <= 0.0 || r.width().max(r.height()) < cx.tol(1.0) { + return vec![]; + } + return vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [r.x0, r.y0, r.width(), r.height()]}))]; + } match self.id { "pencil" | "paintbrush" => { if !self.began { @@ -1404,6 +1462,9 @@ impl Tool for GestureTool { if self.varies_size() { self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p); } + if let Some(out) = self.marquee_pointer(cx, ev) { + return out; + } match ev.kind { PointerKind::Down => { self.active = true; @@ -1420,6 +1481,9 @@ impl Tool for GestureTool { // too, the line keeps Shift's 45° steps. Alt makes the Knife cut along a straight line. self.straight = (self.id == "pencil" && !self.smoothing && (ev.mods.shift || ev.mods.alt)) || (self.id == "knife" && ev.mods.alt); self.unconstrained = self.straight && !ev.mods.shift; + // Alt makes the Eraser draw a marquee, and Shift keeps it square. + self.marquee = self.alt_marquee(ev.mods); + self.square = ev.mods.shift; let extend = if self.draws_path() && !self.smoothing { self.find_extend(cx, p) } else { None }; self.set_extend(cx, extend); // The stroke's previews select the path it continues, so the others are kept now. @@ -1601,6 +1665,7 @@ impl Tool for GestureTool { self.smoothing = false; self.straight = false; self.unconstrained = false; + self.marquee = false; self.clear(); if began { vec![Action::Cancel] } else { vec![] } } @@ -1633,6 +1698,7 @@ impl Tool for GestureTool { self.smoothing = false; self.straight = false; self.unconstrained = false; + self.marquee = false; self.clear(); if began { stale.into_iter().chain([Action::Commit]).collect() } else { vec![] } } @@ -1640,6 +1706,14 @@ impl Tool for GestureTool { self.area_pending.set(false); self.band_pending.set(false); let mut o = self.snap.guides().to_vec(); + // The Eraser's marquee shows without the tip outline. + if self.active + && self.points.len() >= 2 + && let Some(r) = self.marquee_rect() + { + o.push(Overlay::Marquee(r)); + return o; + } // A path being drawn shows itself, except with the Pencil's Live preview off. if !self.active || self.points.len() < 2 || (self.began && self.previews()) { o.extend(self.tip_outline(cx)); diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..0d7d06427e 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2032,6 +2032,82 @@ fn eraser_and_knife_exec_on_release() { assert!(matches!(&a[0], Action::Exec(c, v) if c == "path.knife" && v["points"].as_array().unwrap().len() == 3)); } +/// An Alt-drag with the Eraser shows a marquee from the press point to the pointer, without the +/// tip outline, and the release erases that rectangle; a drag back up and left gives the same +/// kind of rectangle, measured from its top-left corner. +#[test] +fn eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 170.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 190.0).with_mods(alt)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(50.0, 150.0, 250.0, 190.0))]); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 250.0, 200.0).with_mods(alt)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [50.0, 150.0, 200.0, 50.0]}))]); + assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_)))); + // A click erases nothing. + let acts = drag_held(&mut t, &cx, &[(250.0, 200.0)], alt); + assert!(acts.iter().all(Vec::is_empty), "a click: {acts:?}"); + // Alt only at the press is enough, and the drag can go up and left of the press point. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 250.0, 200.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 120.0)); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 100.0, 120.0)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 120.0, 150.0, 80.0]}))]); + // Without Alt the drag is a stroke. + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v.get("rect").is_none() && v["points"].is_array())); +} + +/// Alt+Shift keeps the Eraser's marquee square on its larger side, in the direction the pointer +/// went; Shift can be pressed or let go during the drag. +#[test] +fn eraser_alt_shift_drag_keeps_the_marquee_square() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let alt_shift = Mods { alt: true, shift: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(alt_shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt_shift)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 140.0, 260.0, 200.0))]); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 170.0).with_mods(alt)); + assert_eq!(t.overlays(&cx), vec![Overlay::Marquee(Rect::new(200.0, 170.0, 260.0, 200.0))], "Shift let go"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 190.0, 280.0).with_mods(alt_shift)); + assert_eq!(acts, vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [120.0, 200.0, 80.0, 80.0]}))]); + // A drag along one axis gives a square too. + let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 140.0)], alt_shift); + assert_eq!(acts[2], vec![Action::Exec("path.eraseRegion".into(), json!({"rect": [100.0, 100.0, 40.0, 40.0]}))]); +} + +/// A marquee that encloses no area erases nothing, and Escape during the drag cancels the marquee: +/// the release that follows sends nothing. +#[test] +fn eraser_marquee_click_or_escape_erases_nothing() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = GestureTool::new("eraser"); + let acts = drag_held(&mut t, &cx, &[(100.0, 100.0), (100.0, 160.0)], alt); + assert!(acts.iter().all(Vec::is_empty), "a drag along one axis: {acts:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(alt)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(alt)); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![]); + assert!(!t.busy() && t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Marquee(_)))); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(alt)), vec![]); + // The next plain drag erases a stroke. + let acts = drag(&mut t, &cx, &[(50.0, 150.0), (250.0, 150.0)], Mods::default()); + assert!(matches!(&acts[2][0], Action::Exec(c, v) if c == "path.eraseRegion" && v["points"].is_array())); +} + /// The points of the Knife's release command. fn knife_points(acts: &[Action]) -> Vec<(f64, f64)> { let Some(Action::Exec(c, v)) = acts.first() else { panic!("{acts:?}") }; diff --git a/docs/mcp.md b/docs/mcp.md index e623b86cac..d23f7aa3c4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5748,6 +5748,15 @@ The command refuses another mode, and a variation below 0 or past its range, and the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. `tool.setOption {tool: "eraser"}` takes the same keys. +`path.eraseRegion {rect: [x, y, width, height]}` takes a rectangle in place of `points` and erases everything inside +it from the paths (selected, or all), as an Alt-drag with the Eraser does ([Eraser tool +reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133)). +Closed shapes lose the rectangle's area, and open paths are cut where they cross its edges. The tip's size, angle, +roundness and variations do not apply. A width or height of 0 or less, a value that is not a finite number, or +`points` and `rect` together is refused, and when nothing is erased no undo step is added. In the desktop app an +Alt-drag with the Eraser draws the marquee from the press point to the pointer, Alt+Shift keeps it square on its +larger side, and Escape cancels it. + These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in `path.reshapeSegment` and `object.blend.spine.reshapeSegment`; `x`, `y` and `t` in `path.curvatureEdit`; `x` and `y` diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 071c8d4719..0a88043c3e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -169,6 +169,7 @@ tools, never checked side by side) isn't captured row by row. | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | | Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). | +| Eraser: an Alt-drag draws a marquee and the release erases everything inside it (closed shapes lose the rectangle's area, open paths are cut where they cross its edges); Alt+Shift keeps the marquee square; Escape cancels it, and a click erases nothing | done | `path.eraseRegion {rect}`; [public behavior reference](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133); `eraser_alt_drag_draws_a_marquee_and_erases_the_rectangle`, `eraser_alt_shift_drag_keeps_the_marquee_square`, `eraser_marquee_click_or_escape_erases_nothing`, `erase_region_rect_erases_everything_inside_it`, `erase_region_rect_refuses_bad_values` | | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain |