diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index d9d210096e..40c1bfdeed 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -772,10 +772,6 @@ impl Tool for ShaperTool { use vectorcraft_geom::recognize::{Recognized, recognize}; match ev.kind { PointerKind::Down => { - if let Some(a) = crate::shaperwidget::click(cx, ev.pos) { - self.points.clear(); - return vec![a]; - } self.points = vec![ev.pos]; vec![] } @@ -820,8 +816,6 @@ impl Tool for ShaperTool { None => vec![], } } - // The mode widget answers each click of a double-click on it. - PointerKind::DoubleClick if crate::shaperwidget::over_widget(cx, ev.pos) => vec![], PointerKind::DoubleClick => vec![ Action::Exec("shaper.select".into(), json!({"point": [ev.pos.x, ev.pos.y], "source": true})), Action::SwitchTool("selection".into()), diff --git a/crates/tools/src/mirror.rs b/crates/tools/src/mirror.rs index 31253003d9..345570a9c4 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -8,6 +8,12 @@ use crate::{Action, Cursor, Mods, ToolContext}; pub const HANDLE_RADIUS: f32 = 6.0; +/// How near (screen points) a press must come to an end of the axis to take it. +pub const END_REACH: f32 = 9.0; + +/// How near (screen points) a press must come to the axis's centre or line to take it. +pub const REACH: f32 = 7.0; + #[derive(Clone, Copy, Debug)] pub struct MirrorAxis { pub id: NodeId, @@ -53,12 +59,12 @@ impl MirrorAxis { return None; } let axis = Self::of(cx.doc, cx.selection, cx.zoom)?; - if axis.ends.iter().any(|q| q.distance(p) <= cx.tol(9.0)) { + if axis.ends.iter().any(|q| q.distance(p) <= cx.tol(f64::from(END_REACH))) { return Some((axis, true)); } // The center is its own move handle. Keep it ahead of bounding-box handles when the two // happen to overlap; the rest of the axis line yields to those handles below. - if axis.center.distance(p) <= cx.tol(7.0) { + if axis.center.distance(p) <= cx.tol(f64::from(REACH)) { return Some((axis, false)); } let d = axis.ends[1] - axis.ends[0]; @@ -68,7 +74,7 @@ impl MirrorAxis { } let unit = d / length; let along = (p - axis.ends[0]).dot(unit).clamp(0.0, length); - ((axis.ends[0] + unit * along).distance(p) <= cx.tol(7.0) && !crate::select::bbox_handle_at(cx, p)).then_some((axis, false)) + ((axis.ends[0] + unit * along).distance(p) <= cx.tol(f64::from(REACH)) && !crate::select::bbox_handle_at(cx, p)).then_some((axis, false)) } } @@ -184,29 +190,4 @@ mod tests { spec.kind = RepeatKind::Mirror { angle: f64::NAN, center: Point::ZERO }; assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none()); } - - #[test] - fn a_tool_switch_cancels_a_mirror_axis_drag() { - use crate::{PointerEvent, PointerKind, Tool}; - let (mut doc, id) = doc_with_rect(); - let mut source = doc.node(id).unwrap().clone(); - source.id = doc.alloc_id(); - doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0)); - let mut selection = Selection::default(); - selection.set([id]); - let paint = paint(); - let c = cx(&doc, &selection, &paint); - let axis = MirrorAxis::of(&doc, &selection, c.zoom).unwrap(); - let mut t = crate::select::SelectionTool::default(); - assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)).is_empty()); - let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, axis.center.x + 20.0, axis.center.y)); - assert!(matches!(a.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{a:?}"); - assert_eq!(t.deactivate(&c), vec![Action::Cancel]); - assert!(!t.busy()); - // A press that has not moved the axis leaves nothing to cancel. - t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)); - assert!(t.busy()); - assert!(t.deactivate(&c).is_empty()); - assert!(!t.busy()); - } } diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index eecc6ba0fe..4eda9aa81f 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -23,7 +23,7 @@ pub const HANDLE_GAP: f64 = 22.0; pub const SLIDER_HALF: f32 = 7.0; /// How near (screen points) a press must come to a handle to take it. -const REACH: f64 = 8.0; +pub const REACH: f64 = 8.0; /// The smallest tile (source size plus spacing) a spacing slider leaves, in points. const MIN_TILE: f64 = 0.01; @@ -392,24 +392,4 @@ mod tests { assert_eq!(cursor(&c, g.rows_at), Some(Cursor::ResizeV)); assert_eq!(cursor(&c, g.corner_at), Some(Cursor::ResizeNwSe)); } - - #[test] - fn a_tool_switch_cancels_a_grid_handle_drag() { - use crate::{PointerEvent, PointerKind, Tool}; - let (doc, selection) = grid(); - let paint = paint(); - let c = cx(&doc, &selection, &paint); - let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); - let mut t = crate::select::SelectionTool::default(); - assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)).is_empty()); - let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, g.rows_at.x, g.rows_at.y + 150.0)); - assert!(preview(&a).is_some(), "{a:?}"); - assert_eq!(t.deactivate(&c), vec![Action::Cancel]); - assert!(!t.busy()); - // A press that has not changed the grid leaves nothing to cancel. - t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)); - assert!(t.busy()); - assert!(t.deactivate(&c).is_empty()); - assert!(!t.busy()); - } } diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 7304570404..ce5bbabba2 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -27,7 +27,7 @@ pub const HANDLE_GAP: f64 = 22.0; pub const INSTANCE_STEP: f64 = 16.0; /// How near (screen points) a press must come to a handle to take it. -const REACH: f64 = 8.0; +pub const REACH: f64 = 8.0; /// The most instances a radial repeat has (as `object.repeat.options` accepts them). const MAX_INSTANCES: f64 = 1000.0; @@ -681,26 +681,4 @@ mod tests { assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9}))); assert!(matches!(d.finish().as_slice(), [Action::Commit])); } - - #[test] - fn a_tool_switch_cancels_a_radial_handle_drag() { - use crate::{PointerEvent, PointerKind, Tool}; - let (doc, selection) = radial(); - let paint = paint(); - let c = cx(&doc, &selection, &paint); - let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); - let out = (h.radius_at - h.center) / 100.0; - let to = h.radius_at + out * 25.0; - let mut t = crate::select::SelectionTool::default(); - assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)).is_empty()); - let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); - assert_eq!(preview(&a), Some(&json!({"radius": 125.0})), "{a:?}"); - assert_eq!(t.deactivate(&c), vec![Action::Cancel]); - assert!(!t.busy()); - // A press that has not changed the repeat leaves nothing to cancel. - t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)); - assert!(t.busy()); - assert!(t.deactivate(&c).is_empty()); - assert!(!t.busy()); - } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index fc18a978e6..59e526e65b 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -53,7 +53,7 @@ use crate::objects_on_path::{MemberDrag, MoveAllDrag, RotateAllDrag, SpaceDrag, 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}; @@ -159,18 +159,8 @@ enum State { MoveAll(MoveAllDrag), /// Pressing or dragging the Select/Move widget of an object of an Objects on Path group. Member(MemberDrag), - /// Move or rotate a live mirror axis. - Mirror(crate::mirror::MirrorDrag), - /// Drag a grid repeat's row, column or corner handle or a spacing slider. - GridRepeat(crate::repeat_grid::GridDrag), - /// Drag a radial repeat's instances or radius handle. - RadialRepeat(crate::repeat_radial::RadialDrag), - /// Drag the divider of an Image Trace object in the Split view. - TraceSplit(crate::trace_split::SplitDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), - /// Dragging a 9-slice guide of the symbol being edited. - NineSlice(crate::nineslice::GuideDrag), /// Loaded with the text of area type or type on a path `from` by a click on its out port, or /// on its in port (`before`: the frame it goes into comes before `from` in its thread); /// `press`: where the next press went down and where the pointer is now. @@ -595,12 +585,20 @@ pub(crate) fn shown_box(cx: &ToolContext) -> Option { /// selected, is within `tol` of `p`: (object, where the point is). A press there grabs the object /// by that point — it moves the selection even where no art is painted (an unfilled shape) — as /// Direct Selection's does (#4891). -pub(crate) fn hit_center(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Point)> { +pub fn hit_center(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, Point)> { + shown_centers(cx).into_iter().find(|(_, c)| c.distance(p) <= tol) +} + +/// The selected objects whose centre point is drawn and takes a press ([`hit_center`]), with where it is. +pub fn shown_centers(cx: &ToolContext) -> Vec<(NodeId, Point)> { let (symbols, editable) = (cx.doc.symbol_boxes(), cx.doc.editable()); - cx.selection.objects.iter().copied().filter(|id| editable(*id) && crate::direct::in_scope(cx.doc, cx.isolation, *id)).find_map(|id| { - let c = cx.doc.node(id).filter(|n| n.shows_center())?.geometric_bounds_with(&symbols)?.center(); - (c.distance(p) <= tol).then_some((id, c)) - }) + cx.selection + .objects + .iter() + .copied() + .filter(|id| editable(*id) && crate::direct::in_scope(cx.doc, cx.isolation, *id)) + .filter_map(|id| Some((id, cx.doc.node(id).filter(|n| n.shows_center())?.geometric_bounds_with(&symbols)?.center()))) + .collect() } /// The bounds of object `id`, measured as [`selection_bounds`] measures the selection. @@ -672,10 +670,15 @@ fn box_hit(cx: &ToolContext, b: &OrientedBox, p: Point) -> Option { /// Whether the current selection's bounding-box handle is under `p`, using the same geometry as /// the Selection tool's press handling. -pub(crate) fn bbox_handle_at(cx: &ToolContext, p: Point) -> bool { +pub fn bbox_handle_at(cx: &ToolContext, p: Point) -> bool { shown_box(cx).is_some_and(|b| matches!(box_hit(cx, &b, p), Some(BoxHit::Handle(_)))) } +/// Where the shown bounding box's handles are, in document points: the places [`bbox_handle_at`] answers around. +pub fn bbox_handle_points(cx: &ToolContext) -> Vec { + shown_box(cx).map(|b| crate::bbox::Handle::ALL.map(|h| b.to_doc() * h.pos(b.rect)).to_vec()).unwrap_or_default() +} + /// How near (screen points) the pointer must come to an object's centre or anchor for Smart Guides /// to label it while hovering. const HOVER_REACH: f64 = 6.0; @@ -870,8 +873,8 @@ 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 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, an Image Trace divider, a ruler guide) cancels it: what it changed goes back, no copy + /// 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 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. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { @@ -889,36 +892,13 @@ impl Tool for SelectionTool { *enclosed = !*enclosed; return vec![]; } - if key == ToolKey::Escape - && matches!(self.state, State::Mirror(_)) - && let State::Mirror(d) = std::mem::take(&mut self.state) - { - return d.cancel(); - } - if key == ToolKey::Escape - && matches!(self.state, State::GridRepeat(_)) - && let State::GridRepeat(d) = std::mem::take(&mut self.state) - { - return d.cancel(); - } - if key == ToolKey::Escape - && matches!(self.state, State::RadialRepeat(_)) - && let State::RadialRepeat(d) = std::mem::take(&mut self.state) - { - 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) - { - return d.cancel(); - } + if key == ToolKey::Escape && matches!(self.state, State::Loaded { .. }) { self.state = State::Idle; return vec![]; @@ -945,19 +925,14 @@ impl Tool for SelectionTool { out } - /// Switching tools during a drag of a blend widget, a corner widget, a pie widget, a - /// polygon's side widget, a mirror axis, a grid or radial repeat's handles or an Image Trace - /// divider 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::Corner(c) if c.adjusting() => vec![Action::Cancel], State::Pie(d) if d.adjusting() => vec![Action::Cancel], State::Sides(d) => d.cancel(), - State::Mirror(d) => d.cancel(), - State::GridRepeat(d) => d.cancel(), - State::RadialRepeat(d) => d.cancel(), - State::TraceSplit(d) => d.cancel(), State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], other => { self.state = other; @@ -971,9 +946,7 @@ impl Tool for SelectionTool { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::TraceSplit(_) | State::NineSlice(_) => { - key == ToolKey::Escape - } + State::Loaded { .. } => key == ToolKey::Escape, _ => false, } } @@ -1014,10 +987,7 @@ impl Tool for SelectionTool { State::MoveAll(d) => d.adjusting(), State::Member(d) => d.adjusting(), State::Bracket(b) => b.adjusting(), - State::Mirror(d) => d.adjusting(), - State::GridRepeat(d) => d.adjusting(), - State::RadialRepeat(d) => d.adjusting(), - State::TraceSplit(d) => d.adjusting(), + _ => false, } } @@ -1035,15 +1005,6 @@ impl Tool for SelectionTool { { return out; } - // The edited symbol's 9-slice guides take precedence over every other control and the art. - if let Some(out) = self.nine_slice_guides(cx, ev) { - return out; - } - // Mirror and grid repeat controls take precedence over art and ruler guides; the mirror - // axis line and the grid's controls yield to the bounding-box handles they overlap. - if let Some(out) = self.repeat_controls(cx, ev) { - return out; - } if let Some(out) = self.guide.pointer(cx, ev) { return out; } @@ -1341,32 +1302,6 @@ impl Tool for SelectionTool { /// The pointer for the drag in progress, else the one for what a press would take: a widget, /// a ruler guide, the box's handles or rotate zone, a selected object's centre point or the art. fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { - if let State::Mirror(d) = &self.state { - return d.cursor(cx, p); - } - if let State::GridRepeat(d) = &self.state { - return d.cursor(cx); - } - if let State::RadialRepeat(d) = &self.state { - return d.cursor(cx); - } - if let State::TraceSplit(d) = &self.state { - return d.cursor(cx); - } - if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { - return Cursor::Move; - } - if matches!(self.state, State::Idle) - && !m.cmd - && !m.ctrl - && !m.alt - && let Some(cursor) = crate::mirror::cursor(cx, p) - .or_else(|| crate::repeat_grid::cursor(cx, p)) - .or_else(|| crate::repeat_radial::cursor(cx, p)) - .or_else(|| crate::trace_split::cursor(cx, p)) - { - return cursor; - } match self.state { State::Rotating { center, .. } => return Cursor::rotate_about_in_view(center, p, cx.view_angle()), State::Scaling { handle, bx, .. } => return handle_cursor(handle, bx.angle - cx.view_angle()), @@ -1647,136 +1582,6 @@ impl SelectionTool { } } - /// A press on a 9-slice guide of the edited symbol starts dragging it; the drag and the - /// release go to it. - fn nine_slice_guides(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { - if let State::NineSlice(mut d) = self.state.clone() { - return Some(match ev.kind { - PointerKind::Drag => { - let out = d.drag(cx, ev.pos); - self.state = State::NineSlice(d); - out - } - PointerKind::Up => { - self.state = State::Idle; - d.finish() - } - _ => vec![], - }); - } - if !matches!(self.state, State::Idle) { - return None; - } - match ev.kind { - PointerKind::Down => { - let d = crate::nineslice::GuideDrag::hit(cx, ev)?; - self.state = State::NineSlice(d); - self.hover = None; - Some(vec![]) - } - // The clicks of a double-click on a guide belong to it: it neither edits the art nor - // leaves symbol editing mode. - PointerKind::DoubleClick if crate::nineslice::over_guide(cx, ev.pos) => Some(vec![]), - _ => None, - } - } - - fn repeat_controls(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { - if let State::Mirror(mut d) = self.state.clone() { - match ev.kind { - PointerKind::Drag | PointerKind::Up => { - let mut out = d.drag(cx, ev.pos, ev.mods); - if ev.kind == PointerKind::Up { - out.extend(d.finish()); - self.state = State::Idle; - } else { - self.state = State::Mirror(d); - } - return Some(out); - } - _ => return Some(vec![]), - } - } - if let State::GridRepeat(mut d) = self.state.clone() { - match ev.kind { - PointerKind::Drag | PointerKind::Up => { - let mut out = d.drag(ev.pos); - if ev.kind == PointerKind::Up { - out.extend(d.finish()); - self.state = State::Idle; - } else { - self.state = State::GridRepeat(d); - } - return Some(out); - } - _ => return Some(vec![]), - } - } - if let State::RadialRepeat(mut d) = self.state.clone() { - match ev.kind { - PointerKind::Drag | PointerKind::Up => { - let mut out = d.drag(ev.pos); - if ev.kind == PointerKind::Up { - out.extend(d.finish()); - self.state = State::Idle; - } else { - self.state = State::RadialRepeat(d); - } - return Some(out); - } - _ => return Some(vec![]), - } - } - if let State::TraceSplit(mut d) = self.state.clone() { - match ev.kind { - PointerKind::Drag | PointerKind::Up => { - let mut out = d.drag(cx, ev.pos); - if ev.kind == PointerKind::Up { - out.extend(d.finish()); - self.state = State::Idle; - } else { - self.state = State::TraceSplit(d); - } - return Some(out); - } - _ => return Some(vec![]), - } - } - if matches!(self.state, State::Idle) - && ev.kind == PointerKind::Down - && let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods) - { - self.state = State::Mirror(d); - self.hover = None; - return Some(vec![]); - } - if matches!(self.state, State::Idle) - && ev.kind == PointerKind::Down - && let Some(d) = crate::repeat_grid::GridDrag::hit(cx, ev.pos, ev.mods) - { - self.state = State::GridRepeat(d); - self.hover = None; - return Some(vec![]); - } - if matches!(self.state, State::Idle) - && ev.kind == PointerKind::Down - && let Some(d) = crate::repeat_radial::RadialDrag::hit(cx, ev.pos, ev.mods) - { - self.state = State::RadialRepeat(d); - self.hover = None; - return Some(vec![]); - } - if matches!(self.state, State::Idle) - && ev.kind == PointerKind::Down - && let Some(d) = crate::trace_split::SplitDrag::hit(cx, ev.pos, ev.mods) - { - self.state = State::TraceSplit(d); - self.hover = None; - return Some(vec![]); - } - None - } - fn double_click(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Vec { self.state = State::Idle; // A threaded port: the thread breaks there. Any other port takes the double-click @@ -1792,10 +1597,6 @@ impl SelectionTool { if let Some(a) = corners::double_click(cx, p, false).or_else(|| pie::double_click(cx, p)).or_else(|| typewidget::double_click(cx, p)) { return vec![a]; } - // The Shaper Group's mode widget answers each click of a double-click on it. - if shaperwidget::over_widget(cx, p) { - return vec![]; - } if let Some(a) = release_guide_at(cx, p, m) { return vec![a]; } @@ -1878,10 +1679,6 @@ impl SelectionTool { self.state = State::Bracket(b); return Some(vec![]); } - if let Some(a) = shaperwidget::click(cx, p) { - self.state = State::Idle; - return Some(vec![a]); - } // The type widget answers a double-click only: its clicks neither drag nor deselect. if typewidget::over_widget(cx, p) { self.state = State::Idle; diff --git a/crates/tools/src/trace_split.rs b/crates/tools/src/trace_split.rs index f5949be2a4..438f1df91e 100644 --- a/crates/tools/src/trace_split.rs +++ b/crates/tools/src/trace_split.rs @@ -94,7 +94,8 @@ fn finite(p: Point) -> bool { p.x.is_finite() && p.y.is_finite() } -fn resize_cursor(d: &TraceDivider, cx: &ToolContext) -> Cursor { +/// The resize cursor along the divider `d`, turned with the image and the view. +pub fn resize_cursor(d: &TraceDivider, cx: &ToolContext) -> Cursor { crate::select::handle_cursor(crate::bbox::Handle::Right, d.angle() - cx.view_angle()) } @@ -258,27 +259,4 @@ mod tests { assert!(SplitDrag::hit(&c, Point::new(60.0, 45.0), Mods::default()).is_none(), "the center point"); assert_eq!(cursor(&c, Point::new(60.0, 33.0)), Some(Cursor::ResizeH)); } - - /// Switching away from the Selection tool during a divider drag cancels it, as Escape does: - /// the view goes back. After a press that has not moved there is nothing to put back. - #[test] - fn a_tool_switch_cancels_a_divider_drag() { - use crate::{PointerEvent, PointerKind, Tool}; - let paint = paint(); - let mut selection = Selection::default(); - let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); - selection.set([id]); - let c = cx(&doc, &selection, &paint); - let mut t = crate::select::SelectionTool::default(); - assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)).is_empty()); - let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 40.0)); - assert!(matches!(a.first(), Some(Action::Begin(_))), "{a:?}"); - assert_eq!(t.deactivate(&c), vec![Action::Cancel]); - assert!(!t.busy() && !t.transforming()); - assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 40.0)).is_empty()); - t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)); - assert!(t.busy()); - assert!(t.deactivate(&c).is_empty()); - assert!(!t.busy()); - } } diff --git a/crates/ui-egui/src/canvas/selection_widgets.rs b/crates/ui-egui/src/canvas/selection_widgets.rs new file mode 100644 index 0000000000..69ac4d534f --- /dev/null +++ b/crates/ui-egui/src/canvas/selection_widgets.rs @@ -0,0 +1,532 @@ +//! The Selection tool's on-canvas widgets as one canvas control: the symbol 9-slice guides, the Shaper mode widget, +//! the live mirror axis, the Image Trace split divider and the grid and radial repeat handles. +//! +//! Each widget is a set of parts in the canvas's press arena, so a press on one stays with the control and one +//! elsewhere reaches the tool. A part exists only where the Selection tool would let the widget take the press: a +//! bounding-box handle or a shown centre point keeps its own drag (the parts cut those discs out of their shapes), +//! and a press with Cmd, Ctrl or Alt held belongs to the tool's own gestures. The control paints, declares and +//! reports presses; [`show`] runs the modules' drag values with the presses and sends their actions to the session, +//! where one `Begin`..`Commit` is one undo step. +//! +//! PLAN: `mod selection_widgets;` in `canvas.rs` is canvas-w10's. The `craft_ui::{contract, canvas, primitives, +//! style}` and `craft::behavior` paths are assumed to be the framework crates' public paths for the items used. + +use craft::behavior::{CanvasView, Cursor, HitLevel, HitPriority, HitShape, Metrics, PartKey, PointerButton, PressPhase, PressState, Sense}; +use craft_ui::canvas::{CanvasSpace, canvas_space}; +use craft_ui::contract::{Common, Component, Cx, MeasureCx, Outcome, PaintUi, PartsCx, Props as _, Role}; +use craft_ui::primitives::{PaintShape, StrokeWidth}; +use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; +use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2}; +use vectorcraft_geom::{Point, Vec2 as DocVec}; +use vectorcraft_tools::{Action, Mods, PointerEvent, PointerKind, ToolContext}; +use vectorcraft_tools::{mirror, repeat_grid, repeat_radial, select, shaperwidget, trace_split}; + +use super::BodyKind; +use crate::cursors::tool_cursor; +use crate::VectorcraftApp; + +#[cfg(test)] +mod tests; + +/// Where a press on a bounding-box handle still counts: the circle around the handle that holds its square reach. +const BOX_HANDLE_REACH: f32 = 5.0 * std::f32::consts::SQRT_2; + +/// Which widgets the app's state shows, before the document says which exist. +#[derive(Clone, Copy, Debug)] +pub(super) struct Show { + /// The 9-slice guides: with any tool while a symbol is edited. + pub nine: bool, + /// The Selection tool with selection edges shown: the repeat widgets. + pub selecting: bool, + /// The Shaper mode widget: the Shaper and Selection tools. + pub shaper: bool, + /// The trace divider: `selecting`, and not in outline view. + pub trace: bool, +} + +/// One widget of the control; its parts share a [`PartKey`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Widget { + Nine, + Shaper, + Mirror, + Grid, + Radial, + Trace, +} + +impl Widget { + const fn key(self) -> PartKey { + match self { + Widget::Nine => PartKey::new("nine_slice"), + Widget::Shaper => PartKey::new("shaper"), + Widget::Mirror => PartKey::new("mirror"), + Widget::Grid => PartKey::new("grid_repeat"), + Widget::Radial => PartKey::new("radial_repeat"), + Widget::Trace => PartKey::new("trace_split"), + } + } + + /// Whether a press with Cmd, Ctrl or Alt held still takes the widget; the modules refuse those for the others. + const fn takes_modified(self) -> bool { + matches!(self, Widget::Nine | Widget::Shaper) + } +} + +/// A part to declare: where it is hit, and the cursor over it. +#[derive(Clone, Debug)] +struct Item { + widget: Widget, + index: u64, + hit: HitShape, + cursor: Cursor, + priority: u8, +} + +/// A grid control as drawn: its centre, and the bar a spacing slider is. +#[derive(Clone, Debug)] +struct GridMark { + at: Pos2, + bar: Option<[Pos2; 2]>, +} + +/// A radial repeat as drawn: the circle the instances sit on, and its handles, the splitter with its line across. +#[derive(Clone, Debug)] +struct RadialMark { + circle: Option<(Pos2, f32)>, + handles: Vec<(Pos2, Option<[Pos2; 2]>)>, +} + +/// The Shaper widget as drawn. +#[derive(Clone, Debug)] +struct ShaperMark { + at: Pos2, + construction: bool, + color: DataColor, +} + +/// Everything the control draws and declares in one pass, in screen points. +#[derive(Clone, Debug, Default)] +pub(super) struct Layout { + nine: Vec<[Pos2; 2]>, + shaper: Option, + mirror: Option<([Pos2; 2], Pos2)>, + trace: Option<[Pos2; 2]>, + grid: Vec, + radial: Option, + items: Vec, +} + +fn doc_rgb(rgb: [u8; 3]) -> DataColor { + DataColor::new(Color32::from_rgb(rgb[0], rgb[1], rgb[2])) +} + +impl Layout { + fn item(&mut self, widget: Widget, hit: HitShape, cursor: Cursor, priority: u8) { + let index = self.items.len() as u64; + self.items.push(Item { widget, index, hit, cursor, priority }); + } + + /// The widgets `show` allows, placed through `view`, with the parts the tool would let take a press. + pub(super) fn of(cx: &ToolContext, view: &CanvasView, show: Show) -> Self { + let mut l = Layout::default(); + let at = |p: Point| view.to_screen(p); + let boxes: Vec<(Pos2, f32)> = select::bbox_handle_points(cx).into_iter().map(|p| (at(p), BOX_HANDLE_REACH)).collect(); + let centre_reach = (cx.point_tol() * cx.zoom) as f32; + let centres = select::shown_centers(cx).into_iter().map(|(_, p)| (at(p), centre_reach)); + let move_cursor = tool_cursor(vectorcraft_tools::Cursor::Move); + + if show.nine + && let Some(e) = cx.doc.edited_nine_slice() + { + for (_, a, b) in e.lines() { + let ends = [at(a), at(b)]; + if ends.iter().all(|p| p.is_finite()) { + l.nine.push(ends); + l.item(Widget::Nine, HitShape::polyline(ends.to_vec(), false), move_cursor, 0); + } + } + } + if show.shaper + && let Some(w) = shaperwidget::ShaperWidget::of(cx.doc, cx.selection, cx.isolation, cx.zoom) + && at(w.at).is_finite() + { + let c = at(w.at); + l.shaper = Some(ShaperMark { at: c, construction: w.construction, color: doc_rgb(cx.doc.layer_color(w.group)) }); + let arrow = tool_cursor(vectorcraft_tools::Cursor::Arrow); + l.item(Widget::Shaper, HitShape::circle(c, shaperwidget::RADIUS_PX + 1.0), arrow, 0); + } + if show.selecting && cx.show_bbox { + l.repeat_widgets(cx, view, &boxes); + if show.trace && !cx.outline { + l.trace_divider(cx, view, boxes.iter().copied().chain(centres).collect()); + } + } + l + } + + fn repeat_widgets(&mut self, cx: &ToolContext, view: &CanvasView, boxes: &[(Pos2, f32)]) { + let at = |p: Point| view.to_screen(p); + if let Some(axis) = mirror::MirrorAxis::of(cx.doc, cx.selection, cx.zoom) { + let (ends, centre) = (axis.ends.map(at), at(axis.center)); + if centre.is_finite() && ends.iter().all(|p| p.is_finite()) { + self.mirror = Some((ends, centre)); + let line = HitShape::polyline_within(ends.to_vec(), false, mirror::REACH); + self.item(Widget::Mirror, HitShape::excluding(line, boxes.to_vec()), tool_cursor(vectorcraft_tools::Cursor::Move), 0); + for (end, doc_end) in ends.iter().zip(axis.ends) { + if let Some(c) = mirror::cursor(cx, doc_end) { + self.item(Widget::Mirror, HitShape::circle(*end, mirror::END_REACH), tool_cursor(c), 1); + } + } + self.item(Widget::Mirror, HitShape::circle(centre, mirror::REACH), tool_cursor(vectorcraft_tools::Cursor::Move), 1); + } + } + if let Some(g) = repeat_grid::GridHandles::of(cx.doc, cx.selection, select::selection_box(cx), cx.zoom) { + let half = f64::from(repeat_grid::SLIDER_HALF) / cx.zoom; + for (part, p) in g.parts() { + let c = at(p); + if !c.is_finite() { + continue; + } + let bar = part.is_slider().then(|| { + let along = if part == repeat_grid::GridPart::HSpacing { DocVec::new(0.0, half) } else { DocVec::new(half, 0.0) }; + [at(p - along), at(p + along)] + }); + self.grid.push(GridMark { at: c, bar }); + if let Some(cursor) = repeat_grid::cursor(cx, p) { + let disc = HitShape::circle(c, repeat_grid::REACH as f32); + self.item(Widget::Grid, HitShape::excluding(disc, boxes.to_vec()), tool_cursor(cursor), 1); + } + } + } + if let Some(h) = repeat_radial::RadialHandles::of(cx.doc, cx.selection, select::selection_box(cx), cx.zoom) { + let centre = at(h.center); + let r = (h.radius * cx.zoom) as f32; + let circle = (centre.is_finite() && r.is_finite() && r > 0.5 && r < 20_000.0).then_some((centre, r)); + let mut mark = RadialMark { circle, handles: vec![] }; + for (part, p) in h.parts() { + let c = at(p); + if !c.is_finite() { + continue; + } + let across = (c - centre).normalized() * (repeat_radial::HANDLE_RADIUS + 4.0); + let bar = (part == repeat_radial::RadialPart::Splitter && across.is_finite()).then_some([c - across, c + across]); + mark.handles.push((c, bar)); + if let Some(cursor) = repeat_radial::cursor(cx, p) { + let disc = HitShape::circle(c, repeat_radial::REACH as f32); + self.item(Widget::Radial, HitShape::excluding(disc, boxes.to_vec()), tool_cursor(cursor), 1); + } + } + self.radial = Some(mark); + } + } + + fn trace_divider(&mut self, cx: &ToolContext, view: &CanvasView, holes: Vec<(Pos2, f32)>) { + let Some(d) = trace_split::TraceDivider::of(cx.doc, cx.selection, cx.zoom) else { return }; + let ends = d.ends.map(|p| view.to_screen(p)); + if ends.iter().all(|p| p.is_finite()) { + self.trace = Some(ends); + let line = HitShape::polyline_within(ends.to_vec(), false, trace_split::HIT_PX as f32); + self.item(Widget::Trace, HitShape::excluding(line, holes), tool_cursor(trace_split::resize_cursor(&d, cx)), 0); + } + } +} + +/// The style of the widgets: a halo under the accent, and the size of a handle. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub(super) struct WidgetStyle { + #[style(metrics)] + metrics: Metrics, + halo: StyleColor, + accent: StyleColor, + handle: f32, +} + +/// The selection widgets of a canvas. +#[derive(craft_ui::contract::Component, craft_ui::contract::Props)] +#[component(canvas_control)] +pub(super) struct SelectionWidgets { + #[common] + common: Common, + layout: Layout, + presses: Vec<(Widget, PressState)>, +} + +impl SelectionWidgets { + fn new(layout: Layout) -> Self { + SelectionWidgets { common: Common::new(), layout, presses: vec![] }.label("Selection widgets") + } +} + +/// What the control reports: the presses on its parts this pass. +pub(super) struct WidgetsOutput { + response: Response, + presses: Vec<(Widget, PressState)>, +} + +impl Outcome for WidgetsOutput { + type Value = (); + + fn response(&self) -> &Response { + &self.response + } +} + +impl Component for SelectionWidgets { + const ROLE: Role = Role::GROUP; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = WidgetStyle; + type Output = WidgetsOutput; + + fn style(cx: &StyleCx<'_>, _: SelectionWidgetsStyleKey) -> WidgetStyle { + let tokens = cx.tokens; + WidgetStyle { + metrics: Metrics::new(), + halo: cx.color(tokens.color.overlay.halo), + accent: cx.color(tokens.color.accent.solid), + handle: tokens.size.handle.md, + } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::ZERO + } + + /// The parts of the widgets. The modules' drags refuse Cmd, Ctrl and Alt, so with one held (and no gesture of + /// the control running) their parts are not declared and the press reaches the tool. + fn parts(&mut self, _rect: Rect, cx: &mut PartsCx<'_, Self>) { + let mods = craft_ui::runtime::pointer::frame(cx.ui.ctx()).mods; + let modified = (mods.cmd || mods.ctrl || mods.alt) && !cx.gesture_running(); + for item in self.layout.items.iter().filter(|item| item.widget.takes_modified() || !modified) { + cx.part(item.widget.key().at(item.index), item.hit.clone()) + .sense(Sense::DRAG | Sense::CLICK) + .priority(HitPriority::new(HitLevel::Edge, item.priority)) + .cursor(item.cursor); + } + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + for item in &self.layout.items { + if let Some(result) = cx.part_if_declared(item.widget.key().at(item.index)) + && result.press.phase.is_press() + { + self.presses.push((item.widget, result.press)); + } + } + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let (style, l) = (&cx.style, &self.layout); + let r = style.handle / 2.0; + let draw = ui.draw(); + draw.clipped(cx.rect, |draw| { + for ends in &l.nine { + draw.dashed(ends, draw.dashes(), StrokeWidth::Thin, style.accent); + } + if let Some(w) = &l.shaper { + let circle = PaintShape::Circle(w.at, r); + draw.fill(&circle, style.halo); + draw.stroke(&circle, StrokeWidth::Thin, w.color); + let d = if w.construction { -1.0 } else { 1.0 }; + let tip = w.at + Vec2::new(0.5 * r * d, 0.0); + let back = [w.at + Vec2::new(-0.33 * r * d, -0.5 * r), w.at + Vec2::new(-0.33 * r * d, 0.5 * r)]; + draw.data_fill(&PaintShape::Polygon(vec![tip, back[0], back[1]]), w.color); + } + if let Some((ends, centre)) = &l.mirror { + let line = PaintShape::Path(ends.to_vec()); + draw.stroke(&line, StrokeWidth::Thick, style.halo); + draw.stroke(&line, StrokeWidth::Medium, style.accent); + for end in ends { + let disc = PaintShape::Circle(*end, r); + draw.fill(&disc, style.halo); + draw.stroke(&disc, StrokeWidth::Medium, style.accent); + } + let square = PaintShape::Rect(Rect::from_center_size(*centre, Vec2::splat(style.handle)), CornerRadius::same(2)); + draw.fill(&square, style.accent); + draw.stroke(&square, StrokeWidth::Medium, style.halo); + } + if let Some(ends) = &l.trace { + let line = PaintShape::Path(ends.to_vec()); + draw.stroke(&line, StrokeWidth::Thick, style.halo); + draw.stroke(&line, StrokeWidth::Thin, style.accent); + let (mid, along) = (ends[0] + (ends[1] - ends[0]) * 0.5, ends[1] - ends[0]); + let length = along.length(); + if length > 1.0 { + let half = along / length * trace_split::GRIP_HALF.min(length * 0.5); + let grip = PaintShape::Path(vec![mid - half, mid + half]); + draw.stroke(&grip, StrokeWidth::Heavy, style.halo); + draw.stroke(&grip, StrokeWidth::Thick, style.accent); + } + } + for g in &l.grid { + match g.bar { + Some(bar) => { + let bar = PaintShape::Path(bar.to_vec()); + draw.stroke(&bar, StrokeWidth::Heavy, style.halo); + draw.stroke(&bar, StrokeWidth::Medium, style.accent); + } + None => handle(draw, g.at, r, style), + } + } + if let Some(m) = &l.radial { + if let Some((centre, radius)) = m.circle { + let ring = PaintShape::Circle(centre, radius); + draw.stroke(&ring, StrokeWidth::Thick, style.halo); + draw.stroke(&ring, StrokeWidth::Thin, style.accent); + } + for (at, bar) in &m.handles { + if let Some(bar) = bar { + let bar = PaintShape::Path(bar.to_vec()); + draw.stroke(&bar, StrokeWidth::Thick, style.halo); + draw.stroke(&bar, StrokeWidth::Medium, style.accent); + } + handle(draw, *at, r, style); + } + } + }); + } + + fn finish(self, cx: Cx<'_, Self>) -> WidgetsOutput { + WidgetsOutput { response: cx.response.clone(), presses: self.presses } + } +} + +fn handle(draw: &craft_ui::primitives::Draw<'_>, at: Pos2, radius: f32, style: &WidgetStyle) { + let disc = PaintShape::Circle(at, radius); + draw.fill(&disc, style.halo); + draw.stroke(&disc, StrokeWidth::Medium, style.accent); +} + +/// The drag a press on a widget runs: the module's own value, which previews through the engine's grouping. +#[derive(Clone, Debug)] +pub(super) enum Drag { + Mirror(mirror::MirrorDrag), + Grid(repeat_grid::GridDrag), + Radial(repeat_radial::RadialDrag), + Trace(trace_split::SplitDrag), + Nine(vectorcraft_tools::nineslice::GuideDrag), +} + +impl Drag { + /// The drag a press at `p` begins on `widget`, none where the module refuses it (modifiers, a bounding-box + /// handle) or the widget is the Shaper's, which only clicks. + fn hit(widget: Widget, cx: &ToolContext, p: Point, mods: Mods) -> Option { + match widget { + Widget::Mirror => mirror::MirrorDrag::hit(cx, p, mods).map(Drag::Mirror), + Widget::Grid => repeat_grid::GridDrag::hit(cx, p, mods).map(Drag::Grid), + Widget::Radial => repeat_radial::RadialDrag::hit(cx, p, mods).map(Drag::Radial), + Widget::Trace => trace_split::SplitDrag::hit(cx, p, mods).map(Drag::Trace), + Widget::Nine => vectorcraft_tools::nineslice::GuideDrag::hit(cx, &PointerEvent::new(PointerKind::Down, p.x, p.y)).map(Drag::Nine), + Widget::Shaper => None, + } + } + + fn drag(&mut self, cx: &ToolContext, p: Point, mods: Mods) -> Vec { + match self { + Drag::Mirror(d) => d.drag(cx, p, mods), + Drag::Grid(d) => d.drag(p), + Drag::Radial(d) => d.drag(p), + Drag::Trace(d) => d.drag(cx, p), + Drag::Nine(d) => d.drag(cx, p), + } + } + + fn finish(self) -> Vec { + match self { + Drag::Mirror(d) => d.finish(), + Drag::Grid(d) => d.finish(), + Drag::Radial(d) => d.finish(), + Drag::Trace(d) => d.finish(), + Drag::Nine(d) => d.finish(), + } + } + + fn cancel(self) -> Vec { + match self { + Drag::Mirror(d) => d.cancel(), + Drag::Grid(d) => d.cancel(), + Drag::Radial(d) => d.cancel(), + Drag::Trace(d) => d.cancel(), + Drag::Nine(d) => d.cancel(), + } + } +} + +/// One step of a press on a widget, in document points. +#[derive(Clone, Copy, Debug)] +pub(super) enum Gesture { + /// The button went down at the point. + Press(Point), + /// The pointer moved past the slop. + Move(Point), + /// The button went up after a drag or a hold. + Release, + /// The button went up where it went down: the Shaper widget's click. + Click(Point), + /// The press ended without a release (Escape, a lost pointer). + Cancel, +} + +/// The actions `g` gives for the press on `widget` whose drag is `drag`, which this updates. +pub(super) fn plan(app: &mut VectorcraftApp, drag: &mut Option, widget: Widget, g: Gesture, mods: Mods) -> Vec { + let view = app.view_info(); + // PLAN: assumed `Session::with_tool_context(&mut self, view: ViewInfo, f: impl FnOnce(&ToolContext) -> R) -> R` (canvas-w25, tooling.rs). + app.session.with_tool_context(view, |cx| match g { + Gesture::Press(p) => { + *drag = Drag::hit(widget, cx, p, mods); + vec![] + } + Gesture::Move(p) => drag.as_mut().map(|d| d.drag(cx, p, mods)).unwrap_or_default(), + Gesture::Release => drag.take().map(Drag::finish).unwrap_or_default(), + Gesture::Cancel => drag.take().map(Drag::cancel).unwrap_or_default(), + Gesture::Click(p) => shaperwidget::click(cx, p).into_iter().collect(), + }) +} + +/// [`plan`], with the actions applied to the session. +pub(super) fn advance(app: &mut VectorcraftApp, drag: &mut Option, widget: Widget, g: Gesture, mods: Mods) { + let actions = plan(app, drag, widget, g, mods); + if !actions.is_empty() { + // PLAN: assumed `canvas::drag::apply_requests(app, Result>)` survives the cutover. + let result = app.session.apply_actions(actions); + super::drag::apply_requests(app, result); + } +} + +fn tool_mods(m: craft::keymap::Mods) -> Mods { + Mods { cmd: m.cmd, ctrl: m.ctrl, alt: m.alt, shift: m.shift } +} + +/// Shows the widgets over the document and runs the presses on them. Runs before the tool host, so a press on a part +/// never reaches the tool. +pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSpace, win: super::Win, kind: BodyKind) { + if kind != BodyKind::Live || app.ui.screen_mode == 3 { + return; + } + let tool = app.session.tool_id(); + let revolve_edit = app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active); + let selecting = tool == "selection" && app.ui.view.edges && !revolve_edit; + let visible = Show { nine: true, selecting, shaper: matches!(tool, "shaper" | "selection") && !revolve_edit, trace: selecting && !app.outline_view() }; + let info = app.view_info(); + let layout = app.session.with_tool_context(info, |cx| Layout::of(cx, &space.view, visible)); + let out = SelectionWidgets::new(layout).show(ui); + let id = super::canvas_id(win).with("selection_widget_drag"); + let mut drag: Option = ui.data(|d| d.get_temp::>(id)).flatten(); + for (widget, press) in out.presses { + if !press.phase.start().is_some_and(|s| s.button == PointerButton::Primary) { + continue; + } + let g = match press.phase { + PressPhase::Down { start } => Gesture::Press(space.view.to_doc(start.origin)), + PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => Gesture::Move(space.view.to_doc(pos)), + PressPhase::Release { pos, click, .. } if widget == Widget::Shaper && click => Gesture::Click(space.view.to_doc(pos)), + PressPhase::Release { .. } => Gesture::Release, + PressPhase::Cancel { .. } => Gesture::Cancel, + _ => continue, + }; + advance(app, &mut drag, widget, g, tool_mods(press.mods)); + } + ui.data_mut(|d| d.insert_temp(id, drag)); +} diff --git a/crates/ui-egui/src/canvas/selection_widgets/tests.rs b/crates/ui-egui/src/canvas/selection_widgets/tests.rs new file mode 100644 index 0000000000..96a72d1d1a --- /dev/null +++ b/crates/ui-egui/src/canvas/selection_widgets/tests.rs @@ -0,0 +1,272 @@ +use super::*; +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_doc::pattern::RepeatKind; +use vectorcraft_engine::Session; + +// PLAN: these drive `Layout::of` and `advance` (the control's own steps) with the document points a press reports; +// a one-pass canvas harness for the real input path belongs to canvas-w32's fixture. + +const ALL: Show = Show { nine: true, selecting: true, shaper: true, trace: true }; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("selection"); + app +} + +fn view(app: &VectorcraftApp) -> CanvasView { + app.view().unwrap().canvas(app.ui_scaling(), Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))) +} + +fn layout(app: &mut VectorcraftApp, show: Show) -> Layout { + let (view, info) = (view(app), app.view_info()); + app.session.with_tool_context(info, |cx| Layout::of(cx, &view, show)) +} + +fn widgets(l: &Layout, w: Widget) -> usize { + l.items.iter().filter(|i| i.widget == w).count() +} + +fn node(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::Node { + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap() +} + +/// Presses at screen point `from`, drags to `to` in two moves and releases. +fn drag_through(app: &mut VectorcraftApp, widget: Widget, from: Pos2, to: Pos2) -> Option { + let v = view(app); + let mut drag = None; + let mid = from + (to - from) * 0.5; + for g in [Gesture::Press(v.to_doc(from)), Gesture::Move(v.to_doc(mid)), Gesture::Move(v.to_doc(to)), Gesture::Release] { + advance(app, &mut drag, widget, g, Mods::default()); + } + drag +} + +fn first_at(l: &Layout, w: Widget) -> Pos2 { + match &l.items.iter().find(|i| i.widget == w).unwrap().hit { + HitShape::Circle { center, .. } => *center, + other => other.bounds().center(), + } +} + +fn mirror_app() -> (VectorcraftApp, u64) { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 80})).unwrap(); + let id = app.run("object.repeat.mirror", json!({})).unwrap()["id"].as_u64().unwrap(); + (app, id) +} + +fn grid_of(app: &VectorcraftApp, id: u64) -> (u32, u32, f64) { + let NodeKind::Repeat(spec) = &node(app, id).kind else { panic!("a repeat") }; + let RepeatKind::Grid { rows, cols, h_spacing, .. } = spec.kind else { panic!("a grid") }; + (rows, cols, h_spacing) +} + +fn radial_of(app: &VectorcraftApp, id: u64) -> (u32, f64) { + let NodeKind::Repeat(spec) = &node(app, id).kind else { panic!("a repeat") }; + let RepeatKind::Radial { instances, radius, .. } = spec.kind else { panic!("a radial") }; + (instances, radius) +} + +#[test] +fn the_shaper_widget_points_to_the_other_mode() { + let mut app = app(); + for x in [0, 50] { + app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + app.run("shaper.scribble", &json!({"points": [[25, 20], [75, 35], [30, 50], [125, 65]]})).unwrap(); + let mark = layout(&mut app, ALL).shaper.unwrap(); + assert!(!mark.construction); + let v = view(&app); + let mut drag = None; + advance(&mut app, &mut drag, Widget::Shaper, Gesture::Click(v.to_doc(mark.at)), Mods::default()); + assert!(layout(&mut app, ALL).shaper.unwrap().construction, "a press switches to Construction mode"); + advance(&mut app, &mut drag, Widget::Shaper, Gesture::Click(v.to_doc(mark.at)), Mods::default()); + assert!(!layout(&mut app, ALL).shaper.unwrap().construction, "and back"); +} + +#[test] +fn mirror_axis_tracks_selection_options_and_view_without_editing_art() { + let (mut app, _) = mirror_app(); + let revision = app.session.active().unwrap().revision; + let l = layout(&mut app, ALL); + let (ends, centre) = l.mirror.unwrap(); + assert!(ends.iter().all(|e| e.distance(centre) > 10.0)); + app.view_mut().unwrap().zoom *= 2.0; + let zoomed = layout(&mut app, ALL).mirror.unwrap(); + assert_ne!(zoomed.1, centre, "the axis follows the view"); + assert!(layout(&mut app, Show { selecting: false, ..ALL }).mirror.is_none(), "not with Edges hidden"); + app.run("select.none", json!({})).unwrap(); + assert!(layout(&mut app, ALL).mirror.is_none()); + assert_eq!(app.session.active().unwrap().revision, revision, "showing the axis edits nothing"); +} + +#[test] +fn mirror_axis_drag_uses_canvas_coordinates_in_a_zoomed_rotated_view() { + let (mut app, id) = mirror_app(); + app.view_mut().unwrap().zoom = 1.5; + app.view_mut().unwrap().rotation = 30.0; + let before = node(&app, id); + let l = layout(&mut app, ALL); + let (_, centre) = l.mirror.unwrap(); + let to = centre + Vec2::new(30.0, 10.0); + drag_through(&mut app, Widget::Mirror, centre, to); + let v = view(&app); + let moved = v.to_doc(to) - v.to_doc(centre); + let st = app.session.active().unwrap(); + let axis = mirror::MirrorAxis::of(&st.doc, &st.selection, 1.0).unwrap(); + let NodeKind::Repeat(old) = &before.kind else { panic!() }; + let RepeatKind::Mirror { center: was, .. } = old.kind else { panic!() }; + assert!((axis.center - was - moved).hypot() < 1e-6, "{:?} vs {moved:?}", axis.center - was); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app, id), before, "one undo step"); +} + +#[test] +fn trace_split_divider_drag_in_a_zoomed_rotated_view_is_one_undo_step() { + let mut app = app(); + let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png()); + app.run("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); + app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + app.run("imageTrace.setView", json!({"view": "split"})).unwrap(); + app.view_mut().unwrap().zoom = 1.5; + app.view_mut().unwrap().rotation = 30.0; + let l = layout(&mut app, ALL); + let [a, b] = l.trace.unwrap(); + let (from, along) = (a + (b - a) * 0.25, b - a); + let to = from + Vec2::new(-along.y, along.x).normalized() * 20.0; + let before = app.session.active().unwrap().doc.clone(); + drag_through(&mut app, Widget::Trace, from, to); + assert!(!std::sync::Arc::ptr_eq(&before, &app.session.active().unwrap().doc), "the split moved"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(*app.session.active().unwrap().doc, *before, "one undo step puts it back"); +} + +#[test] +fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 40, "height": 40})).unwrap(); + let id = app.run("object.repeat.grid", json!({"hSpacing": 10, "vSpacing": 10})).unwrap()["id"].as_u64().unwrap(); + let (rows, ..) = grid_of(&app, id); + let l = layout(&mut app, ALL); + let rows_handle = l.grid[0].at; + let step = 50.0 * view(&app).zoom as f32; + drag_through(&mut app, Widget::Grid, rows_handle, rows_handle + Vec2::new(0.0, 2.0 * step)); + assert_eq!(grid_of(&app, id).0, rows + 2); + let l = layout(&mut app, ALL); + let slider = l.grid.iter().find(|g| g.bar.is_some()).unwrap().at; + let spacing = grid_of(&app, id).2; + drag_through(&mut app, Widget::Grid, slider, slider + Vec2::new(6.0, 0.0)); + assert!(grid_of(&app, id).2 > spacing); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!((grid_of(&app, id).0, grid_of(&app, id).2), (rows + 2, spacing), "the spacing was its own step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(grid_of(&app, id).0, rows, "and the rows theirs"); +} + +#[test] +fn radial_repeat_handles_set_instances_and_radius_in_one_undo_step_each() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + let id = app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap()["id"].as_u64().unwrap(); + let l = layout(&mut app, ALL); + let instances = l.radial.as_ref().unwrap().handles[0].0; + drag_through(&mut app, Widget::Radial, instances, instances + Vec2::new(0.0, 2.0 * repeat_radial::INSTANCE_STEP as f32)); + assert_eq!(radial_of(&app, id), (8, 60.0)); + let l = layout(&mut app, ALL); + let (centre, _) = l.radial.as_ref().unwrap().circle.unwrap(); + let radius = l.radial.as_ref().unwrap().handles[1].0; + let out = (radius - centre).normalized(); + let outward = 20.0 * view(&app).zoom as f32; + drag_through(&mut app, Widget::Radial, radius, radius + out * outward); + assert_eq!(radial_of(&app, id), (8, 80.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial_of(&app, id), (8, 60.0)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial_of(&app, id), (6, 60.0)); +} + +#[test] +fn radial_repeat_splitter_hides_instances_in_one_undo_step() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + let id = app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap()["id"].as_u64().unwrap(); + let l = layout(&mut app, ALL); + let m = l.radial.unwrap(); + let (centre, _) = m.circle.unwrap(); + let splitter = m.handles[2].0; + let (v, mut drag) = (view(&app), None); + advance(&mut app, &mut drag, Widget::Radial, Gesture::Press(v.to_doc(splitter)), Mods::default()); + // Back round the circle in 30 degree moves: past two of the six instances. + let from = splitter - centre; + for k in 1..=4 { + let a = (-30.0_f32 * k as f32).to_radians(); + let turned = Vec2::new(from.x * a.cos() - from.y * a.sin(), from.x * a.sin() + from.y * a.cos()); + advance(&mut app, &mut drag, Widget::Radial, Gesture::Move(v.to_doc(centre + turned)), Mods::default()); + } + advance(&mut app, &mut drag, Widget::Radial, Gesture::Release, Mods::default()); + assert_eq!(radial_of(&app, id).0, 4); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(radial_of(&app, id).0, 6, "the split was one step"); +} + +#[test] +fn the_edited_symbols_nine_slice_guides_are_drawn_and_dragged_on_the_canvas() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("symbol.new", json!({"name": "Box", "nineSlice": true})).unwrap(); + app.select_tool("direct"); + let l = layout(&mut app, Show { nine: true, selecting: false, shaper: false, trace: false }); + assert_eq!(l.nine.len(), 4, "the guides show with any tool"); + let lines = |app: &VectorcraftApp| app.session.active().unwrap().doc.edited_nine_slice().unwrap().lines(); + let left = lines(&app)[0].1; + let from = l.nine[0][0] + (l.nine[0][1] - l.nine[0][0]) * 0.5; + let v = view(&app); + drag_through(&mut app, Widget::Nine, from, from - Vec2::new(20.0 * v.zoom as f32, 0.0)); + let moved = lines(&app)[0].1; + assert!((moved.x - (left.x - 20.0)).abs() < 1e-3, "{left:?} to {moved:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(lines(&app)[0].1, left); +} + +#[test] +fn a_press_cancel_mid_drag_gives_one_cancel_and_no_undo_step() { + let (mut app, id) = mirror_app(); + let before = node(&app, id); + let l = layout(&mut app, ALL); + let (_, centre) = l.mirror.unwrap(); + let v = view(&app); + let mut drag = None; + let mut steps = vec![]; + for g in [Gesture::Press(v.to_doc(centre)), Gesture::Move(v.to_doc(centre + Vec2::new(40.0, 0.0))), Gesture::Cancel, Gesture::Release] { + let actions = plan(&mut app, &mut drag, Widget::Mirror, g, Mods::default()); + steps.push(actions.clone()); + app.session.apply_actions(actions).unwrap(); + } + assert_eq!(steps[2], vec![Action::Cancel]); + assert!(steps[3].is_empty(), "the release after a cancel does nothing"); + assert!(drag.is_none()); + assert_eq!(node(&app, id), before); +} + +#[test] +fn no_part_is_declared_where_a_widget_is_hidden() { + let (mut app, _) = mirror_app(); + assert!(widgets(&layout(&mut app, ALL), Widget::Mirror) > 0); + assert_eq!(widgets(&layout(&mut app, Show { selecting: false, ..ALL }), Widget::Mirror), 0, "Edges hidden"); + app.ui.view.bounding_box = false; + assert_eq!(widgets(&layout(&mut app, ALL), Widget::Mirror), 0, "Bounding Box hidden"); + let mut other = app_with_radial(); + let l = layout(&mut other, ALL); + assert_eq!((widgets(&l, Widget::Mirror), widgets(&l, Widget::Grid)), (0, 0), "another repeat kind"); + assert!(widgets(&l, Widget::Radial) > 0); +} + +fn app_with_radial() -> VectorcraftApp { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); + app +}