diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..620b7f8ad5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -148,6 +148,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged. - 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index c761656b7f..bce1e24d98 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -1,7 +1,7 @@ use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment}; use super::cut::{erase_region, erase_segments, knife, split}; use super::freehand::{blob, freehand}; -use super::quickpen::quick_pen; +use super::quickpen::{quick_pen, quick_pen_length}; use super::smooth::{join_scrub, smooth_region}; use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection}; @@ -43,6 +43,15 @@ pub fn specs() -> Vec { has_doc, quick_pen ), + cmd!( + "path.quickPenLength", + "Quick Pen", + [], + None, + "{id, subpath?: index (0), end?: \"end\" (default)|\"start\", length: pt} make the line or arc at that end of the open subpath `length` long, as dragging the Quick Pen tool's length handle does: a line keeps its other point and its direction; an arc (the segments before the end that lie on one circle and turn the same way) keeps its other point, its circle and the way it turns, with a sweep of at most 359°. length runs from 0.001 to 1000000 pt for a line, and to 359° of the circle for an arc. A length the piece already has changes nothing; otherwise the path is selected, as one undo step → {id, kind: \"line\"|\"arc\", length}. An end that is neither straight nor a circular arc, a closed subpath, a locked or hidden path, a length outside the range and a result that would reach past the canvas are errors", + has_doc, + quick_pen_length + ), cmd!( "path.removeAnchor", "Delete Anchor Point", diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs index 84640bc876..c6549075df 100644 --- a/crates/engine/src/cmd/draw2/quickpen.rs +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -1,9 +1,12 @@ -//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs. +//! The Quick Pen tool's commands: `path.quickPen` draws a path of straight lines and circular arcs, +//! and `path.quickPenLength` makes the line or arc at an end of a path longer or shorter. +use vectorcraft_tools::quickpen::length as qpl; use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke}; use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound}; use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or}; +use crate::cmd::f64_req; const C: &str = "path.quickPen"; /// The most pieces one request takes. @@ -94,3 +97,58 @@ pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result { })?; Ok(json!({ "id": id.0 })) } + +const L: &str = "path.quickPenLength"; + +/// `path.quickPenLength`: the line or arc at an end of an open subpath made `length` long. +pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result { + let Some(id) = object_param(p, "id", L)? else { return Err(bad(L, "missing `id`")) }; + let si = usize_opt(p, "subpath", L)?.unwrap_or(0); + let at_start = match p.get("end") { + None | Some(Value::Null) => false, + Some(v) => match v.as_str() { + Some("end") => false, + Some("start") => true, + _ => { + let key = "end"; + return Err(bad(L, format!("`{key}` must be one of {}", ["start", "end"].join(", ")))); + } + }, + }; + let length = f64_req(p, "length", L)?; + let d = &s.doc()?.doc; + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(L, "`id` is not a path"))?; + if !d.is_editable(id) { + return Err(bad(L, "the path is locked or hidden")); + } + let sp = path.subpaths.get(si).ok_or_else(|| bad(L, "no such subpath"))?; + if sp.closed { + return Err(bad(L, "the subpath is closed")); + } + let piece = qpl::end_piece(sp, at_start).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?; + let (key, lo, hi) = ("length", qpl::MIN_LENGTH, piece.max_length()); + if !(lo..=hi).contains(&length) { + // An arc's limit, 359° of its circle, is given to the thousandth of a point, rounded down. + let hi = (hi * 1000.0).floor() / 1000.0; + 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 !qp::on_canvas(&out) { + return Err(bad(L, "result would exceed the canvas (coordinates out of range)")); + } + let kind = match piece.shape { + qpl::EndShape::Line => "line", + qpl::EndShape::Arc { .. } => "arc", + }; + if (length - piece.length).abs() <= 1e-9 * length.max(1.0) { + return Ok(json!({ "id": id.0, "kind": kind, "length": piece.length })); + } + let top = super::super::path::compound_or_self(d, id); + s.edit("Quick Pen", |d, sel| { + let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?; + *slot = out; + sel.set([top]); + Ok(()) + })?; + Ok(json!({ "id": id.0, "kind": kind, "length": length })) +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..2f6f7c9719 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -466,6 +466,7 @@ pub(super) const ALLOWED: &[&str] = &[ "path.moveAnchor", "path.moveAnchors", "path.quickPen", + "path.quickPenLength", "path.rectCut", "path.removeAnchor", "path.removeAnchors", diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 375f648ac8..d9945fa723 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -550,6 +550,18 @@ fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { key(s, ToolKey::AltTap); } +/// Whether the tool shows only the path's points and its length handles (a handle and the line to +/// it from the path's end): no hover preview, label or Smart Guide. +fn only_points(s: &mut Session, v: ViewInfo) -> bool { + let o = s.overlays(v); + let handles: Vec = o.iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect(); + o.iter().all(|o| match o { + Overlay::CurvePoint { .. } | Overlay::Handle { .. } => true, + Overlay::Line { b, .. } => handles.contains(b), + _ => false, + }) +} + /// The last point of the path the tool drew (any other path is a two-point line). fn drawn_end(s: &Session) -> Point { let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); @@ -710,9 +722,8 @@ fn a_hover_shows_nothing_after_smart_guides_change() { s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); let off_anchor = label(&mut s, on).unwrap() - at; assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on)); - assert!(only_points(&mut s, off), "only the path's points show"); + assert!(only_points(&mut s, off), "only the path's points and length handles show"); // A click before the pointer moves does not bring the stale hover back. press_in(&mut s, &[(400.0, 300.0)], off); assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); @@ -746,7 +757,6 @@ fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { s.execute("select.set", &json!({"ids": []})).unwrap(); continuous_arc_after_a_line(&mut s, on); s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on), "the anchor's guide shows"); assert!(only_points(&mut s, off)); let steps = undo_steps(&s); @@ -891,6 +901,467 @@ fn path_quick_pen_refuses_bad_params() { assert_eq!(paths(&s).len(), before.len()); } +/// The handle beyond the end of the path being drawn makes its last line longer, as one undo step, +/// and the next click goes on from the new end. +#[test] +fn dragging_the_end_handle_lengthens_the_last_line() { + 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); + // The handle stands 20 screen points beyond the end, along the line. + press(&mut s, &[(220.0, 100.0), (250.0, 130.0), (280.0, 140.0)]); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, 260.0, 200.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0), pt(260.0, 200.0)], "the drawing went on"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(200.0, 100.0)); +} + +/// Dragged by its end handle, the last sharp-corner arc goes on around its circle and stays the +/// last piece, so C still flips it and `[` `]` still change its size. +#[test] +fn a_dragged_last_arc_still_flips() { + 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); + // The half circle over (200, 300) ends heading down, so its end handle is 20 points below. The + // handle turned a quarter around the center, to (180, 400), takes the end to (200, 400). + press(&mut s, &[(300.0, 320.0), (260.0, 400.0), (180.0, 400.0)]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6, "three quarters around: {:?}", sp.anchors.last()); + assert_eq!(sp.anchors.len(), 4); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert!(flipped.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 2); + // `]` makes the dragged arc 15° larger: it keeps its ends and gains its own undo step. + key(&mut s, ToolKey::BracketRight); + let larger = only_path(&s); + assert_ne!(larger, flipped); + assert!(larger.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 3); +} + +/// Dragged back past its start, the last sharp-corner arc stops at 1°. +#[test] +fn a_dragged_last_arc_keeps_at_least_one_degree() { + 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); + // The half circle about (200, 300) runs over the top from (100, 300) to (300, 300); its end + // handle is 20 points below the end. The pointer goes back around the circle from there, past + // the start of the arc. + let (c, r) = (pt(200.0, 300.0), (100.0f64 * 100.0 + 20.0 * 20.0).sqrt()); + let a0 = 20.0f64.atan2(100.0); + let mut pts = vec![(300.0, 320.0)]; + for d in [45.0f64, 90.0, 135.0, 175.0, 185.0] { + let a = a0 - d.to_radians(); + pts.push((c.x + r * a.cos(), c.y + r * a.sin())); + } + press(&mut s, &pts); + let sp = only_path(&s); + let one = 181f64.to_radians(); + let end = pt(200.0 + 100.0 * one.cos(), 300.0 + 100.0 * one.sin()); + assert!(sp.anchors.last().unwrap().p.distance(end) < 1e-6, "{:?}", sp.anchors.last()); + assert_eq!(sp.anchors.first().unwrap().p, pt(100.0, 300.0)); +} + +/// When the last arc goes on around the circle of the arc before it, its end handle still changes +/// the last arc alone, which C then still flips. +#[test] +fn the_end_handle_changes_the_last_arc_on_a_shared_circle() { + 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); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "turn", "value": 90})).unwrap(); + // A quarter more around the circle about (200, 300), ending heading left. + click(&mut s, 200.0, 400.0); + let r = 100.0 * std::f64::consts::FRAC_1_SQRT_2; + let to = pt(200.0 - r, 300.0 + r); + // The handle at (180, 400) turned 45° more around the center takes the end there with it. + let (sin, cos) = std::f64::consts::FRAC_PI_4.sin_cos(); + let (hx, hy) = (-20.0, 100.0); + let pointer = (200.0 + hx * cos - hy * sin, 300.0 + hx * sin + hy * cos); + press(&mut s, &[(180.0, 400.0), (170.0, 400.0), pointer]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(to) < 1e-6, "135° from (300, 300): {:?}", sp.anchors.last()); + assert!(sp.anchors.get(2).unwrap().p.distance(pt(300.0, 300.0)) < 1e-9, "the first arc stays"); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); +} + +/// Once another path is selected while one was being drawn, the selected path shows its handles. +#[test] +fn another_selected_path_shows_its_handles() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let r = s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 400, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + let handle = + |s: &mut Session| s.overlays(view()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { p, .. } if *p == pt(420.0, 300.0))); + assert!(handle(&mut s)); + assert_eq!(s.cursor(pt(420.0, 300.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); +} + +/// A selected path that is not being drawn shows its handles: the one before its start makes the +/// first arc shorter around its circle. Escape during a drag takes the drag back. +#[test] +fn the_start_handle_of_a_selected_path_shortens_its_arc() { + let mut s = session(); + let r = s + .execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100, "action": "sharpArc"}, {"x": 300, "y": 100}]})) + .unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + quick_pen(&mut s); + let undo = undo_steps(&s); + let before = only_path(&s); + // The half circle leaves (100, 100) heading up, so its start handle is 20 points below. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 70.0), v).unwrap(); + assert_ne!(only_path(&s), before, "previewed"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 70.0), v).unwrap(); + assert_eq!(only_path(&s), before, "taken back"); + assert_eq!(undo_steps(&s), undo); + // The handle turned a quarter around the center, to (130, 50), takes the start to the top of + // the circle: the arc is a quarter from there to (200, 100). + press(&mut s, &[(100.0, 120.0), (130.0, 50.0)]); + let sp = only_path(&s); + assert!(sp.anchors.first().unwrap().p.distance(pt(150.0, 50.0)) < 1e-6, "{:?}", sp.anchors.first()); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// A click on a length handle that does not drag is an ordinary click: while drawing it adds a +/// point there, and with no path being drawn it starts a new path. +#[test] +fn a_click_on_a_handle_adds_a_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); + click(&mut s, 220.0, 100.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(220.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + // After Escape the path stays selected with its handles; a click on one starts a new path. + key(&mut s, ToolKey::Escape); + assert_eq!(s.cursor(pt(240.0, 100.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); + click(&mut s, 240.0, 100.0); + assert_eq!(paths(&s).len(), 2); +} + +/// During a length drag the tool shows the handle and no preview of a next piece to where the +/// pointer was before the press. +#[test] +fn a_length_drag_shows_no_next_piece() { + 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(); + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + let o = s.overlays(v); + assert!(o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { .. }))); + assert!(!o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. } | vectorcraft_tools::Overlay::Measure { .. })), "{o:?}"); + 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)); +} + +/// A press on a length handle clears the Smart Guides of the hover before it, so none show during +/// the drag. +#[test] +fn a_length_drag_shows_no_smart_guide() { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 220, "y1": 100, "x2": 220, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let on = ViewInfo { smart_guides: true, ..Default::default() }; + // The end handle stands on the other line's anchor, so the hover there shows its guide. + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), on).unwrap(); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), on).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), on).unwrap(); + assert!(only_points(&mut s, on), "no guide during the drag: {:?}", s.overlays(on)); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), on).unwrap(); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert_eq!(drawn.1.subpaths[0].anchors.last().unwrap().p, pt(260.0, 100.0)); +} + +/// A length drag that would take the path past the canvas leaves it where the drag last put it, +/// and the drawing goes on from there. +#[test] +fn a_length_drag_stays_on_the_canvas() { + let mut s = session(); + quick_pen(&mut s); + let x = vectorcraft_doc::MAX_COORD - 1000.0; + click(&mut s, x, 100.0); + click(&mut s, x + 500.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at x + 520; a drag to x + 2000 would put the end at x + 1980, past the canvas. + press(&mut s, &[(x + 520.0, 100.0), (x + 2000.0, 100.0)]); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + press(&mut s, &[(x + 520.0, 100.0), (x + 820.0, 100.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 800.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, x + 800.0, 200.0); + assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); +} + +/// A length drag across a line, or out along it and back, leaves its length as it was: it changes +/// nothing and records no undo step, on the path being drawn and on a selected path. +#[test] +fn a_length_drag_that_keeps_the_length_records_no_undo_step() { + 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 before = only_path(&s); + // The end handle is at (220, 100); the first drag goes straight down from it, the second out + // along the line and back. + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } + key(&mut s, ToolKey::Escape); + let undo = undo_steps(&s); + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } +} + +/// 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); +} + +/// Choosing Quick Pen again during a length drag leaves the drawing alone: the drag goes on, ends +/// where the pointer is let go, and the next click goes on drawing the same path. +#[test] +fn choosing_the_tool_again_during_a_length_drag_keeps_the_drawing() { + 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(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 130.0), v).unwrap(); + quick_pen(&mut s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + click(&mut s, 260.0, 200.0); + assert_eq!(paths(&s).len(), 1, "the drawing went on"); + assert_eq!(only_path(&s).anchors.len(), 3); +} + +/// 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] +fn the_start_handle_keeps_the_last_arc_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 300.0); + click(&mut s, 200.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 400.0, 300.0); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + let undo = undo_steps(&s); + // The line leaves (100, 300) heading left, seen from the start, so its handle is 20 points left. + press(&mut s, &[(80.0, 300.0), (60.0, 300.0), (50.0, 300.0)]); + let sp = only_path(&s); + assert_eq!(sp.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view()), "the last arc is still a piece"); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert_eq!(flipped.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert!(flipped.anchors.last().unwrap().p.distance(pt(400.0, 300.0)) < 1e-9); +} + +/// `path.quickPenLength` sets the length of a line or an arc at either end; the same length +/// changes nothing and records no undo step; bad params are refused. +#[test] +fn path_quick_pen_length_sets_an_end() { + let mut s = session(); + let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 200, "y": 0, "action": "sharpArc"}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let r = s.execute("path.quickPenLength", &json!({"id": id, "end": "start", "length": 40})).unwrap(); + assert_eq!((r["kind"].as_str(), r["length"].as_f64()), (Some("line"), Some(40.0))); + assert_eq!(only_path(&s).anchors.first().unwrap().p, pt(60.0, 0.0)); + let undo = undo_steps(&s); + let r = s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 50.0})).unwrap(); + assert_eq!(r["kind"], "arc"); + assert_eq!(undo_steps(&s), undo, "unchanged"); + s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 25.0})).unwrap(); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + assert_eq!(undo_steps(&s), undo + 1); + let before = paths(&s); + let bad: [Value; 7] = [ + json!({"length": 10}), + json!({"id": id}), + json!({"id": id, "length": "10"}), + json!({"id": id, "length": 0}), + json!({"id": id, "length": 1e7, "end": "start"}), + json!({"id": id, "length": 10, "end": "middle"}), + json!({"id": id, "length": 10, "subpath": 1}), + ]; + for p in bad { + assert!(s.execute("path.quickPenLength", &p).is_err(), "{p}"); + } + let curve = s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap(); + s.execute("path.convertAnchor", &json!({"id": curve["id"], "anchor": 1, "to": "smooth", "x": 150, "y": 360})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": curve["id"], "length": 10})).is_err(), "not a line or an arc"); + s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": id, "length": 10})).is_err(), "closed"); + assert_eq!(paths(&s).len(), before.len() + 1); +} + /// With `id` and `keep`, the points after the first `keep` are replaced by the pieces. #[test] fn path_quick_pen_replaces_the_points_after_keep() { diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 2e5eb61491..abae4bc5ea 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -13,6 +13,13 @@ //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. //! +//! A handle stands beyond each end of the path being drawn, or, while none is, of the selected +//! path, where that end is a straight line or a circular arc. Dragging it makes the line or arc +//! longer or shorter, as one undo step (`path.quickPenLength`): a line keeps its direction, and +//! an arc keeps its circle. The dragged end stays on its line or circle and does not snap to Smart +//! Guides. A click on a handle that does not drag is an ordinary click: it adds a point, closes the +//! path or starts one. +//! //! While an arc is drawn, by a drag or as the piece the next click adds, the tool shows a //! protractor around the arc's center: a tick across its circle every 15° from where the arc //! starts, a longer one every 90°, and one where it ends, with a small cross at the center. The @@ -31,12 +38,13 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, MAX_COORD, Node, NodeId, NodeKind}; -use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, BezPath, PathData, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; use crate::guides::{DrawSnap, Leave, SnapSettings}; use crate::pen::{continue_from, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +use length::EndPiece; /// The tool's id. pub const ID: &str = "quickPen"; @@ -49,6 +57,8 @@ pub const TURN_STEP: f64 = 15.0; /// The smallest and largest arc size (degrees). pub const MIN_TURN: f64 = 1.0; pub const MAX_TURN: f64 = 359.0; +/// The command that makes the line or arc at an end of a path longer or shorter. +pub const LENGTH_COMMAND: &str = "path.quickPenLength"; /// Degrees between the protractor's ticks, and the steps a continuous arc's sweep snaps to. pub const TICK_STEP: f64 = 15.0; /// Half the length (screen points) of a protractor tick; the ticks every 90° are twice as long. @@ -57,6 +67,8 @@ const TICK_PX: f64 = 4.0; const CROSS_PX: f64 = 4.0; /// Screen points the pointer moves after a press before the press drags. const DRAG_PX: f64 = 3.0; +/// Screen points a length handle stands beyond the end of the path, along the way it leaves the end. +pub const LENGTH_HANDLE_PX: f64 = 20.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight /// behind, is drawn as a line: no circle runs there in the path's direction. const STRAIGHT: f64 = 1e-6; @@ -361,6 +373,31 @@ impl Drawing { self.pieces.pop(); self.kept.pop(); } + + /// The last piece as `sp`, the subpath being drawn, holds it: the points from where it starts to + /// the end of the path. + fn last_tail(&self, sp: &SubPath) -> Option { + let from = self.kept.last()?.checked_sub(1)?; + Some(SubPath::new(sp.anchors.get_range(from..)?, false)) + } + + /// After the start of the path changed to a different number of points (`delta` more): keeps + /// the pieces that start at or after point `fixed` (counted before the change), which now start + /// `delta` points later, and forgets the others. + fn after_start_change(&mut self, fixed: usize, delta: isize) { + let first = self.kept.iter().position(|k| k.saturating_sub(1) >= fixed).unwrap_or(self.kept.len()); + self.pieces.drain(..first); + self.kept.drain(..first); + for k in &mut self.kept { + *k = k.saturating_add_signed(delta).max(1); + } + } + + /// Forgets every piece: the path as the document holds it is all the drawing goes on from. + fn clear_pieces(&mut self) { + self.pieces.clear(); + self.kept.clear(); + } } /// The press in progress: where it went down, whether it has dragged, and whether it began an undo @@ -374,11 +411,45 @@ struct Press { end: Option<(Point, Point)>, } +/// A length handle: the line or arc at one end of subpath `si` of `id`, and where its handle is. +#[derive(Clone, Copy, Debug, PartialEq)] +struct LengthHandle { + id: NodeId, + si: usize, + at_start: bool, + piece: EndPiece, + at: Point, +} + +/// A length handle being dragged: the handle as the press found it, the length the drag has set, +/// whether the press has moved far enough to drag, and whether the drag began an undo step. +#[derive(Clone, Debug, PartialEq)] +struct LengthDrag { + handle: LengthHandle, + press: Point, + length: f64, + dragged: bool, + begun: bool, + /// The last piece of the path being drawn as it was before the drag, when the handle is at the + /// end of that piece: the drag changes the piece, so C and [ ] still shape it afterwards. + last: Option, + /// 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 { action: Stroke, turn: f64, drawing: Option, press: Option, + length: Option, hover: Option, snap: DrawSnap, /// The pointer while it hovers, whether it lies on a Smart Guide target ([`Self::landed`]), and @@ -390,7 +461,16 @@ pub struct QuickPenTool { impl Default for QuickPenTool { fn default() -> Self { - Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default(), pointer: None } + Self { + action: Stroke::Line, + turn: DEFAULT_TURN, + drawing: None, + press: None, + length: None, + hover: None, + snap: DrawSnap::default(), + pointer: None, + } } } @@ -400,6 +480,14 @@ fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { sel == [id] || cx.doc.parent_of(id).is_some_and(|p| sel == [p] && cx.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) } +/// Whether `sp` lies on the canvas: every point and handle does, or else the curve itself (its +/// extrema, not its handles) does. +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)) +} + fn point_tol(cx: &ToolContext) -> f64 { cx.tol(5.0).max(cx.point_tol()) } @@ -574,6 +662,38 @@ impl QuickPenTool { if self.drawing.is_some() && self.active(cx).is_none() { self.drawing = None; } + // A press on a length handle waits to see whether it drags; one let go without dragging is + // the click `click` makes. + if let Some(handle) = self.length_handle_at(cx, p) + && let Some(before) = cx.doc.node(handle.id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(handle.si)).cloned() + { + let last = self.drawn_last_piece(cx, &handle); + let tail = last.and(self.drawing.as_ref()).and_then(|dr| dr.last_tail(&before)); + 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(); + } + let drag = LengthDrag { + handle, + press: p, + length: handle.piece.length, + dragged: false, + begun: false, + last, + before, + tail, + revision: cx.revision, + stale: false, + }; + // The hover's Smart Guides do not follow a length drag. + self.snap.clear(); + self.length = Some(drag); + return vec![]; + } + self.click(cx, p) + } + + /// What a press away from a length handle, or a click on one, draws. + fn click(&mut self, cx: &ToolContext, p: Point) -> Vec { let tol = point_tol(cx); if let Some((id, sp)) = self.active(cx) { let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { @@ -645,6 +765,211 @@ impl QuickPenTool { SubPath::new(added, false).to_bezpath_into(&mut bp); Some(bp) } + + /// The length handles: at both ends of the path being drawn, or, while none is, of each open + /// subpath of the one editable path selected, wherever the end is a line or an arc. + fn length_handles(&self, cx: &ToolContext) -> Vec { + // At the end of the path being drawn, the handle changes the last piece drawn alone, even + // where the piece before it goes on around the same circle. + let mut tail = None; + let subpaths: Vec<(NodeId, usize, &SubPath)> = if let Some((id, sp)) = self.active(cx) { + tail = self.drawing.as_ref().and_then(|dr| dr.last_tail(sp)); + 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(node) = cx.doc.node(*id) + { + // 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![] + }; + let off = cx.tol(LENGTH_HANDLE_PX); + let mut out = vec![]; + for (id, si, sp) in subpaths { + for at_start in [false, true] { + let piece = match &tail { + Some(t) if !at_start => length::end_piece(t, false), + _ => length::end_piece(sp, at_start), + }; + if let Some(piece) = piece { + out.push(LengthHandle { id, si, at_start, piece, at: piece.end + piece.out * off }); + } + } + } + out + } + + /// The length handle under `p`, the nearest when several are. + fn length_handle_at(&self, cx: &ToolContext, p: Point) -> Option { + let tol = point_tol(cx); + self.length_handles(cx).into_iter().filter(|h| h.at.distance(p) <= tol).min_by(|a, b| a.at.distance(p).total_cmp(&b.at.distance(p))) + } + + /// The last piece of the path being drawn, when `handle` is at its end and the piece is the + /// line or arc there. + fn drawn_last_piece(&self, cx: &ToolContext, handle: &LengthHandle) -> Option { + let (id, sp) = self.active(cx)?; + let dr = self.drawing.as_ref()?; + if handle.at_start || id != handle.id || dr.si != handle.si { + return None; + } + let last = dr.pieces.last()?; + let from = sp.anchors.get(dr.kept.last()?.checked_sub(1)?)?.p; + let same = match handle.piece.shape { + length::EndShape::Line => last.stroke == Stroke::Line, + length::EndShape::Arc { .. } => last.stroke != Stroke::Line, + }; + (same && from.distance(handle.piece.fixed) <= 1e-9).then_some(*last) + } + + /// Puts back the last piece a length drag changed, when the drag is taken back. + fn restore_last_piece(&mut self, drag: &LengthDrag) { + if let (Some(last), Some(l)) = (drag.last, self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut())) { + *l = last; + } + } + + /// `path.quickPenLength`'s params for the length drag. + fn length_params(drag: &LengthDrag) -> Value { + let h = &drag.handle; + 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![]; + } + // A length the end already has changes nothing: no preview, and no undo step before the + // first change. + if (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. 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) { + out.extend([Action::Commit, Action::Notify(PLACED.into())]); + } + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; + } + self.snap.clear(); + return out; + } + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; + } + if !drag.begun { + return vec![]; + } + // A drag that ends at the length the piece started with is taken back, as Escape takes it + // back: it records no undo step. + let changed = (drag.length - drag.handle.piece.length).abs() > 1e-9 * drag.length.max(1.0); + if !changed { + self.restore_last_piece(&drag); + return vec![Action::Cancel, drawn()]; + } + // A drag that drew the last piece again has already changed the drawing. + if drag.last.is_none() + && let Some(dr) = self.drawing.as_mut() + && dr.id == Some(drag.handle.id) + && dr.si == drag.handle.si + { + // The pieces that start at or after the fixed end of a changed start still draw as they + // did, on the points the document holds before them; every other piece is forgotten. + let new_len = length::with_length(&drag.before, drag.handle.at_start, drag.length).map(|sp| sp.anchors.len()); + let fixed = drag.before.anchors.iter().position(|a| a.p.distance(drag.handle.piece.fixed) <= 1e-9); + match (drag.handle.at_start, new_len, fixed) { + (true, Some(new_len), Some(fixed)) => dr.after_start_change(fixed, new_len as isize - drag.before.anchors.len() as isize), + (_, None, _) => self.drawing = None, + _ => dr.clear_pieces(), + } + } + vec![Action::Commit, drawn()] + } } impl Tool for QuickPenTool { @@ -653,7 +978,7 @@ impl Tool for QuickPenTool { } fn busy(&self) -> bool { - self.press.is_some() + self.press.is_some() || self.length.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { @@ -667,7 +992,7 @@ impl Tool for QuickPenTool { vec![] } PointerKind::Down => { - if self.press.is_some() { + if self.press.is_some() || self.length.is_some() { return vec![]; } // The hover shows again when the pointer moves after the press: the point the press @@ -680,6 +1005,7 @@ impl Tool for QuickPenTool { self.pointer = None; self.press_down(cx, p) } + 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) { @@ -693,6 +1019,13 @@ impl Tool for QuickPenTool { self.drag_to(cx, p) } PointerKind::Up => { + if self.length.is_some() { + self.snap.clear(); + // 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. Some(pr) if pr.begun => { @@ -721,6 +1054,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() @@ -757,7 +1095,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, @@ -768,6 +1106,18 @@ impl Tool for QuickPenTool { /// The drawing goes on only when the path is back as it was before the press. fn drop_press(&mut self, cx: &ToolContext) -> Vec { self.snap.clear(); + if let Some(drag) = self.length.take() { + self.restore_last_piece(&drag); + if let Some(dr) = self.drawing.as_mut() { + let before = dr.before_press.take(); + if drag.begun { + match (dr.id.and_then(|id| cx.doc.node(id)), before) { + (Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before), + _ => self.drawing = None, + } + } + } + } if self.press.take().is_some_and(|pr| pr.begun) && let Some(dr) = self.drawing.as_mut() { @@ -783,6 +1133,31 @@ impl Tool for QuickPenTool { fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { + // Escape during a length drag takes the drag back and leaves the path being drawn; Enter + // does nothing until the drag ends. + ToolKey::Escape if self.length.is_some() => match self.length.take() { + Some(drag) => { + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; + } + 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()] + } + 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() { @@ -834,6 +1209,9 @@ impl Tool for QuickPenTool { fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.drawing = None; self.snap.clear(); + if self.length.take().is_some_and(|drag| drag.begun) { + return vec![Action::Commit]; + } match self.press.take() { Some(pr) if pr.begun => vec![Action::Commit], _ => vec![], @@ -841,7 +1219,7 @@ impl Tool for QuickPenTool { } fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { - if self.press.is_none() { + if self.press.is_none() && self.length.is_none() { self.drawing = None; } vec![] @@ -860,6 +1238,22 @@ impl Tool for QuickPenTool { fn overlays(&self, cx: &ToolContext) -> Vec { // A stale hover's Smart Guides go with its preview. let mut o = if self.hover_stale(cx) { vec![] } else { self.snap.guides().to_vec() }; + // The length handles: a line from each end to a handle circle beyond it; during a drag, the + // one being dragged, where the changed end is. + let handles: Vec<(Point, Point)> = match &self.length { + Some(drag) => { + let h = &drag.handle; + let sp = cx.doc.node(h.id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(h.si)); + let piece = sp.and_then(|sp| length::end_piece(sp, h.at_start)); + piece.map(|pc| (pc.end, pc.end + pc.out * cx.tol(LENGTH_HANDLE_PX))).into_iter().collect() + } + None if self.press.is_none() => self.length_handles(cx).iter().map(|h| (h.piece.end, h.at)).collect(), + None => vec![], + }; + for &(a, b) in &handles { + o.push(Overlay::Line { a, b, color: FEEDBACK, dashed: false }); + o.push(Overlay::Handle { p: b, color: FEEDBACK }); + } let Some((id, sp)) = self.active(cx) else { return o }; let end = if self.press.is_none() { self.hover_end(cx, sp) } else { None }; // The arc being drawn: the piece a press drags, or the piece the next click adds while the @@ -877,7 +1271,10 @@ impl Tool for QuickPenTool { o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: FEEDBACK, dashed: false }); o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: FEEDBACK, dashed: false }); } + let on_handle = self.hover.is_some_and(|h| handles.iter().any(|&(_, at)| at.distance(h) <= point_tol(cx))); if self.press.is_none() + && self.length.is_none() + && !on_handle && !self.hover_stale(cx) && let Some(h) = end.or(self.hover) { @@ -902,6 +1299,9 @@ impl Tool for QuickPenTool { fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { let tol = point_tol(cx); + if self.length.is_some() || self.length_handle_at(cx, p).is_some() { + return Cursor::Move; + } if let Some((_, sp)) = self.active(cx) { let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); return if close { Cursor::PenClose } else { Cursor::PenDrawing }; @@ -938,5 +1338,7 @@ impl Tool for QuickPenTool { } } +pub mod length; + #[cfg(test)] mod tests; diff --git a/crates/tools/src/quickpen/length.rs b/crates/tools/src/quickpen/length.rs new file mode 100644 index 0000000000..a32751d120 --- /dev/null +++ b/crates/tools/src/quickpen/length.rs @@ -0,0 +1,246 @@ +//! The line or arc at an end of an open path, and that line or arc made longer or shorter: what the +//! Quick Pen's length handles drag and `path.quickPenLength` sets. +//! +//! The piece at an end is the path's last segment when it is straight, or the run of segments +//! before the end that lie on one circle and turn the same way (an arc drawn as several cubic +//! segments of at most 90° each). A line keeps its other point and its direction; an arc keeps its +//! other point, its circle and the way it turns, and its sweep grows or shrinks. + +use std::f64::consts::{FRAC_PI_2, PI}; + +use vectorcraft_geom::{Anchor, Point, SubPath, Vec2}; + +use super::{MAX_TURN, rot, unit}; + +/// The shortest length a line or arc can be set to (points). +pub const MIN_LENGTH: f64 = 0.001; +/// The longest a line can be set to (points). +pub const MAX_LINE_LENGTH: f64 = 1e6; +/// How close, relative to the radius, the points and handles of a segment must be to a circular +/// arc's for the segment to count as one. +const ARC_TOL: f64 = 1e-6; +/// How far, relative to the segment's length, a straight segment's handles may lie off its line. +const LINE_TOL: f64 = 1e-9; + +/// What the piece at an end is. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum EndShape { + Line, + /// An arc around `center` of `radius`, turning through `sweep` radians from the piece's other + /// point to the end (positive as [`rot`] turns). + Arc { + center: Point, + radius: f64, + sweep: f64, + }, +} + +/// The line or arc at one end of an open subpath. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EndPiece { + pub shape: EndShape, + /// The point the piece leaves from, which stays where it is. + pub fixed: Point, + /// The end of the path. + pub end: Point, + /// The direction the path leaves the end in, away from the rest of the path. + pub out: Vec2, + /// The piece's length along the line or the arc. + pub length: f64, +} + +impl EndPiece { + /// The longest length the piece can be set to: for an arc, a sweep of 359°. + pub fn max_length(&self) -> f64 { + match self.shape { + EndShape::Line => MAX_LINE_LENGTH, + EndShape::Arc { radius, .. } => MAX_TURN.to_radians() * radius, + } + } + + /// The length the piece takes when its end is dragged to `p`: for a line, how far along its + /// direction `p` lies; for an arc, the arc to the angle `p` lies at around its center, taken + /// nearest to `near` (the length before), so a drag goes on past a full half turn. Kept within + /// [`MIN_LENGTH`] and [`Self::max_length`]. + pub fn length_toward(&self, p: Point, near: f64) -> f64 { + let l = match self.shape { + EndShape::Line => { + let Some(u) = unit(self.end - self.fixed) else { return self.length }; + u.dot(p - self.fixed) + } + EndShape::Arc { center, radius, sweep } => { + let (a, b) = (self.fixed - center, p - center); + if b.hypot() <= 1e-12 || radius <= 0.0 { + return near; + } + // The angle from the fixed point to `p`, in the way the arc turns, 0 to 2π. + let phi = a.cross(b).atan2(a.dot(b)) * sweep.signum(); + let phi = if phi < 0.0 { phi + 2.0 * PI } else { phi }; + let at = near / radius; + let turns = ((at - phi) / (2.0 * PI)).round(); + (phi + turns * 2.0 * PI) * radius + } + }; + l.clamp(MIN_LENGTH, self.max_length()) + } + + /// The length the piece takes when its handle, pressed at `press`, is dragged to `p`: the end + /// moves with the pointer and stays where it was relative to it. On a line the end keeps the + /// offset the press had from it; on an arc the offset turns with the pointer around the center, + /// so the end stays the same angle behind the pointer at any radius and zoom. + pub fn length_dragged(&self, press: Point, p: Point, near: f64) -> f64 { + let to = match self.shape { + EndShape::Line => p - (press - self.end), + EndShape::Arc { center, .. } => { + let (a, b) = (press - center, self.end - center); + center + rot(p - center, a.cross(b).atan2(a.dot(b))) + } + }; + self.length_toward(to, near) + } +} + +/// `sp`, or a copy reversed when `at_start`, so the end in question is the last point. +fn oriented(sp: &SubPath, at_start: bool) -> SubPath { + let mut o = sp.clone(); + if at_start { + o.reverse(); + } + o +} + +/// The anchor `i` places from the end in question of `sp` (0 is that end), as it would be in `sp` +/// reversed when `at_start`, read without copying the subpath. +fn from_end(sp: &SubPath, at_start: bool, i: usize) -> Option { + if at_start { sp.anchors.get(i).map(Anchor::reversed) } else { sp.anchors.get(sp.anchors.len().checked_sub(i + 1)?).copied() } +} + +/// Does the cubic from `a` to `b` run straight along its chord? +fn straight(a: &Anchor, b: &Anchor) -> bool { + let c = b.p - a.p; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return false; + } + let u = c / l; + let (h1, h2) = (a.h_out - a.p, b.p - b.h_in); + let along = |h: Vec2| u.cross(h).abs() <= LINE_TOL * l && (-LINE_TOL * l..=l * (1.0 + LINE_TOL)).contains(&u.dot(h)); + along(h1) && along(h2) +} + +/// The circle and signed turn of the cubic from `a` to `b` when it is a circular arc as the Quick +/// Pen draws one (handles along the tangents, each 4/3·tan(turn/4) of the radius long). +fn arc_of(a: &Anchor, b: &Anchor) -> Option<(Point, f64, f64)> { + let (d0, d1) = (a.h_out - a.p, b.p - b.h_in); + let (t0, t1) = (unit(d0)?, unit(d1)?); + let turn = t0.cross(t1).atan2(t0.dot(t1)); + if turn.abs() <= 1e-9 || turn.abs() > FRAC_PI_2 + 1e-6 { + return None; + } + let chord = (b.p - a.p).hypot(); + let r = chord / (2.0 * (turn.abs() / 2.0).sin()); + // An arc whose 359° is shorter than the shortest length has no length to set. + if !r.is_finite() || MAX_TURN.to_radians() * r < MIN_LENGTH { + return None; + } + let center = a.p + rot(t0, FRAC_PI_2 * turn.signum()) * r; + let k = 4.0 / 3.0 * (turn.abs() / 4.0).tan() * r; + let tol = ARC_TOL * r.max(1.0); + // The end lies where the turn takes the start around the circle, not only at the right distance. + let on = + (center + rot(a.p - center, turn)).distance(b.p) <= tol && (d0.hypot() - k).abs() <= tol * 100.0 && (d1.hypot() - k).abs() <= tol * 100.0; + on.then_some((center, r, turn)) +} + +/// The line or arc at the end (`at_start`: the start) of the open subpath `sp`, or none for a +/// closed subpath, one of fewer than two points, or an end whose last segment is neither straight +/// nor a circular arc. +pub fn end_piece(sp: &SubPath, at_start: bool) -> Option { + if sp.closed { + return None; + } + last_piece(sp, at_start).map(|(piece, _)| piece) +} + +/// The line or arc that ends at the end (`at_start`: the start) of `sp`, with how many points back +/// from that end the point it leaves from is. It reads only the points of the piece. +fn last_piece(sp: &SubPath, at_start: bool) -> Option<(EndPiece, usize)> { + let at = |i: usize| from_end(sp, at_start, i); + let last = at(0)?; + let prev = at(1)?; + if straight(&prev, &last) { + let out = unit(last.p - prev.p)?; + return Some((EndPiece { shape: EndShape::Line, fixed: prev.p, end: last.p, out, length: prev.p.distance(last.p) }, 1)); + } + let (center, radius, mut sweep) = arc_of(&prev, &last)?; + let mut back = 1; + while let (Some(a), Some(b)) = (at(back + 1), at(back)) { + let Some((c, r, t)) = arc_of(&a, &b) else { break }; + let tol = ARC_TOL * radius.max(1.0); + if c.distance(center) > tol || (r - radius).abs() > tol || t.signum() != sweep.signum() || (sweep + t).abs() >= 2.0 * PI - 1e-9 { + break; + } + sweep += t; + back += 1; + } + let fixed = at(back)?.p; + let out = unit(last.p - last.h_in)?; + Some((EndPiece { shape: EndShape::Arc { center, radius, sweep }, fixed, end: last.p, out, length: sweep.abs() * radius }, back)) +} + +/// `sp` with the line or arc at the end (`at_start`: the start) made `length` long, or none when +/// that end is not a line or an arc ([`end_piece`]) or `length` is outside [`MIN_LENGTH`] to the +/// piece's [`EndPiece::max_length`]. A line keeps its other point and its direction, and its handles +/// scale with it. An arc keeps its other point, its circle and the way it turns, drawn again as +/// segments of at most 90° each; the point it leaves from keeps its kind and incoming handle. +pub fn with_length(sp: &SubPath, at_start: bool, length: f64) -> Option { + if sp.closed { + return None; + } + let (piece, back) = last_piece(sp, at_start)?; + if !(MIN_LENGTH..=piece.max_length()).contains(&length) { + return None; + } + let mut o = oriented(sp, at_start); + let n = o.anchors.len(); + let from = n.checked_sub(back + 1)?; + let last = *o.anchors.get(n - 1)?; + match piece.shape { + EndShape::Line => { + let ratio = length / piece.length; + let to = piece.fixed + piece.out * length; + let prev = o.anchors.get_mut(n - 2)?; + prev.h_out = prev.p + (prev.h_out - prev.p) * ratio; + let end = o.anchors.get_mut(n - 1)?; + *end = Anchor { p: to, h_in: to + (last.h_in - last.p) * ratio, h_out: to + (last.h_out - last.p), kind: last.kind }; + } + EndShape::Arc { center, radius, sweep } => { + let s = length / radius * sweep.signum(); + let start = *o.anchors.get(from)?; + let t0 = unit(start.h_out - start.p)?; + let segs = ((s.abs() / FRAC_PI_2) - 1e-9).ceil().max(1.0) as usize; + let step = s / segs as f64; + let k = 4.0 / 3.0 * (step.abs() / 4.0).tan() * radius; + o.anchors.truncate(from + 1); + if let Some(a) = o.anchors.last_mut() { + a.h_out = a.p + t0 * k; + } + let r0 = start.p - center; + for i in 1..=segs { + let turned = step * i as f64; + let q = center + rot(r0, turned); + let t = rot(t0, turned); + let mut an = Anchor::with_handles(q, q - t * k, q + t * k); + if i == segs { + an.h_out = q + rot(last.h_out - last.p, s - sweep); + an.kind = last.kind; + } + o.anchors.push(an); + } + } + } + if at_start { + o.reverse(); + } + Some(o) +} diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs index 1319948423..ce6fd5ec4b 100644 --- a/crates/tools/src/quickpen/tests.rs +++ b/crates/tools/src/quickpen/tests.rs @@ -315,3 +315,128 @@ fn the_rubber_band_is_the_next_piece() { } } } + +/// A straight end is a line: at the end it keeps its other point and direction, at the start it +/// keeps the end; the points between stay. +#[test] +fn a_line_end_takes_a_new_length_along_its_direction() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(100.0, 50.0, Stroke::Line)], false); + let end = length::end_piece(&sp, false).unwrap(); + assert_eq!(end.shape, length::EndShape::Line); + assert_eq!((end.fixed, end.end, end.length), (pt(100.0, 0.0), pt(100.0, 50.0), 50.0)); + assert!((end.out - Vec2::new(0.0, 1.0)).hypot() < 1e-12); + let longer = length::with_length(&sp, false, 80.0).unwrap(); + let pts: Vec = longer.anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [pt(0.0, 0.0), pt(100.0, 0.0), pt(100.0, 80.0)]); + let shorter = length::with_length(&sp, true, 40.0).unwrap(); + let pts: Vec = shorter.anchors.iter().map(|a| a.p).collect(); + assert_eq!(pts, [pt(60.0, 0.0), pt(100.0, 0.0), pt(100.0, 50.0)]); + assert_eq!(length::with_length(&sp, false, 0.0), None, "too short"); + assert_eq!(length::with_length(&sp, false, length::MAX_LINE_LENGTH * 2.0), None, "too long"); + // Dragged, the length is how far along the line the pointer is, at least the shortest. + assert_eq!(end.length_toward(pt(130.0, 70.0), 50.0), 70.0); + assert_eq!(end.length_toward(pt(100.0, -30.0), 50.0), length::MIN_LENGTH); +} + +/// A half circle drawn as two quarter segments is one arc: a longer one goes around the same circle +/// from the same start, in three segments for 270°, and a shorter one is one segment. +#[test] +fn an_arc_end_keeps_its_circle() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(200.0, 0.0, Stroke::SharpArc)], false); + let end = length::end_piece(&sp, false).unwrap(); + let length::EndShape::Arc { center, radius, sweep } = end.shape else { panic!("an arc: {end:?}") }; + assert!(center.distance(pt(150.0, 0.0)) < 1e-9 && (radius - 50.0).abs() < 1e-9); + assert!((sweep.abs() - PI).abs() < 1e-9); + assert_eq!(end.fixed, pt(100.0, 0.0), "the arc starts where the line ends"); + let three_quarters = length::with_length(&sp, false, 1.5 * PI * 50.0).unwrap(); + assert_eq!(three_quarters.anchors.len(), 5); + assert!(on_circle(&three_quarters, 1, pt(150.0, 0.0), 50.0)); + assert!(three_quarters.anchors.last().unwrap().p.distance(pt(150.0, 50.0)) < 1e-9, "a quarter more, below the center"); + assert_eq!(three_quarters.anchors.get(1).unwrap().p, pt(100.0, 0.0)); + let quarter = length::with_length(&sp, false, 0.5 * PI * 50.0).unwrap(); + assert_eq!(quarter.anchors.len(), 3); + assert!(quarter.anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + // Set back to its own length, the arc is the same. + let same = length::with_length(&sp, false, end.length).unwrap(); + assert!(same.anchors.iter().zip(sp.anchors.iter()).all(|(a, b)| a.p.distance(b.p) < 1e-9 && a.h_in.distance(b.h_in) < 1e-9)); + assert_eq!(length::with_length(&sp, false, 360.0_f64.to_radians() * 50.0), None, "past 359°"); + // 359° is the longest: set to it, the arc ends 1° short of where it starts. + let max = end.max_length(); + assert!((max - 359f64.to_radians() * 50.0).abs() < 1e-9); + let longest = length::with_length(&sp, false, max).unwrap(); + assert!(on_circle(&longest, 1, pt(150.0, 0.0), 50.0)); + let short_of_start = pt(150.0, 0.0) + rot(pt(100.0, 0.0) - pt(150.0, 0.0), 359f64.to_radians() * sweep.signum()); + assert!(longest.anchors.last().unwrap().p.distance(short_of_start) < 1e-6, "{:?}", longest.anchors.last()); + // Dragged around past the start of the half circle, the arc grows on instead of starting again. + let near = 1.5 * PI * 50.0; + let l = end.length_toward(pt(150.0, 80.0), near); + assert!((l - near).abs() < 1e-9, "{l}"); + // Dragged on past 359°, just past its start (above it, since the half circle bulges up), the arc + // stops there. + assert_eq!(end.length_toward(pt(100.0, -1.0), max - 0.01), max); +} + +/// On a small arc, a handle dragged a quarter turn around the circle takes the end a quarter turn +/// around too: the offset of the handle from the end turns with the pointer. +#[test] +fn a_small_arc_end_follows_its_handle_around_the_circle() { + let sp = build(&start(pt(0.0, 0.0)), &[piece(10.0, 0.0, Stroke::SharpArc)], false); + let end = length::end_piece(&sp, false).unwrap(); + let length::EndShape::Arc { center, radius, sweep } = end.shape else { panic!("an arc: {end:?}") }; + assert!((radius - 5.0).abs() < 1e-9); + let press = end.end + end.out * 20.0; + let quarter = end.length + FRAC_PI_2 * radius; + let turned = |p: Point, a: f64| center + rot(p - center, a); + let l = end.length_dragged(press, turned(press, FRAC_PI_2 * sweep.signum()), end.length); + assert!((l - quarter).abs() < 1e-9, "{l} against {quarter}"); + // A handle pressed where it stands and not moved leaves the length as it is. + assert!((end.length_dragged(press, press, end.length) - end.length).abs() < 1e-9); +} + +/// An end that is neither straight nor circular has no length to set, and neither does a closed path. +#[test] +fn other_ends_have_no_piece() { + let mut sp = start(pt(0.0, 0.0)); + sp.anchors.push(Anchor::with_handles(pt(100.0, 0.0), pt(90.0, 40.0), pt(100.0, 0.0))); + if let Some(a) = sp.anchors.first_mut() { + a.h_out = pt(10.0, 5.0); + } + assert_eq!(length::end_piece(&sp, false), None); + assert_eq!(length::with_length(&sp, false, 10.0), None); + // A cubic with a quarter circle's handles whose end is on that circle, but not a quarter turn + // around it, is not an arc. + let k = 4.0 / 3.0 * (FRAC_PI_2 / 4.0).tan() * 100.0; + let mut off = start(pt(0.0, 0.0)); + off.anchors.push(Anchor::with_handles(pt(-100.0, 100.0), pt(-100.0, 100.0 - k), pt(-100.0, 100.0))); + if let Some(a) = off.anchors.first_mut() { + a.h_out = pt(k, 0.0); + } + assert_eq!(length::end_piece(&off, false), None); + // An arc too small to be 0.001 pt long even at 359° has no length to set either. + let tiny = build(&start(pt(0.0, 0.0)), &[piece(0.0001, 0.0, Stroke::SharpArc)], false); + assert_eq!(tiny.anchors.len(), 3); + assert_eq!(length::end_piece(&tiny, false), None); + let mut closed = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line), piece(100.0, 100.0, Stroke::Line)], false); + closed.closed = true; + assert_eq!(length::end_piece(&closed, false), None); +} + +/// A control point may lie past the canvas while the curve stays on it; a curve that reaches past +/// the canvas is refused. +#[test] +fn the_canvas_check_measures_the_curve_not_its_control_points() { + let m = MAX_COORD; + let cubic = |out_x: f64| { + let mut a = Anchor::corner(pt(m - 100.0, 0.0)); + a.h_out = pt(out_x, 0.0); + let mut b = Anchor::corner(pt(m - 100.0, 100.0)); + b.h_in = b.p; + SubPath::new(vec![a, b], false) + }; + assert!(on_canvas(&cubic(m - 100.0))); + assert!(on_canvas(&cubic(m + 100.0))); + assert!(!on_canvas(&cubic(m + 1000.0))); + let mut far = start(pt(m + 1.0, 0.0)); + far.anchors.push(Anchor::corner(pt(0.0, 0.0))); + assert!(!on_canvas(&far)); +} diff --git a/docs/mcp.md b/docs/mcp.md index 87301d0bf5..9d5a482954 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7531,9 +7531,36 @@ the path. The command returns an error and changes nothing when both or neither an unknown `action`, a `turn` outside 1 to 359, a `flip` or `closed` that is not true or false, a `keep` outside 1 to the subpath's points, and for a closed subpath, a locked or hidden path or an `id` that is not a path. +Dragging the handle at the start or end of the path makes the line or arc there longer or shorter, as +[Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) +describes. The tool shows a handle 20 screen points beyond each end of the path being drawn, along the direction the +path leaves that end, where the end is a straight line or a circular arc; with no path being drawn, it shows them on +each open subpath of the one editable path selected. A line keeps its other point and its direction. An arc keeps its +other point, its circle and the way it turns, and its sweep follows the pointer around the circle, up to 359°. The +dragged end stays on its line or circle and does not snap to Smart Guides, and a drag stops where the path would +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°. 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. + +`path.quickPenLength {id, subpath?, end?, length}` does the same for scripts and agents: it makes the line or arc at +`end` (`"end"`, the default, or `"start"`) of the open subpath `subpath` (0 when left out) `length` points long, +selects the path, as one undo step, and answers `{id, kind, length}`, where `kind` is `"line"` or `"arc"`. The arc at an +end is the run of segments before it that lie on one circle and turn the same way, as the Quick Pen draws them. A +`length` the line or arc already has changes nothing and records no undo step. The command returns an error and +changes nothing when `id` or `length` is missing, when `length` is not a number, is under 0.001, or is over 1000000 +for a line or over 359° of its circle for an arc, for an `end` other than `"start"` or `"end"`, an end that is neither +a straight line nor a circular arc (`the end is not a straight line or a circular arc`), a result that would reach past +the canvas, a closed subpath, a locked or hidden path, and an `id` that is not a path. For an arc, the error gives the +359° limit in points, rounded down to the thousandth. + ```json {"name":"run_command","arguments":{"command":"path.quickPen","params":{"start":[100,100],"pieces":[{"x":200,"y":100},{"x":300,"y":200,"action":"continuousArc"},{"x":300,"y":300,"action":"sharpArc","turn":90,"flip":true}]}}} {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"quickPen","key":"action","value":"sharpArc"}}} +{"name":"run_command","arguments":{"command":"path.quickPenLength","params":{"id":12,"end":"start","length":40}}} ``` ## Registration and trim marks diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6e13769bab..8cde7bb34d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -647,6 +647,8 @@ since 2026-10-01. - **Quick Pen protractor:** while an arc is drawn, by a drag or as the piece the next click adds, the Quick Pen tool shows a protractor around the arc's center: a tick every 15° from the arc's start, a longer one every 90°, and one at its end; the next click's piece shows it only with Enable Rubber Band for the Pen tool on. With Smart Guides on, the end of a continuous arc snaps onto the nearest tick within the snapping tolerance of the pointer when no other Smart Guide snaps the point and neither Snap to Grid nor Snap to Pixel snaps drawn points; Shift does not change it. A continuous arc that starts a path sweeps the arc size and does not snap to a tick, Alt tapped during a press moves the piece's end onto or off the tick for the new action, and a hover hides its preview after a snap setting changes until the pointer moves. The protractor, its 15° step and the tick snapping are VectorCraft's own behavior. Tests: tools `the_arc_circle_is_the_circle_the_arc_is_drawn_on`, `a_continuous_arc_end_goes_to_the_nearest_tick`, `a_tick_past_the_coordinate_limit_is_not_used`, `a_continuous_arc_without_a_direction_has_no_tick`, `the_protractor_ticks_lie_across_the_arc`; engine `a_continuous_arc_end_snaps_to_the_protractor`, `a_click_puts_a_continuous_arc_end_on_a_tick`, `an_alt_tap_during_a_press_moves_the_end_for_the_new_action`, `a_click_on_a_tick_leaves_no_preview_back_to_the_pointer`, `a_hover_snaps_to_a_tick_only_for_a_continuous_arc`, `a_hover_shows_nothing_after_smart_guides_change`, `a_click_that_adds_nothing_keeps_a_stale_hover_hidden`, `a_hover_is_hovered_again_when_the_art_changes`, `an_arc_drag_shows_the_protractor`, `a_hovered_arc_shows_the_protractor_with_the_rubber_band`. New tests of existing Quick Pen behavior: `a_point_snaps_to_a_smart_guide`, `hovering_shows_the_distance_label`. Score and hours unchanged. - **Quick Pen arc center:** wherever the Quick Pen tool shows an arc's protractor, it also marks the arc's center with a small cross. The cross is VectorCraft's own behavior. Test: engine `an_arc_shows_a_cross_at_its_center`. Score and hours unchanged. +- **Quick Pen length handles (#2660, in part):** the Quick Pen tool shows a handle beyond the start and the end of the path being drawn, or of the selected path, where the end is a straight line or a circular arc; dragging it makes the line longer or shorter along its direction, or the arc longer or shorter around its circle, as one undo step (`path.quickPenLength`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) describes. A click on a handle that does not drag is an ordinary click. The handle's place, the 359° limit, the 1° minimum for a dragged last arc, Escape during a drag, the handles on a selected path and the dragged end not snapping are VectorCraft's own rules. Tests: tools `quickpen::tests` (`a_line_end_takes_a_new_length_along_its_direction`, `an_arc_end_keeps_its_circle`, `a_small_arc_end_follows_its_handle_around_the_circle`, `other_ends_have_no_piece`), engine `tests::quickpen` (`dragging_the_end_handle_lengthens_the_last_line`, `a_dragged_last_arc_still_flips`, `a_dragged_last_arc_keeps_at_least_one_degree`, `the_end_handle_changes_the_last_arc_on_a_shared_circle`, `another_selected_path_shows_its_handles`, `the_start_handle_of_a_selected_path_shortens_its_arc`, `a_click_on_a_handle_adds_a_point`, `a_length_drag_shows_no_next_piece`, `a_length_drag_stays_on_the_canvas`, `the_start_handle_keeps_the_last_arc_a_piece`, `path_quick_pen_length_sets_an_end`). Score and hours unchanged. + - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 74d9503bbf..f43f353be3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -208,7 +208,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end, drag the handle at a path's start or end to make its line or arc longer or shorter ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the length handles in `quickpen/length.rs` and `path.quickPenLength`, on the path being drawn or the selected path (a line keeps its direction, an arc its circle, up to 359°); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: Ctrl+scroll for the arc size, and editing and deleting with the tool | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` |