diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9538d645..71a03c96 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -19,7 +19,7 @@ shaders or SDK code). | Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) | | Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) | | emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) | -| `assets/icons/anicraft-*.svg` (36 files: align, distribute, layer, the parenting view, mask and masked layer, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, asset warp, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage, and seven panel icons: properties, swatches, library, explorer, history, output, actions) | Align panel, layer-type, the timeline's Parenting View toggle, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone, Bind and Asset Warp tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage, panel icons in docks collapsed to icons (ADR 0087) | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | +| `assets/icons/anicraft-*.svg` (37 files: align, distribute, layer, the parenting view, mask and masked layer, lasso tool, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, asset warp, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage, and seven panel icons: properties, swatches, library, explorer, history, output, actions) | Align panel, layer-type, the timeline's Parenting View toggle, Lasso tool, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone, Bind and Asset Warp tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage, panel icons in docks collapsed to icons (ADR 0087) | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 | | `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `crates/svg/fixtures/soft-masks-text-paths.svg` | SVG import test drawing (an alpha and a luminance mask, text on a path) | AniCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/*.svg` except `anicraft-*` (37 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons, plus, trash, copy, ellipsis) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | (`icons/.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0; `plus.svg`, `trash.svg`, `copy.svg` and `ellipsis.svg` from Lucide's `main` branch, 2026-11) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) | diff --git a/CHANGELOG.md b/CHANGELOG.md index f1350047..1e788ff2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +* **Lasso tool (L)** (#515, backlog P-018). Draw a freehand loop on the stage to cut out and + select the parts of merged fills and lines inside it and pick objects wholly inside it, across + every visible, unlocked layer (**Shift** adds, **Esc** cancels, a click on empty stage clears). + Headless: `raw.select_area {points, add?}` (even-odd rule for self-intersecting loops; ready + for a straight-edged Polygon mode to call the same command). + * **Timeline and panel bugs from the tracker** (M8, backlog P-009 and P-010, ADR 0131). * **Several layers selected at once** (#512). **Ctrl**-click a layer's name to add it or take it out, **Shift**-click for every layer from the active one, or **Shift+Up** and diff --git a/assets/icons/anicraft-lasso.svg b/assets/icons/anicraft-lasso.svg new file mode 100644 index 00000000..b01b1f0f --- /dev/null +++ b/assets/icons/anicraft-lasso.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/crates/engine/src/cmds_raw.rs b/crates/engine/src/cmds_raw.rs index 093cd8d6..119c04de 100644 --- a/crates/engine/src/cmds_raw.rs +++ b/crates/engine/src/cmds_raw.rs @@ -50,6 +50,15 @@ pub fn specs() -> Vec { true, select_rect, ), + c( + "raw.select_area", + "Lasso Selection", + "", + None, + "{points: [[x, y], ..] (a loop in stage coordinates, closed automatically; 3..=10000 points, refuse more; self-intersecting loops use the even-odd rule), add?: bool} the Lasso, on every visible, unlocked layer: the parts of raw fills and strokes inside the loop (cut at its edges, per layer) and the objects whose bounding box (all four corners, with no loop edge crossing its interior) lies wholly inside it; fewer than 3 distinct points or zero area behaves like a zero-size marquee", + true, + select_area, + ), c("raw.merge", "Merge Shapes", "", None, "{ids?: [..]} the raw shapes (default: the selection) merge again with the raw shapes they touch, in place", true, merge_cmd), c("raw.hit", "Selection Tool Target", "", None, "{x, y, slop?, point_slop?} what a Selection-tool drag from (x, y) takes: a point, a segment to bend, a fill, or an object", false, hit), ] @@ -725,6 +734,268 @@ fn marquee_layer(s: &mut Session, r: &Rect, mut picked: Vec, partial: Ok((cut, origin, inside_all)) } +// ----- the lasso -------------------------------------------------------------------------------- + +/// Required list of `[x, y]` stage positions for `raw.select_area` (at most [`MAX_POINTS`], +/// finite and within [`MAX_EXTENT`]). +fn area_points_param(p: &Value, key: &str) -> Result> { + let bad = || EngineError::Param(format!("param '{key}' must be a list of [x, y] pairs")); + let list = p.get(key).and_then(Value::as_array).ok_or_else(bad)?; + if list.len() > MAX_POINTS { + return Err(EngineError::Param(format!("param '{key}' has more than {MAX_POINTS} points"))); + } + list.iter() + .map(|xy| { + let xy = xy.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?; + let n = |i: usize| { + xy.get(i) + .and_then(Value::as_f64) + .map(|f| f as f32) + .filter(|f| f.is_finite() && f.abs() <= MAX_EXTENT) + .ok_or_else(bad) + }; + Ok(Vec2::new(n(0)?, n(1)?)) + }) + .collect() +} + +/// Drops consecutive near-identical vertices and any duplicate closing vertex. +fn clean_loop(raw: &[Vec2]) -> Vec { + let mut out: Vec = Vec::with_capacity(raw.len()); + for &q in raw { + if out.last().is_none_or(|p| p.distance(q) > 1e-6) { + out.push(q); + } + } + while out.len() > 1 && out.last().zip(out.first()).is_some_and(|(a, b)| a.distance(*b) <= 1e-6) { + out.pop(); + } + out +} + +/// Whether `pts` has fewer than 3 distinct points or all points are collinear (zero enclosed area). +fn loop_is_degenerate(pts: &[Vec2]) -> bool { + let Some(&a) = pts.first() else { return true }; + if pts.len() < 3 { + return true; + } + let (ax, ay) = (f64::from(a.x), f64::from(a.y)); + let mut best_d2 = 0.0f64; + let mut far = (ax, ay); + for &p in &pts[1..] { + let (dx, dy) = (f64::from(p.x) - ax, f64::from(p.y) - ay); + let d2 = dx * dx + dy * dy; + if d2 > best_d2 { + best_d2 = d2; + far = (f64::from(p.x), f64::from(p.y)); + } + } + let len = best_d2.sqrt(); + if len <= 1e-6 { + return true; + } + let (ux, uy) = (far.0 - ax, far.1 - ay); + let max_perp = pts + .iter() + .map(|p| ((ux * (f64::from(p.y) - ay) - uy * (f64::from(p.x) - ax)).abs()) / len) + .fold(0.0f64, f64::max); + max_perp <= 1e-6 +} + +/// Whether `p` lies inside the closed polygon `pts` under the even-odd rule. +fn poly_contains_even_odd(pts: &[Vec2], p: Vec2) -> bool { + let (px, py) = (f64::from(p.x), f64::from(p.y)); + let n = pts.len(); + let mut inside = false; + for i in 0..n { + let (a, b) = (pts[i], pts[(i + 1) % n]); + let (ax, ay, bx, by) = (f64::from(a.x), f64::from(a.y), f64::from(b.x), f64::from(b.y)); + if (ay > py) != (by > py) && px < ax + (py - ay) * (bx - ax) / (by - ay) { + inside = !inside; + } + } + inside +} + +/// Whether `p` lies within `tol` of segment `a..b`. +fn point_on_seg(p: [f64; 2], a: [f64; 2], b: [f64; 2], tol: f64) -> bool { + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + let l2 = dx * dx + dy * dy; + let t = if l2 > 1e-24 { (((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let (qx, qy) = (a[0] + t * dx, a[1] + t * dy); + let (ex, ey) = (p[0] - qx, p[1] - qy); + ex * ex + ey * ey <= tol * tol +} + +/// Whether `p` lies inside (even-odd) or on the boundary of `pts`. +fn poly_contains_or_edge(pts: &[Vec2], p: Vec2) -> bool { + if poly_contains_even_odd(pts, p) { + return true; + } + let q = [f64::from(p.x), f64::from(p.y)]; + let n = pts.len(); + (0..n).any(|i| { + let (a, b) = (pts[i], pts[(i + 1) % n]); + point_on_seg(q, [f64::from(a.x), f64::from(a.y)], [f64::from(b.x), f64::from(b.y)], 1e-4) + }) +} + +/// Whether segment `a..b` has any point strictly inside the open rectangle `(r.min, r.max)`. +fn seg_enters_open_rect(a: Vec2, b: Vec2, r: &Rect) -> bool { + let (ax, ay, bx, by) = (f64::from(a.x), f64::from(a.y), f64::from(b.x), f64::from(b.y)); + let (x0, y0, x1, y1) = (f64::from(r.min.x), f64::from(r.min.y), f64::from(r.max.x), f64::from(r.max.y)); + let (mut lo, mut hi) = (0.0f64, 1.0f64); + let clip = |p0: f64, d: f64, min: f64, max: f64, lo: &mut f64, hi: &mut f64| -> bool { + if d.abs() <= 1e-18 { + p0 > min && p0 < max + } else { + let (t0, t1) = ((min - p0) / d, (max - p0) / d); + let (s0, s1) = if t0 < t1 { (t0, t1) } else { (t1, t0) }; + *lo = lo.max(s0); + *hi = hi.min(s1); + *lo < *hi + } + }; + clip(ax, bx - ax, x0, x1, &mut lo, &mut hi) && clip(ay, by - ay, y0, y1, &mut lo, &mut hi) +} + +/// Whether segment `a..b` strictly crosses segment `c..d` in the interior of both. +fn segs_strictly_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool { + let cross = |o: Vec2, p: Vec2, q: Vec2| (f64::from(p.x) - f64::from(o.x)) * (f64::from(q.y) - f64::from(o.y)) - (f64::from(p.y) - f64::from(o.y)) * (f64::from(q.x) - f64::from(o.x)); + let (d1, d2, d3, d4) = (cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b)); + ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0)) +} + +/// Whether the entire bounding box `r` lies inside the closed polygon `pts` (even-odd rule): +/// all four corners inside or on the boundary, its centre inside, and no loop edge crossing its +/// interior (handles concave and self-intersecting loops without false positives). +fn poly_contains_rect(pts: &[Vec2], loop_bounds: &Rect, r: &Rect) -> bool { + if !contains(loop_bounds, r) { + return false; + } + let corners = [r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y)]; + if !corners.iter().all(|&c| poly_contains_or_edge(pts, c)) { + return false; + } + let n = pts.len(); + if r.width() > 1e-6 && r.height() > 1e-6 { + if !poly_contains_even_odd(pts, r.center()) { + return false; + } + !(0..n).any(|i| seg_enters_open_rect(pts[i], pts[(i + 1) % n], r)) + } else if r.width() > 1e-6 || r.height() > 1e-6 { + if !poly_contains_or_edge(pts, r.center()) { + return false; + } + !(0..n).any(|i| segs_strictly_cross(pts[i], pts[(i + 1) % n], r.min, r.max)) + } else { + true + } +} + +/// The Lasso (`raw.select_area`, issue #515): on every visible, unlocked layer, the parts of raw +/// shapes inside the closed loop (cut at its edges, even-odd rule) and the objects whose bounding +/// box lies wholly inside it. Designed so a straight-edged polygon mode can call the same command. +fn select_area(s: &mut Session, p: &Value) -> Result { + let raw_pts = area_points_param(p, "points")?; + let add = opt_bool(p, "add")?.unwrap_or(false); + if !add { + s.selection.clear(); + } + let pts = clean_loop(&raw_pts); + if loop_is_degenerate(&pts) { + return Ok(json!({"selected": s.selection.id_list(), "cut": 0})); + } + let mut cutter = Path::new(); + let mut loop_bounds = Rect::EMPTY; + for (i, &q) in pts.iter().enumerate() { + loop_bounds.include(q); + if i == 0 { + cutter.move_to(q); + } else { + cutter.line_to(q); + } + } + cutter.close(); + let mut found: Vec<(LayerId, Vec, Vec)> = Vec::new(); + let layers: Vec = s.timeline().layers.iter().map(|l| l.id).filter(|l| s.gathers(*l)).collect(); + for l in layers { + let (mut picked, mut partial) = (Vec::new(), Vec::new()); + for e in s.elements_on(l) { + let bounds = s.element_bounds_on(l, e.id); + if bounds.is_empty() || bounds.intersect(&loop_bounds).is_empty() { + continue; + } + if poly_contains_rect(&pts, &loop_bounds, &bounds) { + picked.push(e.id); + } else if mergeable(&e).is_some() { + partial.push(e.id); + } + } + if !picked.is_empty() || !partial.is_empty() { + found.push((l, picked, partial)); + } + } + let mut cut = 0; + let (mut origin, mut inside): (CutOrigin, Vec) = (Vec::new(), Vec::new()); + let mut hit: Vec = Vec::new(); + for (l, picked, partial) in found { + let (n, o, i, took) = s.with_layer(l, |s| lasso_layer(s, &cutter, picked, &partial))?; + cut += n; + origin.extend(o); + inside.extend(i); + if took { + hit.push(l); + } + } + if !inside.is_empty() { + s.pending_cut = Some((origin, inside)); + } + if !hit.contains(&s.layer) + && let Some(&top) = hit.first() + { + s.layer = top; + } + Ok(json!({"selected": s.selection.id_list(), "cut": cut})) +} + +/// Polygon variant of [`marquee_layer`]: raw shapes partly under `cutter` are cut along it and +/// the parts inside (even-odd) are selected; `picked` (wholly inside) are selected as-is. +fn lasso_layer(s: &mut Session, cutter: &Path, mut picked: Vec, partial: &[ElementId]) -> Result<(usize, CutOrigin, Vec, bool)> { + let here = s.layer; + let mut cut = 0; + let (mut origin, mut inside_all) = (Vec::new(), Vec::new()); + if !partial.is_empty() && on_editable_key(s) { + let kf = s.editable_keyframe()?; + let existing = kf.elements.clone(); + let idx: Vec = existing.iter().enumerate().filter(|(_, e)| partial.contains(&e.id)).map(|(i, _)| i).collect(); + // Parts already selected (an earlier selection, with Shift) stay selected, cut or not. + let parts: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), s.selection.contains(here, e.id))).collect(); + match merge::remerge_with(s, &parts, Some(cutter)) { + Some(rm) if !rm.inside.is_empty() => { + origin = rm.from.iter().filter_map(|&(piece, part)| idx.get(part).and_then(|&i| existing.get(i)).map(|e| (piece, e.id))).collect(); + cut = rm.inside.len(); + let gone: Vec = idx.iter().filter_map(|&i| existing.get(i)).map(|e| e.id).collect(); + s.selection.retain(|l, id| l != here || !gone.contains(&id)); + let mut inside = rm.inside; + inside.extend(rm.picked.iter().filter(|id| !inside.contains(id)).copied().collect::>()); + picked.extend(inside.iter().copied()); + merge::replace(s, &idx, rm.out, false)?; + inside_all = inside; + } + // Only their bounds reached the loop's box: nothing of them lies inside the loop. + Some(_) => {} + // Too complex to cut at once: select them whole. + None => picked.extend(partial.iter().copied()), + } + } else { + picked.extend(partial.iter().copied()); + } + let took = !picked.is_empty(); + s.selection.extend_on(here, picked); + Ok((cut, origin, inside_all, took)) +} + // ----- merging again ---------------------------------------------------------------------------- fn merge_cmd(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6c1644f8..7d55733a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -944,7 +944,7 @@ impl Session { } let Some(p) = self.live_cut() else { return }; let held = self.selection.ids().any(|s| p.inside.contains(&s)); - let fresh_marquee = id == "raw.select_rect" && params.get("add").and_then(Value::as_bool) != Some(true); + let fresh_marquee = matches!(id, "raw.select_rect" | "raw.select_area") && params.get("add").and_then(Value::as_bool) != Some(true); if !held || fresh_marquee || id.starts_with("file.") || id == "edit.undo" || id == "edit.redo" { self.heal_cut(); } diff --git a/crates/engine/src/raw_tests.rs b/crates/engine/src/raw_tests.rs index 1e79b96d..080d171e 100644 --- a/crates/engine/src/raw_tests.rs +++ b/crates/engine/src/raw_tests.rs @@ -440,6 +440,108 @@ fn a_marquee_over_a_whole_raw_shape_selects_it_without_cutting() { assert_eq!(count(&s), (1, 4)); } +// ----- the lasso (`raw.select_area`, issue #515) ------------------------------------------------- + +#[test] +fn lasso_cuts_raw_fill_with_triangle_and_rest_stays_unselected() { + let mut s = rect_session(); + let history = s.history_len(); + let whole_area = fill_area(&s); + // Triangle over the upper-right diagonal half of the 100 × 80 raw rectangle. + let tri = json!([[0, -10], [110, -10], [110, 90]]); + let loop_bounds = anicraft_geom::Rect::new(0.0, -10.0, 110.0, 90.0); + let r = run(&mut s, "raw.select_area", json!({"points": tri})); + assert!(r["cut"].as_u64().unwrap_or(0) > 0, "triangle cut the raw shape: {r}"); + let els = s.visible_elements(); + let sel_fills: Vec<&Arc> = els.iter().filter(|e| s.selection.has_id(e.id) && is_fill(e)).collect(); + let unsel_fills: Vec<&Arc> = els.iter().filter(|e| !s.selection.has_id(e.id) && is_fill(e)).collect(); + assert!(!sel_fills.is_empty(), "a cut fill piece is selected"); + assert!(!unsel_fills.is_empty(), "the rest of the fill stays unselected"); + let sel_area: f32 = sel_fills.iter().map(|e| area(e)).sum(); + let unsel_area: f32 = unsel_fills.iter().map(|e| area(e)).sum(); + assert!(sel_area > 0.0 && sel_area < whole_area, "selected part is smaller than the whole: {sel_area} vs {whole_area}"); + assert!((sel_area + unsel_area - whole_area).abs() < 1.0, "parts add up: {sel_area} + {unsel_area} vs {whole_area}"); + for e in &sel_fills { + let b = s.element_bounds(e.id); + assert!(b.min.x >= loop_bounds.min.x - 1.0 && b.min.y >= loop_bounds.min.y - 1.0 && b.max.x <= loop_bounds.max.x + 1.0 && b.max.y <= loop_bounds.max.y + 1.0, "part bounds inside loop bounds: {b:?}"); + } + // Selecting alone adds no undo step; deselecting heals the cut back whole. + assert_eq!(s.history_len(), history); + run(&mut s, "edit.deselect", json!({})); + assert_eq!(count(&s), (1, 4), "deselect heals the lasso cut"); + // Cutting and deleting the lassoed half is one undo step back to the whole rectangle. + run(&mut s, "raw.select_area", json!({"points": tri})); + run(&mut s, "edit.delete", json!({})); + assert_eq!(s.history_len(), history + 1); + assert!(fill_area(&s) < whole_area * 0.9); + run(&mut s, "edit.undo", json!({})); + assert_eq!(count(&s), (1, 4)); + assert!((fill_area(&s) - whole_area).abs() < 1.0); +} + +#[test] +fn lasso_picks_only_objects_wholly_inside_including_concave_loops() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true})); + let inside_id = s.selection.ids().next().unwrap(); + run(&mut s, "draw.rect", json!({"x": 45, "y": 45, "w": 40, "h": 40, "object": true})); + let crossing_id = s.selection.ids().next().unwrap(); + // Triangle (0,0)-(100,0)-(0,100) wholly holds [10..30, 10..30], crosses [45..85, 45..85]. + run(&mut s, "raw.select_area", json!({"points": [[0, 0], [100, 0], [0, 100]]})); + assert!(s.selection.has_id(inside_id), "object wholly inside is picked"); + assert!(!s.selection.has_id(crossing_id), "object crossing the edge is not picked"); + // A concave C-loop whose arms contain all four corners of a tall box [15..25, 10..90] + // while its notch cuts across the middle [15..25, 40..60] must not pick that box. + run(&mut s, "draw.rect", json!({"x": 15, "y": 10, "w": 10, "h": 80, "object": true})); + let tall_id = s.selection.ids().next().unwrap(); + let c_loop = json!([[0, 0], [40, 0], [40, 30], [10, 30], [10, 70], [40, 70], [40, 100], [0, 100]]); + run(&mut s, "raw.select_area", json!({"points": c_loop})); + assert!(!s.selection.has_id(tall_id), "object spanning a concave notch is not wholly inside"); +} + +#[test] +fn lasso_add_keeps_earlier_selection() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 20, "h": 20, "object": true})); + let a = s.selection.ids().next().unwrap(); + run(&mut s, "draw.rect", json!({"x": 200, "y": 10, "w": 20, "h": 20, "object": true})); + let b = s.selection.ids().next().unwrap(); + run(&mut s, "raw.select_area", json!({"points": [[0, 0], [50, 0], [50, 50], [0, 50]]})); + assert!(s.selection.has_id(a) && !s.selection.has_id(b)); + run(&mut s, "raw.select_area", json!({"points": [[190, 0], [240, 0], [240, 50], [190, 50]], "add": true})); + assert!(s.selection.has_id(a) && s.selection.has_id(b), "add keeps the earlier selection"); +} + +#[test] +fn lasso_handles_self_intersecting_degenerate_and_over_limit_loops() { + let mut s = rect_session(); + let whole_area = fill_area(&s); + // Self-intersecting bowtie across the raw rectangle: selects both lobes (even-odd). + let bowtie = run(&mut s, "raw.select_area", json!({"points": [[-10, -10], [110, 90], [110, -10], [-10, 90]]})); + assert!(bowtie["cut"].as_u64().unwrap_or(0) > 0, "self-intersecting loop cuts under even-odd"); + assert!((fill_area(&s) - whole_area).abs() < 1.0); + // Degenerate loops (empty, 2 points, collinear) cut nothing and behave like a zero-size marquee. + for pts in [json!([]), json!([[0, 0], [50, 50]]), json!([[0, 0], [20, 20], [50, 50], [100, 100]])] { + let r = run(&mut s, "raw.select_area", json!({"points": pts})); + assert_eq!(r["cut"], 0); + assert!(s.selection.is_empty(), "clears selection when add is false"); + assert_eq!(count(&s), (1, 4), "earlier provisional cut healed"); + } + // With add: true, a degenerate loop keeps the existing selection. + run(&mut s, "element.pick", json!({"x": 50, "y": 40})); + let kept = s.selection.len(); + assert!(kept > 0); + let r = run(&mut s, "raw.select_area", json!({"points": [[0, 0], [10, 10]], "add": true})); + assert_eq!(r["cut"], 0); + assert_eq!(s.selection.len(), kept); + // Over-limit point count and bad points are refused cleanly. + let too_many: Vec = (0..10_001).map(|i| json!([i % 100, i / 100])).collect(); + assert!(s.execute("raw.select_area", &json!({"points": too_many})).is_err()); + assert!(s.execute("raw.select_area", &json!({"points": [[0, 0], [1e30, 0], [0, 10]]})).is_err()); + assert!(s.execute("raw.select_area", &json!({"points": [[0, 0], [null, 10], [10, 10]]})).is_err()); + assert!(s.execute("raw.select_area", &json!({})).is_err()); +} + // ----- what a drag takes ------------------------------------------------------------------------------ #[test] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ef17b9ac..5dc23254 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -707,6 +707,12 @@ fn panic_hunt(only: &str) { json!({"x0": 10, "y0": 10, "x1": 45, "y1": 75, "add": true, "from": [1, 2, 3], "snap": 3}), json!({"x0": -1e7, "y0": 1e7, "x1": 1e7, "y1": -1e7, "add": false, "from": [45, 45], "snap": 0.2}), json!({"x0": 30, "y0": 30, "x1": 30, "y1": 30, "point_slop": -5, "ids": [u64::MAX], "points": "x"}), + // Lasso selection (`raw.select_area`, #515): empty, NaN, huge, degenerate, self-crossing and over-limit loops. + json!({"points": [], "add": false}), + json!({"points": [[0, 0], [f64::NAN, 10], [10, 10]], "add": true}), + json!({"points": [[-1e30, 0], [1e30, 1e30], [0, -1e30]], "add": false}), + json!({"points": [[0, 0], [100, 100], [100, 0], [0, 100]], "add": false}), + json!({"points": (0..10_005).map(|i| json!([i, i % 3])).collect::>()}), // Subselection on raw shapes (ADR 0042): handles that aren't there or move too far, // anchors to move along that are hostile, connected sets of anything. json!({"id": 3, "cmd": 1, "slot": 2, "dx": 1e30, "dy": 0, "x": 30, "y": 30, "to_x": 31, "to_y": 30, "with": [[30, 30], [1e30, 0]]}), diff --git a/docs/guide/coming-from-animate.md b/docs/guide/coming-from-animate.md index 204858af..57bace51 100644 --- a/docs/guide/coming-from-animate.md +++ b/docs/guide/coming-from-animate.md @@ -45,6 +45,7 @@ Each tool has the key you already know. |---|---|---| | Selection | **V** | Selects raw strokes and fills with the dot pattern; drag an edge to bend it. | | Subselection | **A** | Points and handles, on raw drawings and drawing objects. | +| Lasso | **L** | Freehand loop selection (Polygon mode and Magic Wand aren't there yet). | | Free Transform | **Q** | Scale, skew (drag the line between two handles), rotate and move; Shift and Alt as you'd expect. Drag the white circle to move the transformation point, double-click it to centre it; a rotated instance's box turns with it. | | Gradient Transform | **F** | Its own button (no flyouts yet). Gradient and bitmap fills, with Lock Fill. | | Width | **U** | Variable-width strokes, with profiles in Properties. | @@ -67,7 +68,7 @@ Each tool has the key you already know. | Zoom | **Z** | | | Object Drawing | **J** | Toggles between merge drawing and drawing objects. | -Not in AniCraft yet: the Lasso, Polygon and Magic Wand tools, the 3D tools, +Not in AniCraft yet: the Polygon (lasso) and Magic Wand tools, the 3D tools, Asset Warp, the Paint Brush and Fluid Brush, Deco and the Spray Brush. More on the tools in [Drawing](drawing.md). diff --git a/docs/guide/drawing.md b/docs/guide/drawing.md index 60025b6b..ccc98c0f 100644 --- a/docs/guide/drawing.md +++ b/docs/guide/drawing.md @@ -18,6 +18,7 @@ your hand. |---|---|---| | Selection | **V** | Select, move and bend artwork | | Subselection | **A** | Edit points and curve handles | +| Lasso | **L** | Select an irregular area with a freehand loop | | Free Transform | **Q** | Scale, skew, rotate and move | | Gradient Transform | **F** | Move, turn and stretch a gradient or bitmap fill | | Width | **U** | Vary a line's thickness along it | @@ -112,6 +113,18 @@ whatever you moved merges with what it lands on. The marquee, **Shift**-click and **Edit › Select All** (**Ctrl+A**) work across every visible, unlocked layer at once. **Edit › Deselect All** is **Ctrl+Shift+A**. +### The Lasso tool + +The **Lasso** (**L**) selects an irregular area. Drag a freehand loop on the stage and let go: +the loop closes automatically back to where you started. On every visible, unlocked layer, the +parts of merged fills and lines inside the loop are cut at its edges and selected, and objects +(drawing objects, groups, symbols, text and bitmaps) wholly inside the loop are selected. + +Hold **Shift** to add to the selection, press **Esc** while dragging to cancel, or click on empty +stage to clear the selection. As with the marquee, clicking away without editing heals cut raw +shapes back whole. To move or transform what you selected, switch to the **Selection** (**V**) or +**Free Transform** (**Q**) tool. + ## Drawing shapes and lines * **Rectangle** (**R**): drag to draw. **Shift** draws a square. Set **Corners** in the diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 6050b4c2..9e4b8cb6 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -1,6 +1,6 @@ # Command reference -Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 399 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). +Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 400 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**Help › Keyboard Shortcuts**) replace the defaults shown here; see the [shortcut reference](shortcuts.md). This page is generated from the command registry, so it always matches the version of AniCraft it came with. @@ -623,6 +623,8 @@ These commands have no menu item: the panels, the stage and the timeline use the Parameters: ``{x, y, to_x, to_y, with?: [[x, y], ..], points?: [[id, cmd], ..], snap?, slop?, merge?: bool} moves the corner or end at (x, y), with every raw shape that shares it, to (to_x, to_y), snapped within `snap` to points, lines and fill edges (while Snap to Objects is on); the anchors at `with` move by as much; returns the points to pass on while a drag goes on`` - **Select Parts** `raw.select_rect` · changes the document Parameters: `{x0, y0, x1, y1, add?: bool} the marquee, on every visible, unlocked layer: the parts of raw fills and strokes under the rectangle (cut at its edges, per layer) and the objects wholly inside it` +- **Lasso Selection** `raw.select_area` · changes the document + Parameters: `{points: [[x, y], ..] (a loop in stage coordinates, closed automatically; 3..=10000 points, refuse more; self-intersecting loops use the even-odd rule), add?: bool} the Lasso, on every visible, unlocked layer: the parts of raw fills and strokes inside the loop (cut at its edges, per layer) and the objects whose bounding box (all four corners, with no loop edge crossing its interior) lies wholly inside it; fewer than 3 distinct points or zero area behaves like a zero-size marquee` - **Merge Shapes** `raw.merge` · changes the document Parameters: `{ids?: [..]} the raw shapes (default: the selection) merge again with the raw shapes they touch, in place` - **Selection Tool Target** `raw.hit` diff --git a/docs/guide/reference/shortcuts.md b/docs/guide/reference/shortcuts.md index 60072894..5c6117d0 100644 --- a/docs/guide/reference/shortcuts.md +++ b/docs/guide/reference/shortcuts.md @@ -21,6 +21,7 @@ This page is generated from the editor's shortcut map, so it always matches the |---|---|---| | Selection | V | V | | Subselection | A | A | +| Lasso | L | L | | Free Transform | Q | Q | | Asset Warp | Shift+Q | ⇧Q | | Gradient Transform | F | F | diff --git a/docs/parity.md b/docs/parity.md index 52d2226c..c03a4ac4 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -29,7 +29,7 @@ AniCraft is an independent, open-source project, and is not affiliated with or e | Area | Done (ours included) | Partial | Missing | Won't do | |---|---|---|---|---| | Workspace and panels | 23 | 5 | 4 | 2 | -| Tools | 19 | 7 | 7 | 1 | +| Tools | 20 | 7 | 6 | 1 | | Drawing model | 16 | 3 | 4 | 0 | | Colour | 8 | 1 | 2 | 2 | | Text | 8 | 5 | 5 | 2 | @@ -49,7 +49,7 @@ AniCraft is an independent, open-source project, and is not affiliated with or e | Accessibility | 4 | 2 | 1 | 0 | | Preferences and shortcuts | 6 | 2 | 0 | 1 | | Automation | 4 | 2 | 1 | 1 | -| **All** | **198** | **53** | **70** | **27** | +| **All** | **199** | **53** | **69** | **27** | The counts are of the rows below, so they weigh a small feature like a large one. The backlog, not this table, says what matters most. @@ -101,7 +101,7 @@ not this table, says what matters most. | Subselection | **done** | [ADR 0042](adr/0042-subselection-and-merging-everywhere.md), [ADR 0045](adr/0045-raw-points-and-raw-shapes-inside-symbols.md). | | Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bug: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), not reproduced on Windows 10 (P-005). | | Gradient Transform | **done** | Gradient and bitmap fills, Lock Fill. | -| Lasso | **missing** | P-018 ([#515](https://github.com/storytold/anicraft/issues/515)). | +| Lasso | **done** | Freehand loop selection ([#515](https://github.com/storytold/anicraft/issues/515)); cuts raw shapes and selects objects wholly inside. | | Polygon (lasso) | **missing** | P-018. | | Magic Wand | **missing** | P-018. | | Pen, with Add, Delete and Convert Anchor Point | **done** | [ADR 0115](adr/0115-pen-parity-and-keep-area-tweens.md). Add, delete and convert are gestures of the Pen and Subselection, not tools of their own. | diff --git a/src/app.rs b/src/app.rs index c2915fe7..c8c147fe 100644 --- a/src/app.rs +++ b/src/app.rs @@ -14,6 +14,7 @@ use std::path::PathBuf; pub enum Tool { Select, Subselect, + Lasso, Transform, /// Asset Warp (ADR 0079): pins on shapes and bitmaps that bend them. Warp, @@ -71,12 +72,13 @@ impl GapSize { } impl Tool { - pub const ALL: [Tool; 24] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Warp, Tool::GradientTransform, Tool::Width, Tool::Bone, Tool::Bind, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom]; + pub const ALL: [Tool; 25] = [Tool::Select, Tool::Subselect, Tool::Lasso, Tool::Transform, Tool::Warp, Tool::GradientTransform, Tool::Width, Tool::Bone, Tool::Bind, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom]; pub fn label(self) -> &'static str { match self { Tool::Select => tr_noop!("Selection"), Tool::Subselect => tr_noop!("Subselection"), + Tool::Lasso => tr_noop!("Lasso"), Tool::Transform => tr_noop!("Free Transform"), Tool::Warp => tr_noop!("Asset Warp"), Tool::GradientTransform => tr_noop!("Gradient Transform"), @@ -106,6 +108,7 @@ impl Tool { match self { Tool::Select => Some("V"), Tool::Subselect => Some("A"), + Tool::Lasso => Some("L"), Tool::Transform => Some("Q"), Tool::Warp => Some("Shift+Q"), Tool::GradientTransform => Some("F"), @@ -135,6 +138,7 @@ impl Tool { match self { Tool::Select => tr_noop!("Click to select, drag to move, drag on empty space to marquee-select. Shift adds to the selection."), Tool::Subselect => tr_noop!("Click a shape to show its points; on a merged drawing, the points of everything connected to it. Drag points or handles to reshape (a shared point moves every shape that has it; a smooth point's handles stay in line, Alt moves one alone); drag a line or fill to move everything connected. Shift adds to the point selection, drag on empty space to marquee points, arrow keys nudge them. Double-click an edge to add a point, Delete removes points, and right-click makes a point smooth or a corner. A motion path's points edit the same way (its ends stay), and so does the path of text on a path (the text follows)."), + Tool::Lasso => tr_noop!("Drag a freehand loop to select the parts of raw shapes inside it and objects wholly inside it. Shift adds to the selection, Esc cancels."), Tool::Pen => tr_noop!("Click to place corner points, drag to pull smooth handles (Alt moves one handle, Shift keeps 45° steps). Click the first point to close; Enter, Esc or a double-click finishes. Click the last point to make it a corner, drag from it for a new handle, Alt-drag it to draw its curve again; Backspace removes it. On a selected path: click a point to make it a corner and again to delete it, click the outline to add a point, click an open end to continue it. Ctrl-click a path to select it. Points snap to points and lines while Snap to Objects is on."), Tool::Text => tr_noop!("Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too."), Tool::Pencil => tr_noop!("Drag to draw freehand. The options bar sets Smooth, Straighten or Ink."), @@ -218,6 +222,8 @@ pub enum Drag { /// pointer to the point. The points that move are `App::raw_points`. RawPoint { at: egui::Pos2, off: egui::Vec2 }, Marquee { start: egui::Pos2, cur: egui::Pos2 }, + /// Lasso tool (issue #515): freehand loop selection; stage-space points are in `App::lasso`. + Lasso, /// Edit Multiple Frames (ADR 0047): moving the selection on every keyframe it is on, the /// pointer at `last` last frame; or a marquee over them. MultiMove { last: egui::Pos2 }, @@ -447,6 +453,8 @@ pub struct App { pub pen: Option, /// Pencil samples of the stroke in progress (stage space). pub pencil: Vec, + /// Lasso loop points in progress (stage space). + pub lasso: Vec, /// A Selection-tool point drag's points (`raw.move_point`'s `points`), and the raw shapes a /// bend or point drag changed (merged again when it ends; ADR 0041). pub raw_points: serde_json::Value, @@ -848,6 +856,7 @@ impl App { rect_radius: 0.0, pen: None, pencil: Vec::new(), + lasso: Vec::new(), raw_points: serde_json::Value::Null, raw_touched: Vec::new(), raw_with: Vec::new(), @@ -4870,6 +4879,12 @@ impl App { self.raw_anchors.clear(); self.raw_ends.clear(); } + if self.tool != Tool::Lasso && (self.drag == Drag::Lasso || !self.lasso.is_empty()) { + self.lasso.clear(); + if self.drag == Drag::Lasso { + self.drag = Drag::None; + } + } pathtools::upkeep(self); crate::motion_path::upkeep(self); crate::widthtool::upkeep(self); diff --git a/src/context_help.rs b/src/context_help.rs index bc0ff355..5267e984 100644 --- a/src/context_help.rs +++ b/src/context_help.rs @@ -16,6 +16,7 @@ pub fn tool_topic(t: Tool) -> &'static str { match t { Tool::Select => "drawing.md#the-tools", Tool::Subselect => "drawing.md#editing-points-with-subselection", + Tool::Lasso => "drawing.md#the-lasso-tool", Tool::Transform => "drawing.md#transforming-artwork", Tool::Warp => "masks-guides-camera-bones.md#asset-warp", Tool::GradientTransform => "drawing.md#gradients-and-bitmap-fills", diff --git a/src/icons.rs b/src/icons.rs index 2a843ef1..95d243e1 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -16,6 +16,7 @@ use std::sync::OnceLock; pub enum Icon { Select, Subselect, + Lasso, Transform, Pen, Pencil, @@ -93,7 +94,8 @@ pub enum Icon { impl Icon { #[cfg(test)] - pub const ALL: [Icon; 75] = [ + pub const ALL: [Icon; 76] = [ + Icon::Lasso, Icon::PanelProperties, Icon::PanelSwatches, Icon::PanelLibrary, @@ -183,6 +185,8 @@ impl Icon { Icon::Select => ("mouse-pointer-2", false), // A hollow arrowhead, mirrored to point like a cursor: the subselection arrow. Icon::Subselect => ("navigation", true), + // A rope loop with its knot and tail (AniCraft original, on Lucide's grid). + Icon::Lasso => ("anicraft-lasso", false), Icon::Transform => ("scaling", false), // A stroke swelling and tapering, with a width point across it (AniCraft original). Icon::Width => ("anicraft-width", false), @@ -333,6 +337,7 @@ static FILES: &[(&str, &str)] = &[ ("anicraft-distribute-h", include_str!("../assets/icons/anicraft-distribute-h.svg")), ("anicraft-distribute-v", include_str!("../assets/icons/anicraft-distribute-v.svg")), ("anicraft-mask", include_str!("../assets/icons/anicraft-mask.svg")), + ("anicraft-lasso", include_str!("../assets/icons/anicraft-lasso.svg")), ("anicraft-width", include_str!("../assets/icons/anicraft-width.svg")), ("anicraft-gradient-transform", include_str!("../assets/icons/anicraft-gradient-transform.svg")), ("anicraft-brush", include_str!("../assets/icons/anicraft-brush.svg")), diff --git a/src/keymap.rs b/src/keymap.rs index 0d8f3bc8..b47900a9 100644 --- a/src/keymap.rs +++ b/src/keymap.rs @@ -48,6 +48,7 @@ pub fn tool_id(t: Tool) -> &'static str { match t { Tool::Select => "tool.selection", Tool::Subselect => "tool.subselection", + Tool::Lasso => "tool.lasso", Tool::Transform => "tool.free_transform", Tool::GradientTransform => "tool.gradient_transform", Tool::Width => "tool.width", diff --git a/src/panels.rs b/src/panels.rs index 712ff95d..76ab3989 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -15,6 +15,7 @@ fn tool_icon(tool: Tool) -> Icon { match tool { Tool::Select => Icon::Select, Tool::Subselect => Icon::Subselect, + Tool::Lasso => Icon::Lasso, Tool::Transform => Icon::Transform, Tool::GradientTransform => Icon::GradientTransform, Tool::Width => Icon::Width, diff --git a/src/stage.rs b/src/stage.rs index 2118cbe6..8f4eee94 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -454,7 +454,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { None => CursorIcon::Default, } } - Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Bone | Tool::Bind | Tool::Warp => CursorIcon::Crosshair, + Tool::Lasso | Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::PaintBrush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Bone | Tool::Bind | Tool::Warp => CursorIcon::Crosshair, Tool::Text => CursorIcon::Text, Tool::Zoom => { if alt { @@ -557,6 +557,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { } } Tool::Subselect => crate::pathtools::subselect_drag_start(app, press, shift, xf), + Tool::Lasso => { + app.lasso = vec![to_v(sp)]; + Drag::Lasso + } Tool::Bone => crate::bone_tool::drag_start(app, xf, press), Tool::Bind => crate::bind_tool::drag_start(app, xf, press), Tool::Warp => crate::warp_tool::drag_start(app, xf, press), @@ -758,11 +762,22 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { (Drag::Brush, Some(c)) => crate::brushtool::sample(app, to_v(c), pressure, xf, now), (Drag::Eraser, Some(c)) => crate::brushtool::sample(app, to_v(c), None, xf, now), (Drag::Marquee { cur: m, .. }, Some(c)) => *m = c, + (Drag::Lasso, Some(c)) => { + let p = to_v(c); + if app.lasso.last().is_none_or(|l| l.distance(p) * zoom >= 1.0) && app.lasso.len() < 10_000 { + app.lasso.push(p); + } + } (Drag::Shape { start, cur: m }, Some(c)) => *m = constrain(app.tool, *start, c, shift), _ => {} } } + if app.drag == Drag::Lasso && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + app.lasso.clear(); + app.drag = Drag::None; + } + if resp.drag_stopped() { match app.drag { Drag::Move { .. } | Drag::SnapMove { .. } | Drag::CameraMove { .. } => { @@ -791,6 +806,17 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // wholly inside it (ADR 0041). app.run("raw.select_rect", json!({"x0": start.x, "y0": start.y, "x1": cur.x, "y1": cur.y, "add": shift})); } + Drag::Lasso => { + if let Some(c) = resp.interact_pointer_pos().map(to_stage) { + let p = to_v(c); + if app.lasso.last().is_none_or(|l| l.distance(p) * zoom >= 1.0) && app.lasso.len() < 10_000 { + app.lasso.push(p); + } + } + let pts = std::mem::take(&mut app.lasso); + let points: Vec<[f32; 2]> = pts.iter().map(|p| [p.x, p.y]).collect(); + app.run("raw.select_area", json!({"points": points, "add": shift})); + } Drag::Shape { start, cur } => create_shape(app, start, cur), Drag::Pan | Drag::None | Drag::CameraWheel { .. } => {} } @@ -868,6 +894,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.bone_sel = None; app.run("element.pick", json!({"x": sp.x, "y": sp.y, "add": shift})); } + Tool::Lasso if !panning => { + app.run("raw.select_area", json!({"points": [], "add": shift})); + } Tool::Zoom => { let z = if alt { app.view.zoom / 2.0 } else { app.view.zoom * 2.0 }; app.zoom_about(canvas, p, z); @@ -1217,7 +1246,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let enveloped = crate::shape_envelope::shown(app).is_some(); // Selected raw fills and strokes (ADRs 0031, 0041) show an // Animate-style stipple overlay instead of a bounding box. - if app.tool == Tool::Select && !preview { + if matches!(app.tool, Tool::Select | Tool::Lasso) && !preview { let gap = dot_gap_points(ppp); let to_px = Affine::translate(origin.x, origin.y) .mul(&Affine::scale(zoom, zoom)); @@ -1338,7 +1367,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { // Transform shows the fill's handles (ADR 0074). continue; } - if app.tool == Tool::Select && raw.contains(&(layer, id)) { + if matches!(app.tool, Tool::Select | Tool::Lasso) && raw.contains(&(layer, id)) { continue; // dots above } if transforming && enveloped { @@ -1419,6 +1448,15 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { painter.rect_filled(r, 0.0, T.selection.gamma_multiply(0.12)); painter.rect_stroke(r, 0.0, sel_stroke, StrokeKind::Middle); } + Drag::Lasso if app.lasso.len() >= 2 => { + let pts: Vec = app.lasso.iter().map(|p| to_screen(*p)).collect(); + if let (Some(&first), Some(&last)) = (pts.first(), pts.last()) + && pts.len() >= 3 + { + painter.add(egui::Shape::dashed_line(&[last, first], Stroke::new(1.0, T.selection.gamma_multiply(0.65)), 4.0, 3.0)); + } + painter.add(egui::Shape::line(pts, sel_stroke)); + } Drag::PointMarquee { start, cur } => { let r = Rect::from_two_pos(to_screen(Vec2::new(start.x, start.y)), to_screen(Vec2::new(cur.x, cur.y))); painter.rect_filled(r, 0.0, T.selection.gamma_multiply(0.12)); @@ -5517,4 +5555,76 @@ mod pointer_tests { // Two separate clicks stay two clicks: the fill alone. assert_eq!(double_click(0.7).s.selection.len(), 1); } + + #[test] + fn lasso_drag_selects_and_esc_cancels() { + let (mut app, ctx, at) = scene(); + // scene() has a raw rectangle at (100..300, 100..220). Add two drawing objects: one + // wholly inside the loop, one outside/crossing. + app.run("draw.rect", json!({"x": 400, "y": 120, "w": 30, "h": 30, "fill": "#22aa44", "stroke": null, "object": true})); + let inner_obj = app.s.selection.ids().next().expect("inner object"); + app.run("draw.rect", json!({"x": 460, "y": 120, "w": 80, "h": 80, "fill": "#aa2244", "stroke": null, "object": true})); + let outer_obj = app.s.selection.ids().next().expect("outer object"); + app.run("edit.deselect", json!({})); + + let mut t = 2.0; + let mut frame = |app: &mut App, mods: Modifiers, events: Vec| { + t += 0.05; + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(t), events: std::iter::once(Event::ModifiersChanged(mods)).chain(events).collect(), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| app.frame(ui)); + out.textures_delta.clear(); + }; + // L shortcut picks the Lasso tool. + frame(&mut app, Modifiers::NONE, vec![Event::Key { key: Key::L, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + assert_eq!(app.tool, Tool::Lasso); + + // Drag a loop over the right half of the raw rect. + let drag_poly = |frame: &mut dyn FnMut(&mut App, Modifiers, Vec), app: &mut App, pts: &[(f32, f32)], shift: bool| { + let mods = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + let btn = |pos: Pos2, pressed: bool| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: mods }; + let first = at(pts[0].0, pts[0].1); + frame(app, mods, vec![Event::PointerMoved(first)]); + frame(app, mods, vec![btn(first, true)]); + for &(x, y) in &pts[1..] { + frame(app, mods, vec![Event::PointerMoved(at(x, y))]); + } + let last = at(pts[pts.len() - 1].0, pts[pts.len() - 1].1); + frame(app, mods, vec![btn(last, false)]); + frame(app, Modifiers::NONE, Vec::new()); + }; + + drag_poly(&mut frame, &mut app, &[(200.0, 80.0), (320.0, 80.0), (320.0, 240.0), (200.0, 240.0)], false); + assert!(!app.s.selection.is_empty(), "lasso selected cut raw parts"); + assert!(app.s.visible_elements().len() > 7, "raw rectangle was cut by the lasso"); + let after_first = app.s.selection.len(); + + // Shift-lasso around the inner object adds it without picking the outer one. + drag_poly(&mut frame, &mut app, &[(385.0, 105.0), (445.0, 105.0), (445.0, 165.0), (385.0, 165.0)], true); + assert!(app.s.selection.len() > after_first); + assert!(app.s.selection.has_id(inner_obj), "inner object added"); + assert!(!app.s.selection.has_id(outer_obj), "outer object not picked"); + let before_esc = app.s.selection.clone(); + + // Esc during a drag cancels it without changing the selection. + let p0 = at(10.0, 10.0); + frame(&mut app, Modifiers::NONE, vec![Event::PointerMoved(p0)]); + frame(&mut app, Modifiers::NONE, vec![button(p0, true)]); + frame(&mut app, Modifiers::NONE, vec![Event::PointerMoved(at(60.0, 10.0))]); + frame(&mut app, Modifiers::NONE, vec![Event::PointerMoved(at(60.0, 60.0))]); + assert_eq!(app.drag, Drag::Lasso); + frame(&mut app, Modifiers::NONE, vec![Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]); + assert_eq!(app.drag, Drag::None); + assert!(app.lasso.is_empty()); + frame(&mut app, Modifiers::NONE, vec![button(at(60.0, 60.0), false)]); + frame(&mut app, Modifiers::NONE, Vec::new()); + assert_eq!(app.s.selection, before_esc, "cancelled lasso leaves selection untouched"); + + // A click without dragging on empty stage clears the selection. + let empty = at(20.0, 20.0); + frame(&mut app, Modifiers::NONE, vec![Event::PointerMoved(empty)]); + frame(&mut app, Modifiers::NONE, vec![button(empty, true)]); + frame(&mut app, Modifiers::NONE, vec![button(empty, false)]); + frame(&mut app, Modifiers::NONE, Vec::new()); + assert!(app.s.selection.is_empty(), "click on empty stage clears selection"); + } } diff --git a/src/tabs.rs b/src/tabs.rs index 1b615bb6..33931b08 100644 --- a/src/tabs.rs +++ b/src/tabs.rs @@ -288,6 +288,7 @@ fn settle(app: &mut App) { app.s.end_gesture(); } app.drag = Drag::None; + app.lasso.clear(); app.tl_drag = crate::timeline::TlDrag::None; app.tl_layer_drag = None; app.me_drag = None;