diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs index fc826b9b42..c6549075df 100644 --- a/crates/engine/src/cmd/draw2/quickpen.rs +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -133,7 +133,7 @@ pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result { return Err(bad(L, format!("`{key}` must be from {lo} to {hi}"))); } let out = qpl::with_length(sp, at_start, length).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; - if !out.anchors.iter().all(|a| within_input_bound(a.p) && within_input_bound(a.h_in) && within_input_bound(a.h_out)) { + if !qp::on_canvas(&out) { return Err(bad(L, "result would exceed the canvas (coordinates out of range)")); } let kind = match piece.shape { diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 8ff8656a00..97591687af 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -762,6 +762,125 @@ fn a_length_drag_stays_on_the_canvas() { assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); } +/// The paths of a selected compound path show length handles, also after a drag selected the +/// compound again. +#[test] +fn a_compound_path_shows_the_length_handles_of_its_paths() { + let mut s = session(); + let a = s.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100}]})).unwrap(); + let b = s.execute("path.quickPen", &json!({"start": [100, 300], "pieces": [{"x": 200, "y": 300}]})).unwrap(); + s.execute("select.set", &json!({"ids": [a["id"], b["id"]]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + quick_pen(&mut s); + press(&mut s, &[(220.0, 100.0), (250.0, 100.0), (280.0, 100.0)]); + press(&mut s, &[(220.0, 300.0), (250.0, 300.0), (270.0, 300.0)]); + let mut ends: Vec = paths(&s).iter().filter_map(|(_, pd)| pd.subpaths[0].anchors.last().map(|a| a.p)).collect(); + ends.sort_by(|p, q| p.y.total_cmp(&q.y)); + assert_eq!(ends, [pt(260.0, 100.0), pt(250.0, 300.0)]); +} + +/// An edit made outside the tool during a length press ends the press: a later drag does not +/// preview from the path as the press found it, and so does not undo the edit. +#[test] +fn an_outside_edit_during_a_length_press_is_kept() { + // The edit comes before the first drag event, or after the drag began. + for began in [false, true] { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + if began { + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + } + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "began: {began}"); + } + // Escape after the edit takes the drag back without taking the edit back. + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "escape"); +} + +/// C and `[` `]` wait for a length drag to end: they neither add an undo step of their own nor +/// change the arc the drag is changing. +#[test] +fn piece_keys_do_nothing_during_a_length_drag() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 320.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 400.0), v).unwrap(); + let during = only_path(&s); + for k in [ToolKey::Letter('c'), ToolKey::BracketRight, ToolKey::BracketLeft] { + assert!(s.tool_claims_key(k, view()), "{k:?} stays with the tool"); + key(&mut s, k); + assert_eq!(only_path(&s), during, "{k:?}"); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 400.0), v).unwrap(); + assert_eq!(undo_steps(&s), undo + 1); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); +} + +/// A length drag ends where the pointer is let go, also when no drag event came after the press. +#[test] +fn a_length_drag_ends_at_the_release_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + // A press let go away from the handle without a drag event drags too. + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(300.0, 100.0)); + assert_eq!(only_path(&s).anchors.len(), 2); + assert_eq!(undo_steps(&s), undo + 2); +} + +/// `path.quickPenLength` refuses a result past the canvas, not only one past the input limit. +#[test] +fn path_quick_pen_length_stays_on_the_canvas() { + let mut s = session(); + let x = vectorcraft_doc::MAX_COORD - 500_000.0; + let r = s.execute("path.quickPen", &json!({"start": [x, 0], "pieces": [{"x": x + 10.0, "y": 0}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let before = only_path(&s); + let undo = undo_steps(&s); + let e = s.execute("path.quickPenLength", &json!({"id": id, "length": 1_000_000})).unwrap_err().to_string(); + assert!(e.contains("would exceed the canvas"), "{e}"); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + s.execute("path.quickPenLength", &json!({"id": id, "length": 400_000})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 400_000.0, 0.0)); +} + /// Dragged by the start handle while the path is being drawn, the first line changes and the last /// sharp-corner arc stays the last piece, so C still flips it. #[test] diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 38f8e3fca1..7d50150be0 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -339,6 +339,12 @@ struct LengthDrag { /// The subpath as the press found it, and its last piece as that subpath held it. before: SubPath, tail: Option, + /// The document's revision ([`ToolContext::revision`]) after the drag's last edit. A press + /// previews from the path as it found it, so once the revision differs, an edit was made + /// outside the tool and the drag previews no more. + revision: (u64, u64), + /// An edit made outside the tool ended the drag. + stale: bool, } pub struct QuickPenTool { @@ -365,7 +371,7 @@ fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { /// Whether `sp` lies on the canvas: every point and handle does, or else the curve itself (its /// extrema, not its handles) does. -fn on_canvas(sp: &SubPath) -> bool { +pub fn on_canvas(sp: &SubPath) -> bool { let within = |v: f64| v.abs() <= MAX_COORD; sp.anchors.iter().all(|a| [a.p, a.h_in, a.h_out].iter().all(|q| within(q.x) && within(q.y))) || PathData::new(vec![sp.clone()]).bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].into_iter().all(within)) @@ -497,7 +503,19 @@ impl QuickPenTool { if let Some(dr) = self.drawing.as_mut().filter(|dr| dr.id == Some(handle.id)) { dr.before_press = shared_node(cx.doc, handle.id).cloned(); } - self.length = Some(LengthDrag { handle, press: p, length: handle.piece.length, dragged: false, begun: false, last, before, tail }); + let drag = LengthDrag { + handle, + press: p, + length: handle.piece.length, + dragged: false, + begun: false, + last, + before, + tail, + revision: cx.revision, + stale: false, + }; + self.length = Some(drag); return vec![]; } self.click(cx, p) @@ -585,9 +603,20 @@ impl QuickPenTool { self.drawing.as_ref().map(|dr| (id, dr.si, sp)).into_iter().collect() } else if let [id] = cx.selection.objects.as_slice() && cx.doc.is_editable(*id) - && let Some(pd) = cx.doc.node(*id).and_then(|n| n.path_data()) + && let Some(node) = cx.doc.node(*id) { - pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed).map(|(si, sp)| (*id, si, sp)).collect() + // A compound path shows the handles of the paths it holds. + let members: Vec<&Node> = if matches!(node.kind, NodeKind::Compound { .. }) { + let editable = cx.doc.editable(); + node.editing_children().iter().map(|c| c.as_ref()).filter(|c| editable(c.id)).collect() + } else { + vec![node] + }; + members + .into_iter() + .filter_map(|n| Some((n.id, n.path_data()?))) + .flat_map(|(id, pd)| pd.subpaths.iter().enumerate().filter(|(_, sp)| !sp.closed).map(move |(si, sp)| (id, si, sp))) + .collect() } else { vec![] }; @@ -643,11 +672,86 @@ impl QuickPenTool { json!({"id": h.id.0, "subpath": h.si, "end": if h.at_start { "start" } else { "end" }, "length": drag.length}) } + /// Moves the end of the line or arc a length drag changes to follow the pointer at `p` and + /// previews it. An edit made outside the tool since the last preview ends the drag instead: the + /// press then commits the document as it is. + fn length_drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec { + let Some(mut drag) = self.length.clone() else { return vec![] }; + if drag.stale { + return vec![]; + } + if drag.revision != cx.revision { + drag.stale = true; + self.length = Some(drag); + return vec![]; + } + if !drag.dragged && p.distance(drag.press) < cx.tol(DRAG_PX) { + return vec![]; + } + drag.dragged = true; + self.length = Some(drag.clone()); + // The end follows the pointer, as far behind it as the press was. + let piece = drag.handle.piece; + let mut length = piece.length_dragged(drag.press, p, drag.length); + // The last piece drawn goes on being a piece of the drawing, drawn again to its new + // end; an arc piece keeps an arc size of at least 1°. + let mut redrawn = None; + let changed = if let (Some(last), Some(tail)) = (drag.last, drag.tail.as_ref()) { + if let length::EndShape::Arc { radius, .. } = piece.shape { + length = length.max(MIN_TURN.to_radians() * radius); + } + let changed = length::with_length(tail, false, length); + redrawn = changed.as_ref().and_then(|sp| sp.anchors.last().map(|a| a.p)).map(|to| { + let turn = match piece.shape { + length::EndShape::Arc { radius, .. } => (length / radius).to_degrees().clamp(MIN_TURN, MAX_TURN), + length::EndShape::Line => last.turn, + }; + Piece { to, turn, ..last } + }); + changed + } else { + length::with_length(&drag.before, drag.handle.at_start, length) + }; + // A length that would take the path past the canvas is not taken: the end stays + // where the drag last put it. + if !changed.is_some_and(|sp| on_canvas(&sp)) { + return vec![]; + } + if drag.begun && (length - drag.length).abs() <= 1e-12 * length.max(1.0) { + return vec![]; + } + let mut out = vec![]; + if !drag.begun { + drag.begun = true; + out.push(Action::Begin("Quick Pen".into())); + } + drag.length = length; + match redrawn { + Some(pc) => { + if let Some(l) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + *l = pc; + } + out.push(Action::Preview(COMMAND.into(), self.params(false))); + } + None => out.push(Action::Preview(LENGTH_COMMAND.into(), Self::length_params(&drag))), + } + // The drawing sees the path as the preview left it. + out.push(drawn()); + self.length = Some(drag); + out + } + /// A length drag let go: once it changed the path being drawn, the drawing goes on from the /// changed path, which `path.quickPenLength` made from the same points. A press on a handle let - /// go without dragging is a click there. + /// go without dragging is a click there. After an edit made outside the tool, the path being + /// drawn ends and the document stays as that edit left it. fn end_length_drag(&mut self, cx: &ToolContext) -> Vec { let Some(drag) = self.length.take() else { return vec![] }; + if drag.stale || drag.revision != cx.revision { + self.drawing = None; + self.snap.clear(); + return if drag.begun { vec![Action::Commit] } else { vec![] }; + } if !drag.dragged { let mut out = self.click(cx, drag.press); if self.press.take().is_some_and(|pr| pr.begun) { @@ -711,60 +815,7 @@ impl Tool for QuickPenTool { } self.press_down(cx, p) } - PointerKind::Drag if self.length.is_some() => { - let Some(mut drag) = self.length.clone() else { return vec![] }; - if !drag.dragged && p.distance(drag.press) < cx.tol(DRAG_PX) { - return vec![]; - } - drag.dragged = true; - self.length = Some(drag.clone()); - // The end follows the pointer, as far behind it as the press was. - let piece = drag.handle.piece; - let mut length = piece.length_dragged(drag.press, p, drag.length); - // The last piece drawn goes on being a piece of the drawing, drawn again to its new - // end; an arc piece keeps an arc size of at least 1°. - let mut redrawn = None; - let changed = if let (Some(last), Some(tail)) = (drag.last, drag.tail.as_ref()) { - if let length::EndShape::Arc { radius, .. } = piece.shape { - length = length.max(MIN_TURN.to_radians() * radius); - } - let changed = length::with_length(tail, false, length); - redrawn = changed.as_ref().and_then(|sp| sp.anchors.last().map(|a| a.p)).map(|to| { - let turn = match piece.shape { - length::EndShape::Arc { radius, .. } => (length / radius).to_degrees().clamp(MIN_TURN, MAX_TURN), - length::EndShape::Line => last.turn, - }; - Piece { to, turn, ..last } - }); - changed - } else { - length::with_length(&drag.before, drag.handle.at_start, length) - }; - // A length that would take the path past the canvas is not taken: the end stays - // where the drag last put it. - if !changed.is_some_and(|sp| on_canvas(&sp)) { - return vec![]; - } - let mut out = vec![]; - if !drag.begun { - drag.begun = true; - out.push(Action::Begin("Quick Pen".into())); - } - drag.length = length; - match redrawn { - Some(pc) => { - if let Some(l) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - *l = pc; - } - out.push(Action::Preview(COMMAND.into(), self.params(false))); - } - None => out.push(Action::Preview(LENGTH_COMMAND.into(), Self::length_params(&drag))), - } - // The drawing sees the path as the preview left it. - out.push(drawn()); - self.length = Some(drag); - out - } + PointerKind::Drag if self.length.is_some() => self.length_drag_to(cx, p), PointerKind::Drag => { let Some(mut pr) = self.press else { return vec![] }; if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { @@ -780,7 +831,10 @@ impl Tool for QuickPenTool { PointerKind::Up => { if self.length.is_some() { self.snap.clear(); - return self.end_length_drag(cx); + // The end goes where the press is let go, also past the last drag. + let mut out = self.length_drag_to(cx, p); + out.extend(self.end_length_drag(cx)); + return out; } let out = match self.press { // The piece ends where the press is let go, also past the last drag. @@ -810,6 +864,11 @@ impl Tool for QuickPenTool { } fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == DRAWN + && let Some(drag) = self.length.as_mut() + { + drag.revision = cx.revision; + } let Some(dr) = self.drawing.as_mut() else { return }; if what == "created" && let [id] = cx.selection.objects.as_slice() @@ -846,7 +905,7 @@ impl Tool for QuickPenTool { fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { match key { - ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(), + ToolKey::Letter('c') => self.length.is_some() || self.last_sharp_arc(cx).is_some(), ToolKey::BracketLeft | ToolKey::BracketRight | ToolKey::AltTap => true, ToolKey::Enter => self.active(cx).is_some(), _ => false, @@ -894,6 +953,12 @@ impl Tool for QuickPenTool { if !drag.begun { return vec![]; } + // An edit made outside the tool since the last preview stays: the cancel would + // take it back with the drag. + if drag.stale || drag.revision != cx.revision { + self.drawing = None; + return vec![Action::Commit]; + } self.restore_last_piece(&drag); // The drawing sees the path as the cancel leaves it. vec![Action::Cancel, drawn()] @@ -901,6 +966,8 @@ impl Tool for QuickPenTool { None => vec![], }, ToolKey::Enter if self.length.is_some() => vec![], + // C and [ ] change the last piece once the drag has ended. + ToolKey::Letter('c') | ToolKey::BracketLeft | ToolKey::BracketRight if self.length.is_some() => vec![], ToolKey::Escape | ToolKey::Enter => self.end(), ToolKey::Letter('c') => { if self.last_sharp_arc(cx).is_none() { diff --git a/docs/mcp.md b/docs/mcp.md index 684db1bf60..79ce0bfd6b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7358,7 +7358,8 @@ dragged end stays on its line or circle and does not snap to Smart Guides, and a reach past the canvas. Each drag is one undo step, Escape during the drag takes it back, and the path being drawn goes on from the new end. The pieces of the path being drawn that the drag does not change stay pieces: C and `[` `]` still change the last one. The last piece, dragged by its end, stays -that piece, and as an arc it keeps an arc size of at least 1°. A click on a handle that does not drag is an ordinary +that piece, and as an arc it keeps an arc size of at least 1°. C and `[` `]` do nothing until the drag ends, and the +end goes where the pointer is let go. A click on a handle that does not drag is an ordinary click: it adds a point, closes the path or starts a new one. The handle's place, the 359° limit, the 1° minimum, Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules.