diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 23dbe66e71..709be444b4 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -204,8 +204,7 @@ impl Session { let _ = self.finish_tool_edit_later(); // The switch goes on whatever the lent tool's last actions did, as for the deactivation. let _ = self.give_back_tool(view); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - let _ = self.apply_actions(acts); + let _ = self.deactivate_tool(view); // A batch leaves its interaction open in the document it leaves, to keep or roll back with // the rest of the batch; anything else in progress (a drag) is cancelled. if self.batch_stash.is_none() { diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 794cc7a2a3..65ea837527 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -188,8 +188,7 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - self.apply_actions(acts)?; + self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); if let Some(selection) = text_selection { @@ -205,6 +204,18 @@ impl Session { Ok(()) } + /// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the + /// batch settled the tool's drag when it began, and the open interaction holds the batch's + /// steps, which the batch keeps or rolls back as a whole. + pub(crate) fn deactivate_tool(&mut self, view: ViewInfo) -> Result<()> { + let mut acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); + if self.batch_stash.is_some() { + acts.retain(|a| !matches!(a, Action::Cancel)); + } + self.apply_actions(acts)?; + Ok(()) + } + /// The selection tools other than Direct Selection pick whole objects: with one of them chosen, /// an object selected in a symbol instance's art gives way to the instance. The revision /// changes with it, so panels that cache by revision show the instance. @@ -297,8 +308,7 @@ impl Session { // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. let mesh_points = (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - let r = self.apply_actions(acts); + let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { @@ -311,7 +321,7 @@ impl Session { self.lent_selection = left; } self.after_command(None); - r.map(drop) + r } /// A fresh `id` tool with the options it keeps ([`settings`]): its last values, from this diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs index 3ef209efab..bce666d484 100644 --- a/crates/mcp/src/tests/shapewidgets.rs +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -1,5 +1,6 @@ -//! A shape tool's double-click on a selected live shape's corner widget through MCP: the -//! gesture's `requests` carry the Transform panel. +//! Live shape widgets through MCP: a shape tool's double-click on a selected live shape's corner +//! widget, whose gesture's `requests` carry the Transform panel, and a drag on a live polygon's +//! side widget. use serde_json::{Value, json}; use vectorcraft_tools::corners::CornerWidgets; @@ -28,3 +29,74 @@ fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); assert_eq!(off["requests"], json!([]), "{off}"); } + +/// The selected live polygon's sides, radius and transform. +fn polygon(h: &mut Headless) -> (u32, f64, vectorcraft_geom::Affine) { + let st = h.session.doc().unwrap(); + let id = st.selection.objects[0]; + let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") }; + let Some(vectorcraft_doc::LiveShape::Polygon { sides, radius, xf, .. }) = live.as_deref() else { panic!("not a live polygon: {live:?}") }; + (*sides, *radius, *xf) +} + +/// A drag down on a live polygon's side widget with the Selection tool gives it more sides in one +/// undo step, keeping its radius and transform; undo puts the count back. +#[test] +fn a_side_widget_drag_changes_a_polygons_sides_in_one_undo_step() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap(); + let st = h.session.doc().unwrap(); + let id = st.selection.objects[0]; + let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds"); + let bx = vectorcraft_doc::OrientedBox::aligned(b); + let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget"); + let steps = st.history.undo.len(); + let before = polygon(&mut h); + assert_eq!(before.0, 5); + let zoom = h.view.zoom; + let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom}); + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0), ev("up", 25.0)]})); + let after = polygon(&mut h); + assert_eq!((after.0, after.1, after.2), (7, before.1, before.2)); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + h.call("engine.execute", json!({"command": "edit.undo", "params": {}})).unwrap(); + assert_eq!(polygon(&mut h), before); + // A drag that comes back to the start leaves no undo step. + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 25.0), ev("drag", 0.0), ev("up", 0.0)]})); + assert_eq!(polygon(&mut h), before); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps); +} + +/// A batch run during a side widget drag settles the drag first. A batch step that switches +/// documents then ends the drag without undoing the batch's own steps in the document it leaves. +#[test] +fn a_batch_that_switches_documents_during_a_side_widget_drag_keeps_its_steps() { + let mut h = Headless::new(); + for _ in 0..2 { + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + } + h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap(); + let st = h.session.doc().unwrap(); + let (uid, id) = (st.uid, st.selection.objects[0]); + let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds"); + let bx = vectorcraft_doc::OrientedBox::aligned(b); + let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget"); + let steps = st.history.undo.len(); + let zoom = h.view.zoom; + let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom}); + // The drag stays held: no `up`. + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0)]})); + let batch = json!({"commands": [ + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 20, "height": 20}}, + {"command": "document.activate", "params": {"index": 0}} + ]}); + h.call("engine.execute", json!({"command": "command.batch", "params": batch})).unwrap(); + let st = h.session.documents().iter().find(|d| d.uid == uid).expect("the polygon's document"); + let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") }; + assert!(matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Polygon { sides: 7, .. })), "the settled drag: {live:?}"); + assert_eq!(st.history.undo.len(), steps + 2, "the drag and the batch, each one undo step"); + let rect = st.selection.objects[0]; + assert_ne!(rect, id, "the batch's rectangle is selected"); + assert!(st.doc.node(rect).is_some(), "the batch's rectangle stays"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 190ca54820..663e8026af 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -42,6 +42,7 @@ pub mod select; pub mod settings; pub mod shape; pub mod shaperwidget; +pub mod sidewidget; pub mod slice; pub mod symbolism; pub mod text; diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 079de9ed06..583a0e42c3 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -54,6 +54,7 @@ use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; use crate::shaperwidget; +use crate::sidewidget::{self, SideDrag}; use crate::typewidget; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids}; @@ -134,6 +135,8 @@ enum State { Corner(CornerDrag), /// Dragging a live ellipse's pie widget. Pie(PieDrag), + /// Dragging a live polygon's side widget. + Sides(SideDrag), /// Dragging a selected blend's Appearance or Easing widget. BlendWidget(BlendWidgetDrag), /// Dragging an Objects on Path group's Rotate All widget. @@ -827,7 +830,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, a polygon's side widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. @@ -864,6 +867,12 @@ impl Tool for SelectionTool { { return d.cancel(); } + if key == ToolKey::Escape + && matches!(self.state, State::Sides(_)) + && let State::Sides(d) = std::mem::take(&mut self.state) + { + return d.cancel(); + } if key == ToolKey::Escape && matches!(self.state, State::NineSlice(_)) && let State::NineSlice(d) = std::mem::take(&mut self.state) @@ -896,11 +905,15 @@ impl Tool for SelectionTool { out } - /// Switching tools during a blend widget's drag cancels it, as Escape does: its value goes back. + /// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a + /// polygon's side widget cancels it, as Escape does: its value goes back. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { match std::mem::take(&mut self.state) { State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel], - State::BlendWidget(_) => vec![], + State::Corner(c) if c.adjusting() => vec![Action::Cancel], + State::Pie(d) if d.adjusting() => vec![Action::Cancel], + State::Sides(d) => d.cancel(), + State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], other => { self.state = other; vec![] @@ -947,6 +960,7 @@ impl Tool for SelectionTool { State::Moving { began: true, .. } | State::Scaling { .. } | State::Rotating { .. } => true, State::Corner(c) => c.adjusting(), State::Pie(d) => d.adjusting(), + State::Sides(d) => d.adjusting(), State::BlendWidget(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), State::Space(d) => d.adjusting(), @@ -1126,6 +1140,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::Sides(mut d)) => { + let out = d.drag(cx, p); + self.state = State::Sides(d); + out + } + (PointerKind::Up, State::Sides(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::BlendWidget(mut d)) => { let out = d.drag(cx, p); self.state = State::BlendWidget(d); @@ -1233,6 +1256,7 @@ impl Tool for SelectionTool { }), State::Corner(c) => o.extend(c.overlays(cx)), State::Pie(d) => o.extend(d.overlays(cx)), + State::Sides(d) => o.extend(d.overlays(cx)), State::BlendWidget(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), State::Space(d) => o.extend(d.overlays(cx)), @@ -1292,7 +1316,7 @@ impl Tool for SelectionTool { State::Moving { began: true, .. } if m.alt => return Cursor::SelectionCopy, State::Moving { began: true, .. } => return if self.snapped { Cursor::ArrowHollow } else { Cursor::Arrow }, State::Corner(_) => return Cursor::CornerRadius, - State::Pie(_) | State::BlendWidget(_) => return Cursor::ArrowHollow, + State::Pie(_) | State::Sides(_) | State::BlendWidget(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, State::Space(_) => return Cursor::ArrowHollow, State::MoveAll(_) | State::Member(_) => return Cursor::Move, @@ -1323,6 +1347,9 @@ impl Tool for SelectionTool { if near_selected && pie::over_widget(cx, p) { return Cursor::ArrowHollow; } + if sidewidget::over_widget(cx, p) { + return Cursor::ArrowHollow; + } if blendwidget::over_widget(cx, p) { return Cursor::ArrowHollow; } @@ -1689,6 +1716,10 @@ impl SelectionTool { if blendwidget::over_widget(cx, p) { return vec![]; } + // A live polygon's side widget takes a plain double-click the same way. + if sidewidget::over_widget(cx, p) { + return vec![]; + } if crate::rulerguide::guide_at(cx, p).is_some() { return vec![]; } @@ -1728,7 +1759,7 @@ impl SelectionTool { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, a polygon's side widget, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1738,6 +1769,10 @@ impl SelectionTool { self.state = State::Pie(d); return Some(vec![]); } + if let Some(d) = SideDrag::hit(cx, ev) { + self.state = State::Sides(d); + return Some(vec![]); + } if let Some(d) = BlendWidgetDrag::hit(cx, ev) { self.state = State::BlendWidget(d); return Some(vec![]); diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index d4c8d4f36c..6685dd20f2 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -25,7 +25,8 @@ //! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle, //! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at //! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on -//! a live ellipse's pie widget sets its pie angle, as with the Selection tool; a drag on one of the +//! a live ellipse's pie widget sets its pie angle and a drag on a live polygon's side widget sets +//! its number of sides, as with the Selection tool; a drag on one of the //! box's eight handles scales the selection, a press on the selection's centre point (Show Center) //! moves it, and one just outside a corner of its box turns it about that centre, as the Selection //! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477). @@ -43,6 +44,7 @@ use crate::corners::{self, CornerDrag}; use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square}; use crate::pie::{self, PieDrag}; use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; +use crate::sidewidget::{self, SideDrag}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The largest corner radius the Rounded Rectangle tool draws, points: the range of General › @@ -84,6 +86,7 @@ pub fn shows_shape_widgets(id: &str) -> bool { enum WidgetDrag { Corner(CornerDrag), Pie(PieDrag), + Sides(SideDrag), } /// A drag of the selection itself, taken by a shape tool: a handle of its box scales it, the centre @@ -294,18 +297,21 @@ impl ShapeTool { self.star_ratio = o.star_ratio; } - /// A press on a corner or pie widget of the selection: the drag adjusts it. + /// A press on a corner, pie or side widget of the selection: the drag adjusts it. fn press_widget(&mut self, cx: &ToolContext, ev: &PointerEvent) -> bool { if !shows_shape_widgets(self.id) { return false; } - self.widget = CornerDrag::hit(cx, ev, false).map(WidgetDrag::Corner).or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie)); + self.widget = CornerDrag::hit(cx, ev, false) + .map(WidgetDrag::Corner) + .or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie)) + .or_else(|| SideDrag::hit(cx, ev).map(WidgetDrag::Sides)); self.widget.is_some() } - /// Is `p` over a corner or pie widget of the selection that a press would drag? + /// Is `p` over a corner, pie or side widget of the selection that a press would drag? fn over_widget(&self, cx: &ToolContext, p: Point) -> bool { - shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p)) + shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p) || sidewidget::over_widget(cx, p)) } /// The selection's box, while this tool shows it (the tools that draw a box, with a selection @@ -481,10 +487,12 @@ impl ShapeTool { PointerKind::Drag => match w { WidgetDrag::Corner(c) => c.drag(cx, ev.pos), WidgetDrag::Pie(d) => d.drag(cx, ev.pos), + WidgetDrag::Sides(d) => d.drag(cx, ev.pos), }, PointerKind::Up => match self.widget.take() { Some(WidgetDrag::Corner(c)) => c.finish(), Some(WidgetDrag::Pie(d)) => d.finish(), + Some(WidgetDrag::Sides(d)) => d.finish(), None => vec![], }, _ => vec![], @@ -823,6 +831,12 @@ impl Tool for ShapeTool { _ => vec![], } } + /// Switching tools during a drag of a corner, pie or side widget cancels it, as Escape does: + /// the shape goes back. + fn deactivate(&mut self, cx: &ToolContext) -> Vec { + if self.widget.is_some() { self.key(cx, ToolKey::Escape, Mods::default()) } else { vec![] } + } + /// ↑/↓ change a polygon's sides, a star's points or the rounded rectangle's radius while it is /// drawn; Escape turns a widget or selection drag back. fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { @@ -838,6 +852,7 @@ impl Tool for ShapeTool { (ToolKey::Escape, _) => match self.widget.take() { Some(WidgetDrag::Corner(c)) if c.adjusting() => vec![Action::Cancel], Some(WidgetDrag::Pie(d)) if d.adjusting() => vec![Action::Cancel], + Some(WidgetDrag::Sides(d)) => d.cancel(), _ => vec![], }, _ => vec![], @@ -920,6 +935,7 @@ impl Tool for ShapeTool { match &self.widget { Some(WidgetDrag::Corner(c)) => c.adjusting(), Some(WidgetDrag::Pie(d)) => d.adjusting(), + Some(WidgetDrag::Sides(d)) => d.adjusting(), None => match &self.selection { Some(SelectionDrag::Move { began, .. }) => *began, Some(SelectionDrag::Rotate { .. } | SelectionDrag::Scale { .. }) => true, @@ -956,6 +972,7 @@ impl Tool for ShapeTool { match &self.widget { Some(WidgetDrag::Corner(c)) => return c.overlays(cx), Some(WidgetDrag::Pie(d)) => return d.overlays(cx), + Some(WidgetDrag::Sides(d)) => return d.overlays(cx), None => {} } // A line on a common tangent shows that snap's guides, and its length and angle. @@ -1017,7 +1034,7 @@ impl Tool for ShapeTool { let idle = self.start.is_none(); match &self.widget { Some(WidgetDrag::Corner(_)) => return Cursor::CornerRadius, - Some(WidgetDrag::Pie(_)) => return Cursor::ArrowHollow, + Some(WidgetDrag::Pie(_) | WidgetDrag::Sides(_)) => return Cursor::ArrowHollow, None => {} } // Alt-dragging the selection leaves a copy behind; otherwise the arrow, hollow while the diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index ec911f4cfb..d52cf374d4 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1309,6 +1309,114 @@ fn a_shape_tool_drags_the_selected_shapes_widgets() { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]); } +/// With a shape tool, a drag down on a selected live polygon's side widget adds sides instead of +/// drawing, and Escape puts the count back; Line Segment draws from the widget. +#[test] +fn a_shape_tool_drags_a_polygons_side_widget() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let shape = + LiveShape::Polygon { radius: 80.0, sides: 5, xf: Affine::translate((250.0, 250.0)), radii: vec![], kinds: vec![], radii_relative: false }; + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = crate::sidewidget::SideWidget::for_tool(&c).expect("a side widget"); + let down = |px: f64| PointerEvent::new(PointerKind::Drag, w.at.x, w.at.y + px); + for tool in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(tool); + assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::ArrowHollow, "{tool}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)).is_empty(), "{tool}"); + let a = t.pointer(&c, &down(25.0)); + assert_eq!( + a, + vec![Action::Begin("Live Shape".into()), Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 7 }))], + "{tool}" + ); + assert!(t.transforming() && !t.drawing_boxed(), "{tool}"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, w.at.x, w.at.y + 25.0)), vec![Action::Commit], "{tool}"); + assert!(!t.busy(), "{tool}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)); + t.pointer(&c, &down(-13.0)); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{tool}"); + assert!(!t.busy(), "{tool}"); + } + let mut t = ShapeTool::new("lineSegment"); + assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::Crosshair); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)); + let a = t.pointer(&c, &down(25.0)); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "shape.line"), "{a:?}"); +} + +/// Switching away from a shape tool or the Selection tool during a drag of a corner, pie or side +/// widget cancels it, as Escape does: the shape goes back. After a press that has not moved there +/// is nothing to put back. +#[test] +fn a_tool_switch_cancels_a_widget_drag() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let xf = Affine::translate((100.0, 100.0)); + let rect = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let ellipse = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let polygon = live(LiveShape::Polygon { + radius: 80.0, + sides: 5, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let p = paint(); + let side = crate::sidewidget::SideWidget::for_tool(&cx(&polygon.0, &polygon.1, &p)).expect("a side widget").0.at; + // The corner widget at (110, 110), the pie widget 12 px right of (300, 150), the side widget. + let drags = [ + (&rect, Point::new(110.0, 110.0), Point::new(130.0, 130.0)), + (&ellipse, Point::new(312.0, 150.0), Point::new(200.0, 20.0)), + (&polygon, side, side + Vec2::new(0.0, 25.0)), + ]; + for ((d, s), at, to) in drags { + let c = cx(d, s, &p); + let tools: [Box; 6] = [ + Box::new(crate::select::SelectionTool::default()), + Box::new(ShapeTool::new("rectangle")), + Box::new(ShapeTool::new("roundedRectangle")), + Box::new(ShapeTool::new("ellipse")), + Box::new(ShapeTool::new("polygon")), + Box::new(ShapeTool::new("star")), + ]; + for mut t in tools { + let id = t.id(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty(), "{id} at {at:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{id} at {at:?}: {a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel], "{id} at {at:?}"); + assert!(!t.busy() && !t.transforming(), "{id} at {at:?}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, to.x, to.y)).is_empty(), "{id} at {at:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(t.busy(), "{id} at {at:?}"); + assert!(t.deactivate(&c).is_empty(), "{id} at {at:?}"); + assert!(!t.busy(), "{id} at {at:?}"); + } + } +} + /// A double-click on a corner widget of a selected live shape, with a shape tool that shows the /// widgets, asks for the Transform panel and nothing else: neither click draws, edits or begins an /// undo step, and the tool stays idle. Line Segment, a plain path, a pie widget, a hidden or diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs new file mode 100644 index 0000000000..7928238d51 --- /dev/null +++ b/crates/tools/src/sidewidget.rs @@ -0,0 +1,432 @@ +//! The side widget: a small diamond beside the right side of a selected live polygon's bounding +//! box (). +//! Dragging it down adds sides and dragging it up removes them, one side per [`STEP_PX`] screen +//! pixels along the box's own vertical axis, from 3 to 11 sides. A polygon with more than 11 +//! sides keeps its count until the drag goes up a step, which gives it 11. The drag sends +//! `object.setLiveShape`'s `sides` in one undo step, and none when the count ends where it began. +//! The Selection tool and the shape tools that show the box hit the widget, and the canvas draws it +//! from the same geometry. + +use serde_json::json; +use vectorcraft_doc::{Document, LiveShape, NodeId, NodeKind, OrientedBox, Selection}; +use vectorcraft_geom::Point; + +use crate::select::shown_box; +use crate::{Action, Overlay, PointerEvent, ToolContext}; + +/// The widget's center sits this far (screen px) outside the middle of the box's right side, clear +/// of its handle. +const OFFSET_PX: f64 = 16.0; +/// Half the widget's diagonal (screen px), as the canvas draws it. +pub const RADIUS_PX: f32 = 4.0; +/// How near (screen px) the pointer must be to hit it. +const HIT_PX: f64 = 5.0; +/// How far (screen px) the pointer moves along the box's vertical axis per side. +pub const STEP_PX: f64 = 12.0; +/// The fewest sides a drag gives. +pub const MIN_SIDES: u32 = 3; +/// The most sides a drag gives. +pub const MAX_SIDES: u32 = 11; + +/// The side widget of a selection that is exactly one editable live polygon. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SideWidget { + pub id: NodeId, + /// Center in document coordinates. + pub at: Point, + /// The polygon's side count. + pub sides: u32, +} + +impl SideWidget { + /// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document + /// point). None unless the selection is one whole editable live polygon, with no anchors or + /// segments of it selected. + pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option { + let [id] = selection.objects[..] else { return None }; + if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None }; + let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None }; + let r = bx.rect; + let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y); + (at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides }) + } + + /// The widget the tool can drag (its bounding box showing). + pub fn for_tool(cx: &ToolContext) -> Option<(Self, OrientedBox)> { + // One object or none: a larger selection's box is not measured. + if cx.selection.objects.len() != 1 { + return None; + } + let bx = shown_box(cx)?; + Some((Self::of(cx.doc, cx.selection, &bx, cx.zoom)?, bx)) + } + + /// The widget of `cx` and its box if the widget is under `p`. + fn at(cx: &ToolContext, p: Point) -> Option<(Self, OrientedBox)> { + Self::for_tool(cx).filter(|(w, _)| w.at.distance(p) <= cx.tol(HIT_PX)) + } +} + +/// Is `p` over the side widget? +pub fn over_widget(cx: &ToolContext, p: Point) -> bool { + SideWidget::at(cx, p).is_some() +} + +/// The side count a drag of `steps` (down positive) gives a polygon of `from` sides: within 3 to 11, +/// and `from` itself while a polygon of more than 11 sides has not been dragged up. +pub fn sides_after(from: u32, steps: i64) -> u32 { + let (min, max) = (i64::from(MIN_SIDES), i64::from(MAX_SIDES)); + let to = if from <= MAX_SIDES { + i64::from(from).saturating_add(steps) + } else if steps >= 0 { + return from; + } else { + (max + 1).saturating_add(steps) + }; + to.clamp(min, max) as u32 +} + +/// Dragging the side widget. +#[derive(Clone, Debug)] +pub struct SideDrag { + widget: SideWidget, + bx: OrientedBox, + start: Point, + /// The pointer has left the click. + moved: bool, + /// The undo step has begun: the count has differed from the polygon's. + began: bool, + /// The count last sent (the polygon's until the drag changes it). + sides: u32, + at: Point, +} + +impl SideDrag { + /// The drag has left the click. + pub fn adjusting(&self) -> bool { + self.moved + } + + /// Start a drag when the press `ev` is on the side widget of the selection. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let (widget, bx) = SideWidget::at(cx, ev.pos)?; + Some(Self { widget, bx, start: ev.pos, moved: false, began: false, sides: widget.sides, at: ev.pos }) + } + + /// A pointer position that is not finite leaves the count and the readout as they are. A drag + /// too long to measure counts as the most steps in its direction. + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !p.x.is_finite() || !p.y.is_finite() { + return vec![]; + } + self.at = p; + if !self.moved { + if p.distance(self.start) < cx.tol(3.0) { + return vec![]; + } + self.moved = true; + } + let down = (self.bx.to_local(p).y - self.bx.to_local(self.start).y) * cx.zoom; + let steps = (down / STEP_PX).trunc(); + if steps.is_nan() { + return vec![]; + } + // The cast saturates: an infinite count of steps becomes i64::MAX or i64::MIN. + let sides = sides_after(self.widget.sides, steps as i64); + if sides == self.sides { + return vec![]; + } + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Live Shape".into())); + } + self.sides = sides; + out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, "sides": sides }))); + out + } + + /// The release: one undo step when the count changed, and nothing kept when it came back. + pub fn finish(self) -> Vec { + match (self.began, self.sides == self.widget.sides) { + (false, _) => vec![], + (true, true) => vec![Action::Cancel], + (true, false) => vec![Action::Commit], + } + } + + /// Escape: the polygon keeps the count it had. + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } + + /// The side count next to the pointer. + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.moved || !cx.measurement_labels { + return vec![]; + } + vec![Overlay::Measure { p: self.at, text: format!("Sides: {}", self.sides) }] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::select::SelectionTool; + use crate::testutil::*; + use crate::{Cursor, Mods, PointerKind, Tool, ToolKey}; + use vectorcraft_doc::{Appearance, Node}; + use vectorcraft_geom::Affine; + + /// A document holding a live polygon of `sides` sides and radius 100 placed by `xf`, and a + /// selection of it. + fn polygon_doc(sides: u32, xf: Affine) -> (Document, NodeId, Selection) { + let live = LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false }; + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut n = Node::path(id, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, id, s) + } + + fn ev(kind: PointerKind, p: Point) -> PointerEvent { + PointerEvent::new(kind, p.x, p.y) + } + + fn sides_of(a: &[Action]) -> Vec { + a.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["sides"].as_u64() } else { None }).collect() + } + + #[test] + fn the_counts_stay_within_three_and_eleven() { + assert_eq!(sides_after(5, 1), 6); + assert_eq!(sides_after(5, -1), 4); + assert_eq!(sides_after(5, 100), 11); + assert_eq!(sides_after(5, -100), 3); + assert_eq!(sides_after(3, -1), 3); + assert_eq!(sides_after(11, 1), 11); + // Over 11: unchanged until the drag goes up, which gives 11, then 10. + assert_eq!(sides_after(40, 0), 40); + assert_eq!(sides_after(40, 5), 40); + assert_eq!(sides_after(40, -1), 11); + assert_eq!(sides_after(40, -2), 10); + assert_eq!(sides_after(1000, -100), 3); + } + + #[test] + fn the_longest_drags_stay_within_three_and_eleven() { + assert_eq!(sides_after(5, i64::MAX), 11); + assert_eq!(sides_after(5, i64::MIN), 3); + assert_eq!(sides_after(3, i64::MAX), 11); + assert_eq!(sides_after(11, i64::MAX), 11); + assert_eq!(sides_after(11, i64::MIN), 3); + assert_eq!(sides_after(40, i64::MAX), 40); + assert_eq!(sides_after(40, i64::MIN), 3); + } + + /// A drag far past the document, even one too long to measure, stops at 11 down and 3 up; a + /// pointer position that is not finite keeps the count it had. + #[test] + fn a_huge_or_invalid_drag_stays_within_three_and_eleven() { + let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + // At zoom 1 the step count is finite and past i64; at zoom 4 the distance itself is infinite. + for zoom in [1.0, 4.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let far = |y: f64| Point::new(w.at.x, y); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, far(1e308)))), [11], "zoom {zoom}"); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, far(-1e308)))), [3], "zoom {zoom}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, far(-1e308))), vec![Action::Commit]); + } + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let shown = w.at + vectorcraft_geom::Vec2::new(0.0, 24.0); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, shown))), [7]); + for bad in [Point::new(f64::NAN, w.at.y), Point::new(w.at.x, f64::INFINITY), Point::new(w.at.x, f64::NEG_INFINITY)] { + assert!(t.pointer(&c, &ev(PointerKind::Drag, bad)).is_empty(), "{bad:?}"); + } + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { p, text } if *p == shown && text == "Sides: 7"))); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, shown)), vec![Action::Commit]); + } + + /// The widget sits 16 px right of the middle of the box's right side, at any zoom; only one + /// whole editable live polygon shows it. + #[test] + fn one_whole_live_polygon_shows_the_widget() { + let (d, id, s) = polygon_doc(6, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, bx) = SideWidget::for_tool(&c).expect("a widget"); + assert_eq!((w.id, w.sides), (id, 6)); + let want = |zoom: f64| Point::new(bx.rect.x1 + 16.0 / zoom, bx.rect.center().y); + assert!(w.at.distance(want(1.0)) < 1e-9, "{w:?} {bx:?}"); + assert!(SideWidget::of(&d, &s, &bx, 4.0).unwrap().at.distance(want(4.0)) < 1e-9); + assert!(over_widget(&c, w.at) && !over_widget(&c, w.at + vectorcraft_geom::Vec2::new(0.0, 8.0))); + // Hidden with the bounding box hidden, with an anchor or segment selected, or with no zoom. + assert!(SideWidget::for_tool(&ToolContext { show_bbox: false, ..cx(&d, &s, &p) }).is_none()); + let mut part = s.clone(); + part.segments.insert(id, Default::default()); + assert!(SideWidget::of(&d, &part, &bx, 1.0).is_none()); + assert!(SideWidget::of(&d, &s, &bx, 0.0).is_none() && SideWidget::of(&d, &s, &bx, f64::NAN).is_none()); + // A locked polygon, two polygons, nothing or a plain path: none. + let mut locked = d.clone(); + locked.node_mut(id).unwrap().locked = true; + assert!(SideWidget::of(&locked, &s, &bx, 1.0).is_none()); + let mut two = d.clone(); + let other = two.alloc_id(); + let mut n = two.node(id).unwrap().clone(); + n.id = other; + let l = two.layers[0].id; + two.insert(Some(l), 0, n).unwrap(); + let mut both = s.clone(); + both.add(other); + assert!(SideWidget::of(&two, &both, &bx, 1.0).is_none()); + assert!(SideWidget::of(&d, &Selection::default(), &bx, 1.0).is_none()); + let (d, rect) = doc_with_rect(); + let mut s = Selection::default(); + s.add(rect); + let bx = OrientedBox::aligned(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0)); + assert!(SideWidget::of(&d, &s, &bx, 1.0).is_none()); + } + + /// With the Selection tool, dragging the widget down adds a side per 12 screen px and up removes + /// them, within 3 to 11, in one undo step with the count shown next to the pointer. + #[test] + fn dragging_the_widget_changes_the_sides() { + let (d, id, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + for zoom in [1.0, 2.0] { + let c = ToolContext { zoom, ..cx(&d, &s, &p) }; + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let at = |px: f64| w.at + vectorcraft_geom::Vec2::new(0.0, px / zoom); + let mut t = SelectionTool::default(); + assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::ArrowHollow); + assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty()); + // Past the click but short of a step: nothing yet. + assert!(t.pointer(&c, &ev(PointerKind::Drag, at(6.0))).is_empty()); + assert!(t.transforming()); + let a = t.pointer(&c, &ev(PointerKind::Drag, at(12.0))); + assert_eq!(a[0], Action::Begin("Live Shape".into())); + assert_eq!(a[1], Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 6 }))); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Sides: 6"))); + // The same count again sends nothing; far down stops at 11, far up at 3. + assert!(t.pointer(&c, &ev(PointerKind::Drag, at(20.0))).is_empty()); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(500.0)))), [11]); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(-500.0)))), [3]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at(-500.0))), vec![Action::Commit]); + assert!(!t.busy() && !t.transforming()); + } + // A click sends nothing, and the readout follows Measurement Labels. + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 13.0))); + let quiet = ToolContext { measurement_labels: false, ..cx(&d, &s, &p) }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + // Back at the start: the release keeps nothing. + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at))), [5]); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, w.at)), vec![Action::Cancel]); + } + + /// On a turned polygon the drag is read along the box's own vertical axis. + #[test] + fn a_turned_polygon_reads_the_drag_along_its_box() { + let xf = Affine::translate((400.0, 400.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2); + let (d, _, s) = polygon_doc(5, xf); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, bx) = SideWidget::for_tool(&c).unwrap(); + let down = bx.to_doc() * Point::new(0.0, 1.0) - bx.to_doc() * Point::ZERO; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at + down * 25.0))), [7], "{bx:?}"); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at - down * 13.0))), [4]); + } + + /// A double-click on the widget with the Selection tool does nothing: in isolation mode it does + /// not leave isolation, though no art is under the widget. + #[test] + fn a_double_click_on_the_widget_does_nothing() { + let live = LiveShape::Polygon { + radius: 100.0, + sides: 5, + xf: Affine::translate((300.0, 300.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }; + let mut d = Document::new(800.0, 800.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut n = Node::path(id, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + let group = d.alloc_id(); + d.insert(Some(l), 0, Node::group(group, vec![std::sync::Arc::new(n)])).unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = ToolContext { isolation: Some(group), ..cx(&d, &s, &p) }; + let (w, _) = SideWidget::for_tool(&c).unwrap(); + assert!(vectorcraft_doc::hit::hit_test(&d, w.at, c.hit_options()).is_none()); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, w.at)).is_empty()); + // Away from the widget and the art, the double-click leaves isolation. + let away = w.at + vectorcraft_geom::Vec2::new(40.0, 0.0); + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, away)), vec![Action::Exec("object.exitIsolation".into(), json!({}))]); + } + + /// A polygon of more than 11 sides keeps its count on a press and a drag down; the first step + /// up gives 11. + #[test] + fn a_polygon_over_eleven_sides_does_not_jump() { + let (d, _, s) = polygon_doc(40, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 40.0))).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, w.at + vectorcraft_geom::Vec2::new(0.0, 40.0))).is_empty()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + let a = t.pointer(&c, &ev(PointerKind::Drag, w.at - vectorcraft_geom::Vec2::new(0.0, 12.0))); + assert_eq!(a[0], Action::Begin("Live Shape".into())); + assert_eq!(sides_of(&a), [11]); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Sides: 11"))); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at - vectorcraft_geom::Vec2::new(0.0, 24.0)))), [10]); + } + + /// Escape during a drag puts the count back; the release after it sends nothing. + #[test] + fn escape_cancels_a_side_widget_drag() { + let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let c = cx(&d, &s, &p); + let (w, _) = SideWidget::for_tool(&c).unwrap(); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 30.0))); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty()); + } +} diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 3ac70a3c41..de05367568 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -255,6 +255,13 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: p.circle_filled(c, r, if w.area { color } else { Color32::WHITE }); p.circle_stroke(c, r, Stroke::new(1.0, color)); } + // A live polygon's side widget: a diamond beside the middle of the box's right side, drawn + // only while the box is drawn (the box hides during a turn and during a drag of the widget). + if !drawing_boxed && let Some(w) = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &b, xf.zoom) { + let (c, r) = (xf.to_screen(w.at), vectorcraft_tools::sidewidget::RADIUS_PX); + let diamond = vec![c + vec2(0.0, -r), c + vec2(r, 0.0), c + vec2(0.0, r), c + vec2(-r, 0.0)]; + p.add(Shape::convex_polygon(diamond, Color32::WHITE, Stroke::new(1.0, color))); + } } // Pie widgets (Selection tool, with View › Show Bounding Box, on live ellipses): each joined // by a line to the outline's point at its angle. They stay while one is dragged. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 7ddd6d197c..a11ffbd23e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6737,6 +6737,48 @@ fn a_selected_ellipse_shows_its_pie_widgets() { assert_eq!(widgets(&mut app), 0, "no bounding box, no widgets"); } +/// A selected live polygon shows its side widget, a white diamond beside its box, with the +/// Selection tool and the shape tools while the bounding box shows, and hides with the box while +/// the polygon is moved. +#[test] +fn a_selected_polygon_shows_its_side_widget() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.polygon", &json!({"cx": 200, "cy": 150, "radius": 60, "sides": 5})).unwrap(); + let ctx = egui::Context::default(); + // A white diamond as wide and tall as the widget. + let size = 2.0 * vectorcraft_tools::sidewidget::RADIUS_PX; + let diamond = |ps: &egui::epaint::PathShape| { + let span = |f: fn(&egui::Pos2) -> f32| { + let v: Vec = ps.points.iter().map(f).collect(); + v.iter().copied().fold(f32::MIN, f32::max) - v.iter().copied().fold(f32::MAX, f32::min) + }; + ps.closed && ps.points.len() == 4 && ps.fill == Color32::WHITE && (span(|p| p.x) - size).abs() < 0.01 && (span(|p| p.y) - size).abs() < 0.01 + }; + let widgets = |app: &mut VectorcraftApp| shapes(app, &ctx).iter().filter(|s| matches!(s, Shape::Path(ps) if diamond(ps))).count(); + app.select_tool("selection"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("polygon"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("directSelection"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("lineSegment"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("selection"); + app.run("view.boundingBox", json!({})).unwrap(); + assert_eq!(widgets(&mut app), 0, "no bounding box, no widget"); + app.run("view.boundingBox", json!({})).unwrap(); + // A move of the polygon hides the box, and the widget with it, until the release. + let view = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 150.0), view).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 150.0), view).unwrap(); + assert_eq!(widgets(&mut app), 0, "hidden while the polygon moves"); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 150.0), view).unwrap(); + assert_eq!(widgets(&mut app), 1, "back after the release"); + app.session.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + assert_eq!(widgets(&mut app), 0, "an ellipse has none"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a672d6e8f4..bb5f46c059 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1384,6 +1384,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). - **Blend spine points by marquee:** with Direct Selection, a marquee picks the spine points inside it on a selected blend, the topmost one when several are selected, and the picked points drag together as Shift-clicked ones do; Shift-marquee adds points or takes picked ones away, a plain marquee around none of them drops the picks, and Escape during the marquee keeps them. Unselected, locked and hidden blends are skipped. The spine's points are anchor points edited with Direct Selection ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/modify-spine-of-blended-objects.html)), and a boundary drag with the tool selects anchor points ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/select-anchor-points-in-paths.html)); the rules for selected, topmost and Shift are VectorCraft's own (`crates/tools/src/direct/tests.rs`, `marquee_picks_selected_blend_spine_points_which_drag_together`, `shift_marquee_toggles_selected_blend_spine_points`, `marquee_skips_unselected_locked_and_hidden_blend_spines`, `escape_cancels_a_marquee_and_keeps_the_picked_spine_points`). When no selected object is a blend, the selected-spine checks of Direct Selection's hover, press and marquee, the Anchor Point tool and the Pen return at once instead of building every blend's spine first; on 20,000 paths and 200 blends with one path selected, 500 checks took 24 µs instead of 336 ms, and the results are the same (`the_selected_spine_check_builds_no_spine_without_a_selected_blend`, `the_selected_spine_check_matches_a_filter_of_every_spine`; `selected_spine_check_timing` times it). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index db8acdeedb..cedee1ae22 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -251,6 +251,7 @@ tools, never checked side by side) isn't captured row by row. | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing | +| Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | | A shape just drawn shows its bounding box and Live Shape widgets with the shape tool still active, and the selection can be moved and turned without switching tools | done | #5477: Rectangle, Rounded Rectangle, Ellipse, Polygon and Star keep the selection's bounding box, corner widgets and pie widgets on show while they draw nothing; a drag on a corner or pie widget adjusts it (arrows step the corner kind, Escape cancels), a press on the selection's centre point (Attributes › Show Center) moves the selection — the Selection tool's move arrow, snapping and Alt copy — a press just outside a corner of the box turns it about the centre (the Selection tool's rotate zone and cursor), and a press anywhere else draws (so a second shape drawn from the first one's centre moves the first: press elsewhere or deselect first). Public descriptions: [Live Shapes](https://helpx.adobe.com/illustrator/using/live-shapes.html) (live shapes adjust without switching tools) and [CreativePro, Working with Live Shapes](https://creativepro.com/?p=23921) (a widget shows in every corner on release; drag one toward the centre to round). A drag on one of the box's handles scales the selection as the Selection tool's handles do. A double-click on a corner widget of a selected live rectangle or polygon shows and selects the Transform panel where it is (closed, docked, floating or in an icon column; a second double-click keeps it on show), and leaves the tool, the selection and the document as they were; a double-click on a pie widget, off the widgets, with Show Corner Widget off or with Line Segment does nothing, and the Selection tool's double-click on a corner widget still opens the Corners dialog. Public description: [Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) (a double-click on a corner widget of a selected live shape opens the Transform panel). Tests `a_shape_tool_drags_the_selected_shapes_widgets`, `a_shape_tool_moves_the_selection_by_its_centre_point_and_turns_it_from_a_corner`, `a_shape_tool_scales_the_selection_by_its_bounding_box_handles`, `a_double_click_on_a_corner_widget_shows_the_transform_panel`, `a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_panel` (engine), `a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel` (MCP: the `pointer_gesture` reply's `requests` carry `{"panel": "transform"}`) and `a_tools_panel_request_shows_the_panel_and_a_second_keeps_it_shown` (UI) | | Isolation mode by double-click (groups and single objects), breadcrumbs, Esc to exit | done | Single paths, compound paths, images, meshes and placed files isolate too ([helpx: Isolate objects](https://helpx.adobe.com/africa/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)); locking or hiding the layer (or a group) around the isolated object afterwards keeps clicks and marquees off it, as outside isolation mode (#5309) | | "Magnetic" moves of selected anchors with a modifier (#955 request) | missing | not a feature of the reference app as documented; under discussion |