diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index b5fd1135aa..fc4cc6543d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1544,6 +1544,8 @@ fn headless_backend_methods() { let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap(); assert_eq!(selected["tool"], tool.id); } + let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); + assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); } diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c226a3c4d9..707b058023 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -10,6 +10,7 @@ pub mod enclosing_lasso; pub mod extend_path; pub mod measure_inspect; pub mod parametric_shape; +pub mod polygonal_lasso; pub mod shared_edge; pub mod slide_anchor; pub mod smart_pen; @@ -38,13 +39,21 @@ pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, l pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; +pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }]; + /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = - &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour"), (BOX_3D, "3D Box")]; +const HEADED: &[(&[ToolInfo], &str)] = &[ + (PATH_TOOLS, "Path Precision Tools"), + (SMART_PEN, "Smart Pen"), + (ENCLOSING_LASSO, "Enclosing Lasso"), + (CONTOUR, "Contour"), + (BOX_3D, "3D Box"), + (POLYGONAL_LASSO, "Polygonal Lasso"), +]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -66,6 +75,7 @@ pub fn create(id: &str) -> Option> { enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), contour::ID => Box::new(contour::ContourTool::default()), box3d::ID => Box::new(box3d::Box3dTool::default()), + polygonal_lasso::ID => Box::new(polygonal_lasso::PolygonalLassoTool::default()), _ => return None, }) } @@ -88,6 +98,7 @@ mod tests { assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); + assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); assert_eq!(GROUPS.len(), HEADED.len()); assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID)); assert!(create("pen").is_none() && heading("pen").is_none()); diff --git a/crates/tools/src/addons/polygonal_lasso.rs b/crates/tools/src/addons/polygonal_lasso.rs new file mode 100644 index 0000000000..1838293b66 --- /dev/null +++ b/crates/tools/src/addons/polygonal_lasso.rs @@ -0,0 +1,186 @@ +//! Polygonal Lasso selects anchor points inside a straight-edged loop, as the Lasso does inside a +//! freehand one. Each click sets a vertex, and a segment from the last vertex follows the pointer. +//! A double-click, Enter or a click on the first vertex closes the loop; Backspace or Delete removes +//! the last vertex and Escape drops the loop. Shift keeps the next segment to 45° steps (from the Constrain +//! Angle). Shift held at the first click adds to the selection and Alt subtracts from it. + +use vectorcraft_geom::{Point, constrain_angle_from}; + +use crate::meshedit::MeshEdit; +use crate::xform::lasso_select; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "polygonalLasso"; +/// The most vertices a loop keeps; clicks past it are ignored. +pub(crate) const MAX_VERTICES: usize = 65_536; + +#[derive(Default)] +pub struct PolygonalLassoTool { + vertices: Vec, + /// Where the segment from the last vertex ends: the pointer, constrained while Shift is held. + hover: Option, + /// Shift held at the first click: the loop adds to the selection. + add: bool, + /// Alt held at the first click: the loop subtracts from the selection. + sub: bool, + /// Whether the press in progress set a vertex (a dropped press takes it back). + pressed_vertex: bool, + /// The picked gradient mesh points (the tool's `meshPoints` option), as with the Lasso. + mesh: MeshEdit, +} + +impl PolygonalLassoTool { + /// The next vertex for a pointer at `p`: with Shift and a vertex already set, at a 45° step + /// from the last vertex. + fn target(&self, cx: &ToolContext, p: Point, mods: Mods) -> Point { + match self.vertices.last() { + Some(&last) if mods.shift => last + constrain_angle_from(p - last, 45.0, cx.constrain_angle), + _ => p, + } + } + + /// How near a vertex a click counts as a click on it. + fn reach(cx: &ToolContext) -> f64 { + cx.tol(5.0).max(cx.point_tol()) + } + + /// Removes the last vertex and hides the segment that followed the pointer until the pointer + /// moves again. A press in progress no longer owns a vertex, so dropping it removes nothing more. + fn take_back_vertex(&mut self) { + self.vertices.pop(); + self.hover = None; + self.pressed_vertex = false; + } + + fn clear(&mut self) { + self.vertices.clear(); + self.hover = None; + self.pressed_vertex = false; + } + + /// Closes the loop and selects inside it. A loop of fewer than three vertices selects nothing. + fn close(&mut self, cx: &ToolContext) -> Vec { + let vertices = std::mem::take(&mut self.vertices); + self.clear(); + if vertices.len() < 3 { + return vec![]; + } + vec![lasso_select(cx, &mut self.mesh, &vertices, self.add, self.sub)] + } +} + +impl Tool for PolygonalLassoTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + match ev.kind { + PointerKind::Move | PointerKind::Drag => { + self.hover = (!self.vertices.is_empty()).then(|| self.target(cx, ev.pos, ev.mods)); + vec![] + } + PointerKind::Down => { + self.pressed_vertex = false; + let reach = Self::reach(cx); + let Some(&first) = self.vertices.first() else { + self.add = ev.mods.shift; + self.sub = ev.mods.alt; + self.vertices.push(ev.pos); + self.pressed_vertex = true; + return vec![]; + }; + if first.distance(ev.pos) <= reach { + // With fewer than three vertices, a click on the first one adds nothing. + return if self.vertices.len() >= 3 { self.close(cx) } else { vec![] }; + } + let p = self.target(cx, ev.pos, ev.mods); + // The second click of a double-click lands on the vertex the first one set. + if self.vertices.last().is_some_and(|last| last.distance(p) > reach) && self.vertices.len() < MAX_VERTICES { + self.vertices.push(p); + self.pressed_vertex = true; + } + self.hover = Some(p); + vec![] + } + PointerKind::Up => { + self.pressed_vertex = false; + vec![] + } + PointerKind::DoubleClick => self.close(cx), + // The third click of a triple-click starts no loop of its own. + PointerKind::TripleClick => { + if self.vertices.len() == 1 { + self.clear(); + } + vec![] + } + } + } + + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Enter => self.close(cx), + ToolKey::Escape => { + self.clear(); + vec![] + } + ToolKey::Backspace | ToolKey::Delete => { + self.take_back_vertex(); + vec![] + } + _ => vec![], + } + } + + /// A dropped press (a second finger, a canceled touch) takes back only the vertex it set. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if std::mem::take(&mut self.pressed_vertex) { + self.take_back_vertex(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + !self.vertices.is_empty() && matches!(key, ToolKey::Enter | ToolKey::Escape | ToolKey::Backspace | ToolKey::Delete) + } + + /// A loop being drawn: Escape drops it. Keys the tool does not claim run their commands. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + !self.vertices.is_empty() + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + } + + fn options(&self) -> serde_json::Value { + self.mesh.options() + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); + let mut line = self.vertices.clone(); + line.extend(self.hover.filter(|_| !self.vertices.is_empty())); + if line.len() >= 2 { + out.push(Overlay::Path { path: crate::xform::polygon(&line, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { + Cursor::Lasso + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/addons/polygonal_lasso/tests.rs b/crates/tools/src/addons/polygonal_lasso/tests.rs new file mode 100644 index 0000000000..cf2b9e6f70 --- /dev/null +++ b/crates/tools/src/addons/polygonal_lasso/tests.rs @@ -0,0 +1,243 @@ +use super::*; +use crate::testutil::*; +use serde_json::Value; +use vectorcraft_doc::{Appearance, Document, Node, Selection}; +use vectorcraft_geom::{Rect, shapes}; + +fn click(tool: &mut dyn Tool, cx: &ToolContext, (x, y): (f64, f64), mods: Mods) -> Vec { + let mut acts = tool.pointer(cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(mods)); + acts.extend(tool.pointer(cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(mods))); + acts +} + +/// Clicks each vertex in turn with `first` held at the first click only. +fn clicks(tool: &mut dyn Tool, cx: &ToolContext, vertices: &[(f64, f64)], first: Mods) { + for (i, v) in vertices.iter().enumerate() { + let acts = click(tool, cx, *v, if i == 0 { first } else { Mods::default() }); + assert!(acts.is_empty(), "a vertex click selects nothing: {acts:?}"); + } +} + +/// The anchors each selected path has in a `select.anchorsMany` command, and its mode. +fn selected(acts: &[Action]) -> (Vec<(u64, usize)>, String) { + let [Action::Exec(c, v)] = acts else { panic!("one selection command: {acts:?}") }; + assert_eq!(c, "select.anchorsMany"); + let items = v["items"].as_array().unwrap(); + let ids = items.iter().map(|it| (it["id"].as_u64().unwrap(), it["anchors"].as_array().unwrap().len())).collect(); + (ids, v["mode"].as_str().unwrap().to_owned()) +} + +/// A triangle around the rectangle's top left corner (100, 100) only. +const CORNER: &[(f64, f64)] = &[(80.0, 80.0), (140.0, 80.0), (80.0, 140.0)]; + +#[test] +fn a_double_click_enter_or_a_click_on_the_first_vertex_closes_the_loop() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + type Closing<'a> = &'a dyn Fn(&mut dyn Tool) -> Vec; + let closings: [Closing; 3] = [ + &|t| { + let mut acts = click(t, &cx, (80.0, 141.0), Mods::default()); + acts.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 141.0))); + acts + }, + &|t| t.key(&cx, ToolKey::Enter, Mods::default()), + &|t| click(t, &cx, (82.0, 81.0), Mods::default()), + ]; + for (i, close) in closings.iter().enumerate() { + let mut tool = crate::create(ID); + assert_eq!(tool.id(), ID); + clicks(tool.as_mut(), &cx, CORNER, Mods::default()); + assert!(tool.ends_on_escape(&cx) && tool.claims_key(&cx, ToolKey::Enter), "closing {i}"); + assert_eq!(selected(&close(tool.as_mut())), (vec![(id.0, 1)], "set".to_owned()), "closing {i}"); + assert!(!tool.ends_on_escape(&cx), "closing {i}"); + } +} + +#[test] +fn a_double_click_at_a_new_point_sets_that_vertex_and_closes() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &CORNER[..2], Mods::default()); + let mut acts = click(&mut tool, &cx, (80.0, 140.0), Mods::default()); + acts.extend(click(&mut tool, &cx, (80.0, 140.0), Mods::default())); + assert!(acts.is_empty(), "{acts:?}"); + assert_eq!(tool.vertices.len(), 3, "the second click of the double-click sets no vertex"); + let acts = tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 140.0)); + assert_eq!(selected(&acts), (vec![(id.0, 1)], "set".to_owned())); + assert!(!tool.ends_on_escape(&cx)); +} + +#[test] +fn backspace_or_delete_removes_the_last_vertex() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + // (300, 300) would take in the corner at (200, 200) too. + clicks(&mut tool, &cx, &[(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)], Mods::default()); + assert!(tool.claims_key(&cx, ToolKey::Backspace)); + assert!(tool.key(&cx, ToolKey::Backspace, Mods::default()).is_empty()); + assert_eq!(tool.vertices.len(), 2); + // The preview runs along the two vertices left, not back to the removed one. + let overlays = tool.overlays(&cx); + let [Overlay::Path { path, .. }] = overlays.as_slice() else { panic!("one preview path") }; + assert_eq!(path.elements().len(), 2); + clicks(&mut tool, &cx, &[(300.0, 300.0)], Mods::default()); + assert!(tool.claims_key(&cx, ToolKey::Delete)); + assert!(tool.key(&cx, ToolKey::Delete, Mods::default()).is_empty()); + assert_eq!(tool.vertices.len(), 2); + clicks(&mut tool, &cx, &[(80.0, 140.0)], Mods::default()); + assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(id.0, 1)], "set".to_owned())); + assert!(!tool.claims_key(&cx, ToolKey::Delete), "with no loop open, Delete deletes"); +} + +#[test] +fn escape_drops_the_loop_and_leaves_the_selection() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, CORNER, Mods::default()); + assert!(tool.claims_key(&cx, ToolKey::Escape)); + assert!(tool.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(!tool.ends_on_escape(&cx) && !tool.claims_key(&cx, ToolKey::Enter)); + assert!(tool.overlays(&cx).is_empty()); + assert!(tool.key(&cx, ToolKey::Enter, Mods::default()).is_empty()); + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 140.0)).is_empty()); +} + +#[test] +fn shift_keeps_the_segment_to_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &[(100.0, 100.0)], Mods::default()); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 110.0).with_mods(shift)); + let hover = tool.hover.unwrap(); + assert!((hover.y - 100.0).abs() < 1e-9 && hover.x > 199.0, "{hover:?}"); + assert_eq!(tool.overlays(&cx).len(), 1, "the segment follows the pointer"); + click(&mut tool, &cx, (190.0, 175.0), shift); + let v = tool.vertices[1]; + assert!(((v.x - 100.0) - (v.y - 100.0)).abs() < 1e-9 && v.x > 150.0, "on the 45° line: {v:?}"); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 110.0)); + assert_eq!(tool.hover, Some(Point::new(200.0, 110.0)), "without Shift the segment goes to the pointer"); +} + +#[test] +fn shift_or_alt_at_the_first_click_adds_or_subtracts() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let alt = Mods { alt: true, ..Mods::default() }; + for (first, mode) in [(shift, "add"), (alt, "subtract"), (Mods::default(), "set")] { + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, CORNER, first); + assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(id.0, 1)], mode.to_owned())); + } + // Shift held only at a later click constrains that segment and does not add. + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &CORNER[..2], Mods::default()); + click(&mut tool, &cx, (80.0, 140.0), shift); + assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())).1, "set"); +} + +#[test] +fn a_concave_loop_leaves_out_anchors_in_its_notch() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + // An L: the bottom left corner (100, 200) is in the notch. + clicks(&mut tool, &cx, &[(60.0, 60.0), (240.0, 60.0), (240.0, 240.0), (160.0, 240.0), (160.0, 170.0), (60.0, 170.0)], Mods::default()); + let acts = tool.key(&cx, ToolKey::Enter, Mods::default()); + assert_eq!(selected(&acts), (vec![(id.0, 3)], "set".to_owned())); + let Action::Exec(_, v) = &acts[0] else { panic!() }; + let picked: Vec = v["items"][0]["anchors"].as_array().unwrap().clone(); + // The rectangle's anchors run (100, 100), (200, 100), (200, 200), (100, 200). + assert!(!picked.contains(&serde_json::json!([0, 3])), "{picked:?}"); +} + +#[test] +fn fewer_than_three_vertices_select_nothing() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &CORNER[..2], Mods::default()); + // A click on the first vertex of a two-vertex loop sets no vertex on top of it and closes nothing. + assert!(click(&mut tool, &cx, (81.0, 80.0), Mods::default()).is_empty()); + assert_eq!(tool.vertices.len(), 2); + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 81.0, 80.0)).is_empty()); + assert!(!tool.ends_on_escape(&cx)); + clicks(&mut tool, &cx, &CORNER[..2], Mods::default()); + assert!(tool.key(&cx, ToolKey::Enter, Mods::default()).is_empty()); + assert!(!tool.ends_on_escape(&cx)); + // A double-click on empty canvas: its second click sets no second vertex. + assert!(click(&mut tool, &cx, (80.0, 80.0), Mods::default()).is_empty()); + assert!(click(&mut tool, &cx, (81.0, 80.0), Mods::default()).is_empty()); + assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 81.0, 80.0)).is_empty()); + assert!(!tool.ends_on_escape(&cx)); +} + +#[test] +fn a_loop_that_crosses_itself_selects_by_the_even_odd_rule() { + // A small square in the middle of a five-pointed star, where the star's edges wind twice, and + // one in the star's top point, where they wind once. + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (middle, point) = (d.alloc_id(), d.alloc_id()); + d.insert(Some(l), 0, Node::path(middle, shapes::rectangle(Rect::new(140.0, 140.0, 160.0, 160.0)), Appearance::default_art())).unwrap(); + d.insert(Some(l), 1, Node::path(point, shapes::rectangle(Rect::new(148.0, 78.0, 152.0, 82.0)), Appearance::default_art())).unwrap(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let star: Vec<(f64, f64)> = (0..5) + .map(|k| { + let a = f64::from(-90 + 144 * k).to_radians(); + (150.0 + 100.0 * a.cos(), 150.0 + 100.0 * a.sin()) + }) + .collect(); + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &star, Mods::default()); + assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(point.0, 4)], "set".to_owned())); +} + +#[test] +fn a_dropped_press_takes_back_only_its_vertex() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &CORNER[..2], Mods::default()); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 140.0)); + assert!(tool.drop_press(&cx).is_empty()); + assert_eq!(tool.vertices, vec![Point::new(80.0, 80.0), Point::new(140.0, 80.0)]); + assert_eq!(tool.hover, None); +} + +#[test] +fn a_dropped_press_after_backspace_keeps_the_earlier_vertices() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut tool = PolygonalLassoTool::default(); + clicks(&mut tool, &cx, &CORNER[..2], Mods::default()); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 140.0)); + assert!(tool.key(&cx, ToolKey::Backspace, Mods::default()).is_empty()); + assert!(tool.drop_press(&cx).is_empty()); + assert_eq!(tool.vertices, vec![Point::new(80.0, 80.0), Point::new(140.0, 80.0)]); +} + +#[test] +fn the_tool_shows_the_lasso_cursor() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + assert_eq!(PolygonalLassoTool::default().cursor(&cx, Point::new(10.0, 10.0), Mods::default()), Cursor::Lasso); +} diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index 51756bf0fd..34bea168ea 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -747,7 +747,7 @@ hotspot = "The tip." [[cursor]] id = "Lasso" group = "Drawing and editing tools" -shown_when = ["The Lasso tool: drag a loop round anchor points and segments to select them; Shift adds to the selection, Alt takes from it.", "The Enclosing Lasso tool: draw a loop to select fully enclosed objects; Shift adds, Alt subtracts."] +shown_when = ["The Lasso tool: drag a loop round anchor points and segments to select them; Shift adds to the selection, Alt takes from it.", "The Enclosing Lasso tool: draw a loop to select fully enclosed objects; Shift adds, Alt subtracts.", "The Polygonal Lasso tool: click the corners of a loop around anchor points to select them; Shift or Alt at the first click adds or subtracts."] hotspot = "Where the loop is drawn from." [[cursor]] diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index a9de5b1e0c..a168c28396 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -686,6 +686,7 @@ mod cursor_tests { for (id, c) in [ ("lasso", Cursor::Lasso), (addons::enclosing_lasso::ID, Cursor::Lasso), + (addons::polygonal_lasso::ID, Cursor::Lasso), ("magicWand", Cursor::MagicWand), ("paintbrush", Cursor::Paintbrush), ("blobBrush", Cursor::BlobBrush), diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index 915eb35e8a..74cf0b761d 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -25,6 +25,7 @@ pub use gradient::GradientTool; pub(crate) use measure::end_point as measure_end_point; pub use measure::{MeasureTool, measure}; pub use transform::{TransformKind, TransformTool}; +pub(crate) use wand::lasso_select; pub use wand::{LassoTool, MagicWandTool}; /// Create a transform/utility tool by id (None = not one of ours). diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index 41f42718a7..e34630020f 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -77,6 +77,46 @@ fn anchors_json(v: &BTreeSet) -> Value { Value::Array(v.iter().map(|(s, a)| json!([s, a])).collect()) } +/// The selection a closed loop `poly` (even-odd) makes, for the Lasso and the Polygonal Lasso: +/// the anchor points inside it on every editable path a click can pick, and the gradient mesh +/// points inside it, which `mesh` keeps picked, with their meshes. `add` (Shift) adds to the +/// selection and `sub` (Alt) subtracts from it. +pub(crate) fn lasso_select(cx: &ToolContext, mesh: &mut MeshEdit, poly: &[Point], add: bool, sub: bool) -> Action { + // Anchors inside the loop for every editable path the Lasso may pick. + let mut hits: Vec<(NodeId, BTreeSet)> = vec![]; + let mut inside: Vec<(NodeId, usize)> = vec![]; + crate::draw2::walk_pickable(cx, |n| { + if let Some(grid) = grid_of(n) { + inside.extend(grid.points.iter().enumerate().filter(|(_, q)| point_in_polygon(poly, q.p)).map(|(i, _)| (n.id, i))); + } + if let NodeKind::Path { path, .. } = &n.kind { + let v: BTreeSet = path.anchors().filter(|(_, _, a)| point_in_polygon(poly, a.p)).map(|(s, i, _)| (s, i)).collect(); + if !v.is_empty() { + hits.push((n.id, v)); + } + } + }); + let editable = cx.doc.editable(); + hits.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); + // The mesh points inside the loop are picked, and their meshes selected whole; + // Alt deselects a mesh only when it loses its last picked point. + inside.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); + for (id, any) in mesh.lasso(&inside, add, sub) { + if any != sub { + hits.push((id, BTreeSet::new())); + } + } + let items: Vec = hits.iter().map(|(id, v)| json!({ "id": id.0, "anchors": anchors_json(v) })).collect(); + let mode = if sub { + "subtract" + } else if add { + "add" + } else { + "set" + }; + Action::Exec("select.anchorsMany".into(), json!({ "items": items, "mode": mode })) +} + impl Tool for LassoTool { fn id(&self) -> &'static str { "lasso" @@ -107,40 +147,7 @@ impl Tool for LassoTool { if poly.len() < 3 { return if add || sub { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - // Anchors inside the loop for every editable path the Lasso may pick. - let mut hits: Vec<(NodeId, BTreeSet)> = vec![]; - let mut inside: Vec<(NodeId, usize)> = vec![]; - crate::draw2::walk_pickable(cx, |n| { - if let Some(grid) = grid_of(n) { - inside.extend(grid.points.iter().enumerate().filter(|(_, q)| point_in_polygon(&poly, q.p)).map(|(i, _)| (n.id, i))); - } - if let NodeKind::Path { path, .. } = &n.kind { - let v: BTreeSet = - path.anchors().filter(|(_, _, a)| point_in_polygon(&poly, a.p)).map(|(s, i, _)| (s, i)).collect(); - if !v.is_empty() { - hits.push((n.id, v)); - } - } - }); - let editable = cx.doc.editable(); - hits.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); - // The mesh points inside the loop are picked, and their meshes selected whole; - // Alt deselects a mesh only when it loses its last picked point. - inside.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id)); - for (id, any) in self.mesh.lasso(&inside, add, sub) { - if any != sub { - hits.push((id, BTreeSet::new())); - } - } - let items: Vec = hits.iter().map(|(id, v)| json!({ "id": id.0, "anchors": anchors_json(v) })).collect(); - let mode = if sub { - "subtract" - } else if add { - "add" - } else { - "set" - }; - vec![Action::Exec("select.anchorsMany".into(), json!({ "items": items, "mode": mode }))] + vec![lasso_select(cx, &mut self.mesh, &poly, add, sub)] } _ => vec![], } diff --git a/crates/ui-egui/src/addons.rs b/crates/ui-egui/src/addons.rs index b63c32af59..ec1207ad46 100644 --- a/crates/ui-egui/src/addons.rs +++ b/crates/ui-egui/src/addons.rs @@ -12,6 +12,7 @@ pub mod image; pub mod packaging; pub mod pathtools; pub mod pen; +pub mod polygonal_lasso; pub mod select; pub mod shapes; pub mod typetools; @@ -33,6 +34,7 @@ pub fn plugin_menu() -> Vec { Item::Sub("Image Tools", image::menu()), Item::Sub("Packaging Tools", packaging::menu()), Item::Sub("Path Precision Tools", pathtools::menu()), + Item::Sub("Polygonal Lasso", polygonal_lasso::menu()), Item::Sub("Selection Tools", select::menu()), Item::Sub("Smart Pen", pen::menu()), Item::Sub("Type Tools", typetools::menu()), diff --git a/crates/ui-egui/src/addons/polygonal_lasso.rs b/crates/ui-egui/src/addons/polygonal_lasso.rs new file mode 100644 index 0000000000..e3d82199d0 --- /dev/null +++ b/crates/ui-egui/src/addons/polygonal_lasso.rs @@ -0,0 +1,8 @@ +use serde_json::json; +use vectorcraft_tools::addons::polygonal_lasso; + +use crate::menus::Item; + +pub fn menu() -> Vec { + vec![Item::Cmd("Polygonal Lasso Tool", "tool.select", json!({"tool": polygonal_lasso::ID}))] +} diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index c38cde007e..fedfe9dcfd 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -637,6 +637,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; let contour = vectorcraft_tools::addons::contour::ID; let box3d = vectorcraft_tools::addons::box3d::ID; + let polygonal = vectorcraft_tools::addons::polygonal_lasso::ID; let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect(); assert_eq!( addon, @@ -652,7 +653,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "smartPen", enclosing, contour, - box3d + box3d, + polygonal ] ); for advanced in [false, true] { @@ -669,7 +671,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); - for tool in ["extendPath", "smartPen", enclosing, contour, box3d] { + assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal]))); + for tool in ["extendPath", "smartPen", enclosing, contour, box3d, polygonal] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index faf6180840..7b468133da 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1836,6 +1836,8 @@ font-technology Variable Променливи Lasso Tool Инструмент „Ласо“ Enclosing Lasso Tool Инструмент „Обхващащо ласо“ Enclosing Lasso Обхващащо ласо + Polygonal Lasso Tool Инструмент „Многоъгълно ласо“ + Polygonal Lasso Многоъгълно ласо Last Effect: {name} Посл. ефект: {name} Last Effect: {} Посл. ефект: {} Last Effect… Посл. ефект… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index db9e97f9bc..a23e506ff6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1413,6 +1413,8 @@ lighting Light Svjetlo Lasso Tool Alat laso Enclosing Lasso Tool Alat laso za obuhvatanje Enclosing Lasso Laso za obuhvatanje + Polygonal Lasso Tool Alat poligonalni laso + Polygonal Lasso Poligonalni laso Lasso Laso Line Cut Tool Alat za rez linijom Line Graph Tool Alat za linijski grafikon diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 1705aa6811..dae8c6b7c7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2348,6 +2348,8 @@ digits Malayalam Malaiàlam Lasso Tool Eina de llaç Enclosing Lasso Tool Eina de llaç envoltant Enclosing Lasso Llaç envoltant + Polygonal Lasso Tool Eina de llaç poligonal + Polygonal Lasso Llaç poligonal Last Últim Last Artboard Últim tauler Status Bar Show Mostra a la barra d'estat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3ce4d6f0a5..2ce9c959c8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1439,6 +1439,8 @@ lighting Light Světlo Lasso Tool Nástroj Laso Enclosing Lasso Tool Nástroj obklopující laso Enclosing Lasso Obklopující laso + Polygonal Lasso Tool Nástroj Mnohoúhelníkové laso + Polygonal Lasso Mnohoúhelníkové laso Lasso Laso Line Cut Tool Nástroj Řez čarou Line Graph Tool Nástroj Spojnicový graf diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 69db2c7136..77fb05a4a0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4014,6 +4014,8 @@ lighting Light Lys Lasso Tool Lassoværktøj Enclosing Lasso Tool Omsluttende lassoværktøj Enclosing Lasso Omsluttende lasso + Polygonal Lasso Tool Polygonlassoværktøj + Polygonal Lasso Polygonlasso Lasso Lasso Line Cut Tool Linjeskæringsværktøj Line Graph Tool Linjediagramværktøj diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9adc5e4da1..6794dba0c2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1902,6 +1902,8 @@ file-filter Templates Vorlagen Lasso Tool Lasso-Werkzeug Enclosing Lasso Tool Umschließendes Lasso-Werkzeug Enclosing Lasso Umschließendes Lasso + Polygonal Lasso Tool Polygon-Lasso-Werkzeug + Polygonal Lasso Polygon-Lasso Last Effect: {name} Letzter Effekt: {name} Last Effect: {} Letzter Effekt: {} Last Effect… Letzter Effekt… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2bb03c51e9..e23161a9fa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1806,6 +1806,8 @@ font-technology Variable Μεταβλητές Lasso Tool Λάσο (Lasso Tool) Enclosing Lasso Tool Εργαλείο περικλείοντος λάσου Enclosing Lasso Περικλείον λάσο + Polygonal Lasso Tool Εργαλείο πολυγωνικού λάσου + Polygonal Lasso Πολυγωνικό λάσο Last Effect: {name} Τελευταίο εφέ: {name} Last Effect: {} Τελευταίο εφέ: {} Last Effect… Τελευταίο εφέ… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index fc63c72e93..390487d3ca 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1903,6 +1903,8 @@ font-technology Variable Variables Lasso Tool Herramienta Lazo Enclosing Lasso Tool Herramienta Lazo envolvente Enclosing Lasso Lazo envolvente + Polygonal Lasso Tool Herramienta Lazo poligonal + Polygonal Lasso Lazo poligonal Last Effect: {name} Último efecto: {name} Last Effect: {} Último efecto: {} Last Effect… Último efecto… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 59aa73a6b8..76dc83ab3f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1415,6 +1415,8 @@ lighting Light Valo Lasso Tool Lassotyökalu Enclosing Lasso Tool Sulkeva lassotyökalu Enclosing Lasso Sulkeva lasso + Polygonal Lasso Tool Monikulmiolassotyökalu + Polygonal Lasso Monikulmiolasso Lasso Lasso Line Cut Tool Viivaleikkaustyökalu Line Graph Tool Viivakaaviotyökalu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 14a0be4478..5b6973bf77 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1893,6 +1893,8 @@ font-technology Variable Variables Lasso Tool Outil Lasso Enclosing Lasso Tool Outil Lasso englobant Enclosing Lasso Lasso englobant + Polygonal Lasso Tool Outil Lasso polygonal + Polygonal Lasso Lasso polygonal Last Effect: {name} Dernier effet : {name} Last Effect: {} Dernier effet : {} Last Effect… Dernier effet… diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 3d04ff79a9..1f4a8747b9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2735,6 +2735,8 @@ Polygon બહુકોણ Polygon Properties: બહુકોણના ગુણધર્મો: Polygon Tool બહુકોણ ટૂલ + Polygonal Lasso બહુકોણીય લાસો + Polygonal Lasso Tool બહુકોણીય લાસો ટૂલ Portrait પોટ્રેટ Portuguese પોર્ટુગીઝ Position સ્થિતિ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 447b652288..53f1448a45 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3682,6 +3682,8 @@ antiAlias Sharp शार्प Polygon बहुभुज Polygon Properties: बहुभुज प्रॉपर्टीज़: Polygon Tool पॉलीगोन टूल + Polygonal Lasso बहुभुज लैस्सो + Polygonal Lasso Tool बहुभुज लैस्सो टूल Portrait पोर्ट्रेट Portrait (flipped) पोर्ट्रेट (फ्लिप) Portuguese पुर्तगाली diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e081c882b6..3266e816ec 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2372,6 +2372,8 @@ file-filter Templates Sablonok Lasso Tool Lasszó Enclosing Lasso Tool Körülzáró lasszó Enclosing Lasso Körülzáró lasszó + Polygonal Lasso Tool Sokszöglasszó + Polygonal Lasso Sokszöglasszó Last Utolsó Last commit Utolsó commit Last Effect: {name} Legutóbbi effektus: {name} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9f27f50e03..5abb84b178 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1340,6 +1340,8 @@ lighting Light Cahaya Lasso Tool Alat lasso Enclosing Lasso Tool Alat laso pengeliling Enclosing Lasso Laso pengeliling + Polygonal Lasso Tool Alat laso poligonal + Polygonal Lasso Laso poligonal Lasso Lasso Line Cut Tool Alat potong garis Line Graph Tool Alat grafik garis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b294b7da3a..86a7e3be42 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1939,6 +1939,8 @@ file-filter Templates Modelli Lasso Tool Strumento Lazo Enclosing Lasso Tool Strumento Lazo di inclusione Enclosing Lasso Lazo di inclusione + Polygonal Lasso Tool Strumento Lazo poligonale + Polygonal Lasso Lazo poligonale Last Effect: {name} Ultimo effetto: {name} Last Effect: {} Ultimo effetto: {} Last Effect… Ultimo effetto… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 56c1c1e5ec..a0bab4da05 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2230,6 +2230,8 @@ antiAlias Sharp シャープ Lasso Tool なげなわツール Enclosing Lasso Tool 囲みなげなわツール Enclosing Lasso 囲みなげなわ + Polygonal Lasso Tool 多角形なげなわツール + Polygonal Lasso 多角形なげなわ Last Effect: {name} 最後の効果:{name} Last Page 最後のページ Layer Options… レイヤーオプション… diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0f18e63a1a..e684f095ee 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3376,6 +3376,8 @@ lighting Light სინათლე Lasso Tool ლასოს ხელსაწყო Enclosing Lasso Tool შემომსაზღვრელი ლასოს ხელსაწყო Enclosing Lasso შემომსაზღვრელი ლასო + Polygonal Lasso Tool მრავალკუთხა ლასოს ხელსაწყო + Polygonal Lasso მრავალკუთხა ლასო Line Cut Tool ხაზით ჭრის ხელსაწყო Line Graph Tool ხაზოვანი დიაგრამის ხელსაწყო Line Segment Tool ხაზის სეგმენტის ხელსაწყო diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8e5a3799a5..e79832d1d6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2220,6 +2220,8 @@ antiAlias Sharp 날카롭게 Lasso Tool 올가미 도구 Enclosing Lasso Tool 둘러싸기 올가미 도구 Enclosing Lasso 둘러싸기 올가미 + Polygonal Lasso Tool 다각형 올가미 도구 + Polygonal Lasso 다각형 올가미 Last Effect: {name} 마지막 효과: {name} Last Page 마지막 페이지 Layer Options… 레이어 옵션… diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 96e9e6a985..7aff5bdfea 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1908,6 +1908,8 @@ lighting Light Licht Lasso Tool Lasso-gereedschap Enclosing Lasso Tool Omsluitend lassogereedschap Enclosing Lasso Omsluitende lasso + Polygonal Lasso Tool Veelhoekig lassogereedschap + Polygonal Lasso Veelhoekige lasso Lasso Lasso Line Cut Tool Lijnknip-gereedschap Line Graph Tool Lijndiagram-gereedschap diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 487283e406..08acb978a2 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1362,6 +1362,8 @@ lighting Light Światło Lasso Tool Narzędzie Lasso Enclosing Lasso Tool Narzędzie lassa obejmującego Enclosing Lasso Lasso obejmujące + Polygonal Lasso Tool Narzędzie lassa wielokątnego + Polygonal Lasso Lasso wielokątne Line Cut Tool Narzędzie Cięcie linią Line Graph Tool Narzędzie Wykres liniowy Line Segment Tool Narzędzie Odcinek diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index e1a8bcb11c..db5dc28560 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1603,6 +1603,8 @@ antiAlias Sharp Nítido Lasso Tool Ferramenta Laço Enclosing Lasso Tool Ferramenta Laço envolvente Enclosing Lasso Laço envolvente + Polygonal Lasso Tool Ferramenta Laço poligonal + Polygonal Lasso Laço poligonal Last Effect: {name} Último Efeito: {name} Last Effect… Último Efeito… Last Page Última Página diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f443922dd7..5b3e1f2b13 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1930,6 +1930,8 @@ file-filter Templates Шаблоны Lasso Tool Инструмент «Лассо» Enclosing Lasso Tool Инструмент «Охватывающее лассо» Enclosing Lasso Охватывающее лассо + Polygonal Lasso Tool Инструмент «Многоугольное лассо» + Polygonal Lasso Многоугольное лассо Last Effect: {name} Последний эффект: {name} Last Effect: {} Последний эффект: {} Last Effect… Последний эффект… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index f4277b7fd6..6707616de4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1852,6 +1852,8 @@ font-technology Variable Variabla Lasso Tool Lassoverktyg Enclosing Lasso Tool Omslutande lassoverktyg Enclosing Lasso Omslutande lasso + Polygonal Lasso Tool Polygonlassoverktyg + Polygonal Lasso Polygonlasso Last Effect: {name} Senaste effekten: {name} Last Effect: {} Senaste effekten: {} Last Effect… Senaste effekten… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index afd8cdce9a..3268e15ef4 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1725,6 +1725,8 @@ font-technology Variable Değişken Lasso Tool Kement Aracı Enclosing Lasso Tool Çevreleyen Kement Aracı Enclosing Lasso Çevreleyen Kement + Polygonal Lasso Tool Çokgen Kement Aracı + Polygonal Lasso Çokgen Kement Last Effect: {name} Son Etki: {name} Last Effect: {} Son Etki: {} Last Effect… Son Etki… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 682edcbd4b..274fd612a7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1933,6 +1933,8 @@ file-filter Templates Шаблони Lasso Tool Інструмент «Ласо» Enclosing Lasso Tool Інструмент «Охоплювальне ласо» Enclosing Lasso Охоплювальне ласо + Polygonal Lasso Tool Інструмент «Багатокутне ласо» + Polygonal Lasso Багатокутне ласо Last Effect: {name} Останній ефект: {name} Last Effect: {} Останній ефект: {} Last Effect… Останній ефект… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 7cbc02163d..ff2fa055ce 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2214,6 +2214,8 @@ digits Hindi Hindi Lasso Tool Công cụ Lasso Enclosing Lasso Tool Công cụ Lasso bao quanh Enclosing Lasso Lasso bao quanh + Polygonal Lasso Tool Công cụ Lasso đa giác + Polygonal Lasso Lasso đa giác Last Cuối cùng Last commit Commit cuối cùng Last Effect: {name} Hiệu ứng vừa dùng: {name} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b445c6b44f..cf9090882b 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1815,6 +1815,8 @@ file-filter Templates 模板 Lasso Tool 套索工具 Enclosing Lasso Tool 包围套索工具 Enclosing Lasso 包围套索 + Polygonal Lasso Tool 多边形套索工具 + Polygonal Lasso 多边形套索 Last Effect: {name} 最后一次效果:{name} Last Effect: {} 上次效果:{} Last Effect… 上次效果… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6f8e18baf0..03ba2e6abc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3046,6 +3046,8 @@ liquify-list-end {0}, {1} {0}和{1} Lasso Tool 套索工具 Enclosing Lasso Tool 包圍套索工具 Enclosing Lasso 包圍套索 + Polygonal Lasso Tool 多邊形套索工具 + Polygonal Lasso 多邊形套索 Last Effect: {name} 最後一次效果:{name} Last Effect: {} 上次效果:{} Last Effect… 最後一次效果… diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 3e07419bb4..a24e598ecc 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1255,6 +1255,48 @@ fn enclosing_lasso_escape_cancels_and_q_returns_to_anchor_lasso() { assert_eq!(app.session.tool_id(), "lasso"); } +/// While a Polygonal Lasso loop is open, Backspace and Delete remove its last vertex instead of +/// deleting the selected art, Enter closes it, and Escape drops it and leaves the selection. +#[test] +fn polygonal_lasso_takes_backspace_delete_enter_and_escape_while_a_loop_is_open() { + use vectorcraft_doc::NodeId; + use vectorcraft_tools::{PointerEvent, PointerKind}; + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + crate::shortcut_editor::sync(&app.ui); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + app.select_tool(vectorcraft_tools::addons::polygonal_lasso::ID); + let view = app.view_info(); + let click = |app: &mut VectorcraftApp, x: f64, y: f64| { + app.session.pointer(&PointerEvent::new(PointerKind::Down, x, y), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Up, x, y), view).unwrap(); + }; + for (x, y) in [(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)] { + click(&mut app, x, y); + } + frame(&mut app, press(Key::Backspace, Modifiers::NONE)); + assert!(app.session.active().unwrap().doc.node(id).is_some(), "Backspace leaves the selected art"); + click(&mut app, 300.0, 300.0); + frame(&mut app, press(Key::Delete, Modifiers::NONE)); + assert!(app.session.active().unwrap().doc.node(id).is_some(), "Delete leaves the selected art"); + assert!(app.session.tool_ends_on_escape(view)); + frame(&mut app, press(Key::Escape, Modifiers::NONE)); + assert!(!app.session.tool_ends_on_escape(view)); + assert_eq!(app.session.active().unwrap().selection.objects, vec![id]); + for (x, y) in [(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)] { + click(&mut app, x, y); + } + frame(&mut app, press(Key::Backspace, Modifiers::NONE)); + click(&mut app, 80.0, 140.0); + frame(&mut app, press(Key::Enter, Modifiers::NONE)); + assert!(!app.session.tool_ends_on_escape(view)); + let sel = &app.session.active().unwrap().selection; + assert_eq!(sel.objects, vec![id]); + assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(1), "only the corner inside the loop"); +} + /// Binds Show Grid to `chord`, or with `None` leaves every command its default shortcut. fn bind_grid(app: &mut VectorcraftApp, chord: Option<&str>) { app.ui.shortcut_overrides.clear(); diff --git a/crates/ui-egui/src/touch.rs b/crates/ui-egui/src/touch.rs index 48db775c31..c7be289a92 100644 --- a/crates/ui-egui/src/touch.rs +++ b/crates/ui-egui/src/touch.rs @@ -142,7 +142,8 @@ pub const FIRST_DRAWING_TOOL: &str = "pencil"; /// A tool of selection mode: one that selects objects or parts of them. fn selects(id: &str) -> bool { - vectorcraft_tools::catalog::is_selection_tool(id) || matches!(id, "magicWand" | "lasso" | "perspectiveSelection") + vectorcraft_tools::catalog::is_selection_tool(id) + || matches!(id, "magicWand" | "lasso" | "enclosingLasso" | "polygonalLasso" | "perspectiveSelection") } /// A tool of drawing mode: any tool but those of selection mode and those that only move, turn or @@ -203,7 +204,8 @@ mod tests { for id in ["pencil", "pen", "rectangle", "paintbrush", "type", "eraser", "shapeBuilder"] { assert!(is_drawing_tool(id), "{id}"); } - let selecting = ["selection", "directSelection", "groupSelection", "magicWand", "lasso", "perspectiveSelection"]; + let selecting = + ["selection", "directSelection", "groupSelection", "magicWand", "lasso", "enclosingLasso", "polygonalLasso", "perspectiveSelection"]; for id in selecting.into_iter().chain(["hand", "rotateView", "zoom", "printTiling"]) { assert!(!is_drawing_tool(id), "{id}"); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 69859c12e1..ee77f6fb95 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1146,6 +1146,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. + Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345).