Shapes: dragging a live polygon's side widget changes its number of sides

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 edges are shown. Dragging it sets the side count from 3
to 11: down adds a side and 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} in one undo step, none when the count ends
where it began, and Escape puts the count back. Typed counts keep their
3 to 1000 range. The widget is drawn only while the box is drawn, so it
hides during a move, a turn and its own drag.

The help page describes the widget and its 3 to 11 range:
https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html
The widget's look and place, the drag direction, the step and the rule
for more than 11 sides are VectorCraft's own.

Docs: docs/target-app-parity.md and docs/ui-parity.md.
This commit is contained in:
dotCooCoo
2026-11-16 14:06:47 -08:00
parent f10c3aeacc
commit 3addb0940f
10 changed files with 533 additions and 11 deletions
+1
View File
@@ -40,6 +40,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;
+30 -3
View File
@@ -53,6 +53,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};
@@ -133,6 +134,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.
@@ -797,7 +800,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.
@@ -834,6 +837,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)
@@ -917,6 +926,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(),
@@ -1094,6 +1104,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);
@@ -1201,6 +1220,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)),
@@ -1260,7 +1280,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,
@@ -1283,6 +1303,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;
}
@@ -1674,7 +1697,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);
@@ -1684,6 +1707,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![]);
+17 -6
View File
@@ -17,7 +17,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).
@@ -35,6 +36,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 ›
@@ -76,6 +78,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
@@ -257,18 +260,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
@@ -444,10 +450,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![],
@@ -779,6 +787,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![],
@@ -849,6 +858,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,
@@ -871,6 +881,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.
@@ -921,7 +932,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
+45
View File
@@ -1103,6 +1103,51 @@ 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:?}");
}
/// 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
+348
View File
@@ -0,0 +1,348 @@
//! The side widget: a small diamond beside the right side of a selected live polygon's bounding
//! box (<https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html>).
//! 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<Self> {
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) + steps
} else if steps >= 0 {
return from;
} else {
max + 1 + 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<Self> {
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 })
}
pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
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();
let sides = sides_after(self.widget.sides, if steps.is_finite() { steps as i64 } else { 0 });
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<Action> {
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<Action> {
if self.began { vec![Action::Cancel] } else { vec![] }
}
/// The side count next to the pointer.
pub fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
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<u64> {
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);
}
/// 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 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());
}
}