diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 39b39fc294..78927ef970 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -227,6 +227,16 @@ impl Node { } } + /// The path whose anchors the anchor tools edit, in document space: a path's, or the path of + /// type on a path outside perspective (Add, Delete and Anchor Point tools, Pen + Alt). + pub fn anchor_path(&self) -> Option> { + match &self.kind { + NodeKind::Path { path, .. } => Some(std::borrow::Cow::Borrowed(path)), + NodeKind::Text(t) if self.extras().perspective.is_none() => t.type_path().map(std::borrow::Cow::Owned), + _ => None, + } + } + pub fn path_data_mut(&mut self) -> Option<&mut PathData> { match &mut self.kind { NodeKind::Path { path, .. } => Some(path), diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 5b213f3b08..c4d3cd6bb4 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -487,6 +487,16 @@ impl TextObject { true }) } + /// Replace type on a path's path with `path`, given in document space; the brackets keep their + /// fractions of the path. False, changing nothing, for other type, a degenerate `xf` or a path + /// that would not be finite. + pub fn set_type_path(&mut self, path: &PathData) -> bool { + matches!(self.kind, TextKind::OnPath { .. }) + && self.reshape_local(|frame, to_text| { + *frame = path.transformed(to_text); + true + }) + } /// Edit a copy of the area frame with `f` (given the document → text space map) and keep it /// when `f` succeeds and the result is finite. fn reshape_area(&mut self, f: impl FnOnce(&mut PathData, Affine) -> bool) -> bool { diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 1054ca3ddc..13291b5307 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -33,6 +33,6 @@ mod smooth; pub(super) use anchors::{following_anchors, remove_anchors_of}; pub use commands::specs; -pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt}; +pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt, with_anchor_path}; pub(super) use cut::{components, erase_outline}; pub(super) use freehand::freehand_brushed; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 8068418edd..a1271a39a9 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -1,4 +1,4 @@ -use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound}; +use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, with_anchor_path, within_input_bound}; use super::{ Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2, add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or, @@ -111,6 +111,24 @@ pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result { let ai = usize_req(p, "anchor", C)?; let curvature = switch_or(p, "curvature", false, C)?; let removed = s.edit("Delete Anchor Point", |d, sel| { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + // Type on a path keeps its path: the anchor goes only while two or more stay. + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + if curvature { + vectorcraft_tools::draw2::curvature_remove(sp, ai); + } else { + po::remove_anchors(sp, &[ai]); + } + Ok(()) + })?; + sel.anchors.remove(&id); + sel.segments.remove(&id); + return Ok(false); + } let sp = path_mut(d, id)?.subpaths.get(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; if ai >= sp.anchors.len() { return Err(EngineError::Other("no such anchor".into())); @@ -254,23 +272,24 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "x and y must be finite")); } s.edit("Convert Anchor Point", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if smooth && target.is_none() { - if ai >= sp.anchors.len() { - return Err(EngineError::Other("no such anchor".into())); + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if smooth && target.is_none() { + if ai >= sp.anchors.len() { + return Err(EngineError::Other("no such anchor".into())); + } + // Without a handle position the anchor curves as the Curvature tool curves a point; one + // with no direction to take stays as it is. + vectorcraft_tools::draw2::curvature_smooth(sp, ai); + return Ok(()); } - // Without a handle position the anchor curves as the Curvature tool curves a point; one - // with no direction to take stays as it is. - vectorcraft_tools::draw2::curvature_smooth(sp, ai); - return Ok(()); - } - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - match target { - Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), - _ => a.retract(), - } - Ok(()) + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + match target { + Some(t) if smooth && t.distance(a.p) > 1e-9 => *a = Anchor::smooth(a.p, t), + _ => a.retract(), + } + Ok(()) + }) })?; ok() } @@ -287,13 +306,14 @@ pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result { } let perpendicular = switch_or(p, "perpendicular", false, C)?; s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; - if !bent { - return Err(EngineError::Other("no such segment".into())); - } - Ok(()) + with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + let bent = if perpendicular { sp.bend_segment_perpendicular(seg, t, dv) } else { sp.bend_segment(seg, t, dv) }; + if !bent { + return Err(EngineError::Other("no such segment".into())); + } + Ok(()) + }) })?; ok() } diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 08404a3092..eda5d19d23 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Delete Anchor Point", [], None, - "{id, subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points)", + "{id (a path, or type on a path), subpath?, anchor, curvature?} remove one anchor, re-fitting the curve (with curvature: true, the curve where it was follows the remaining anchors, as the Curvature tool curves its points); type on a path keeps two anchors on its path at least", has_doc, remove_anchor ), @@ -75,7 +75,7 @@ pub fn specs() -> Vec { "Convert Anchor Point", [], None, - "{id, subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", + "{id (a path, or type on a path), subpath?, anchor, to: \"corner\"|\"smooth\", x?, y?} (smooth with x/y: out handle there, in handle mirrored; without: as the Curvature tool curves a point, along the circle through it and its neighbours, or at an open end one handle into the curve)", has_doc, convert_anchor ), @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Reshape Segment", [], None, - "{id, subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", + "{id (a path, or type on a path), subpath?, segment, t, dx, dy, perpendicular?: bool} bend a segment so the point at t moves by (dx, dy); with perpendicular (Shift), both handles stand at right angles to the line between its anchors at one length, and the point at t lies as far from that line as the moved point does", has_doc, reshape_segment ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index f69ac40822..999953eb52 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -308,6 +308,29 @@ pub(super) fn path_mut(d: &mut Document, id: NodeId) -> Result<&mut PathData> { } } +/// Run `f` on the anchors the anchor tools edit on `id` ([`Node::anchor_path`]): a path's, as +/// [`path_mut`] gives them, or type on a path's path in document space. The type keeps the edited +/// path and lays out again; an edit that leaves a subpath with fewer than two anchors, or a path +/// that is not finite or reaches past the canvas, is an error and changes nothing. +pub(in super::super) fn with_anchor_path(d: &mut Document, id: NodeId, f: impl FnOnce(&mut PathData) -> Result) -> Result { + if !matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return f(path_mut(d, id)?); + } + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + let mut path = n.anchor_path().map(std::borrow::Cow::into_owned).ok_or_else(|| EngineError::Other(format!("object {id} is not a path")))?; + let r = f(&mut path)?; + let within = path.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)); + if path.subpaths.is_empty() || path.subpaths.iter().any(|sp| sp.anchors.len() < 2) || !within { + return Err(EngineError::Other(format!("type on a path keeps at least two anchors on its path, within the canvas (object {id})"))); + } + let NodeKind::Text(t) = &mut n.kind else { return Err(EngineError::NoNode(id)) }; + if !t.set_type_path(&path) { + return Err(EngineError::Other(format!("the path of object {id} would not be finite"))); + } + crate::cmd::typecmd::refresh_bounds(t); + Ok(r) +} + pub(super) fn path_of(d: &Document, id: NodeId) -> Result<(PathData, FillRule)> { match d.node(id).map(|n| &n.kind) { Some(NodeKind::Path { path, rule, .. }) => Ok((path.clone(), *rule)), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index de0013036c..62d6f27e27 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", + "{id (a path, or type on a path), subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", has_doc, set_handle ), @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Move Anchor Point", [], None, - "{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again", + "{id (a path, or type on a path), subpath?, anchor, x, y} move one anchor to (x, y), its handles with it; with Live Corners that store a radius (rounded, or straightened by an earlier move), the uncut corner moves by the delta from the drawn anchor to (x, y) and is recut at its radius, so the drawn anchor can finish away from (x, y), and a straightened corner that bends again rounds again", has_doc, move_anchor ), @@ -149,7 +149,7 @@ pub fn specs() -> Vec { "Add Anchor Point", [], None, - "{id, subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected", + "{id (a path, or type on a path), subpath?, segment, t: 0..1, selectAnchor?: bool (the path becomes the selection with only the new anchor direct-selected, also when it is selected)} add an anchor at t on the segment → {anchor}; the direct-selected anchors and selected segments keep the same points (a selected segment it splits stays selected as its two halves), and a path that isn't selected becomes the selection with the new anchor direct-selected; type on a path is left selected whole, with no direct-selected anchors (with selectAnchor, or when it wasn't selected, it becomes the selection)", has_doc, insert_anchor ), @@ -719,39 +719,42 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Reshape", |d, _| { - let path = path_mut(d, id)?; - let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - let old_point = a.p; - let old_handle = if out { a.h_out } else { a.h_in }; - if let Some(to) = at { - a.translate(to - a.p); - } - let handle = if out { a.h_out } else { a.h_in }; - let kind_changes = independent && a.kind != AnchorKind::Corner; - // Ordinary decimal moves can round `at - old_point` differently from the handle's - // translation. Within that calculation's roundoff, place the selected point exactly - // without realigning the other stored Smooth handle. Real edits still use set_handle. - let translation_roundoff = at.is_some_and(|to| { - let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { - let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); - (actual - requested).abs() <= 4.0 * f64::EPSILON * scale - }; - to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) - }); - if !kind_changes && (handle == pos || translation_roundoff) { - if out { - a.h_out = pos; - } else { - a.h_in = pos; + super::draw2::with_anchor_path(d, id, |path| { + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let old_point = a.p; + let old_handle = if out { a.h_out } else { a.h_in }; + if let Some(to) = at { + a.translate(to - a.p); } - } else { - a.set_handle(out, pos, independent); - } - if symmetric { - let opposite = a.p - (pos - a.p); - if out { a.h_in = opposite } else { a.h_out = opposite } - } - Ok(()) + let handle = if out { a.h_out } else { a.h_in }; + let kind_changes = independent && a.kind != AnchorKind::Corner; + // Ordinary decimal moves can round `at - old_point` differently from the handle's + // translation. Within that calculation's roundoff, place the selected point exactly + // without realigning the other stored Smooth handle. Real edits still use set_handle. + let translation_roundoff = at.is_some_and(|to| { + let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { + let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); + (actual - requested).abs() <= 4.0 * f64::EPSILON * scale + }; + to != old_point + && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) + && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) + }); + if !kind_changes && (handle == pos || translation_roundoff) { + if out { + a.h_out = pos; + } else { + a.h_in = pos; + } + } else { + a.set_handle(out, pos, independent); + } + if symmetric { + let opposite = a.p - (pos - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } + Ok(()) + }) })?; ok() } @@ -852,22 +855,26 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out if s.script_running() { return Err(EngineError::Busy); } - let unchanged = s.doc()?.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)).is_some_and(|sp| { - sp.anchors.get(ai).is_some_and(|a| { - let mut linked = *a; - linked.link_handle(out, pos, sp.has_segment(ai, !out)); - linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + let unchanged = s.doc()?.doc.node(id).and_then(Node::anchor_path).is_some_and(|pd| { + pd.subpaths.get(si).is_some_and(|sp| { + sp.anchors.get(ai).is_some_and(|a| { + let mut linked = *a; + linked.link_handle(out, pos, sp.has_segment(ai, !out)); + linked == *a || ((if out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + }) }) }); if unchanged { return ok(); } s.edit("Reshape", |d, _| { - let sp = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - let pull_out = sp.has_segment(ai, !out); - let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - a.link_handle(out, pos, pull_out); - Ok(()) + super::draw2::with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + let pull_out = sp.has_segment(ai, !out); + let a = sp.anchors.get_mut(ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + a.link_handle(out, pos, pull_out); + Ok(()) + }) })?; ok() } @@ -958,6 +965,13 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result { return ok(); } s.edit("Move", |d, sel| { + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + return super::draw2::with_anchor_path(d, id, |path| { + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + *a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p)); + Ok(()) + }); + } let old = d.node(id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).map(|a| a.p); let before = corner_sources(d, id); let moved = BTreeSet::from([(si, ai)]); @@ -975,24 +989,25 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result { ok() } -/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path that has it. -/// Busy while a script runs, as [`Session::edit`] is. +/// Anchor `ai` of subpath `si` of path `id` in the active document, when `id` is a path, or type +/// on a path ([`Node::anchor_path`], in document space), that has it. Busy while a script runs, as +/// [`Session::edit`] is. fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result> { if s.script_running() { return Err(EngineError::Busy); } let d = &s.doc()?.doc; - Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied()) + Ok(d.node(id).and_then(Node::anchor_path).and_then(|path| path.subpaths.get(si).and_then(|sp| sp.anchors.get(ai)).copied())) } -/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or -/// incoming side; false when the path, subpath or anchor is not there. +/// Whether anchor `ai` of subpath `si` of path `id` (or of type on a path's path) has a segment on +/// its outgoing (`out`) or incoming side; false when the path, subpath or anchor is not there. fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result { if s.script_running() { return Err(EngineError::Busy); } let d = &s.doc()?.doc; - Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out))) + Ok(d.node(id).and_then(Node::anchor_path).is_some_and(|path| path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, out)))) } fn set_anchors(s: &mut Session, p: &Value) -> Result { @@ -2610,12 +2625,27 @@ fn insert_anchor(s: &mut Session, p: &Value) -> Result { let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0); let select_anchor = switch_or(p, "selectAnchor", false, "path.insertAnchor")?; let idx = s.edit("Add Anchor Point", |d, sel| { - let path = path_mut(d, id)?; - let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; - if seg >= sp.segment_count() { - return Err(EngineError::Other("no such segment".into())); + let idx = super::draw2::with_anchor_path(d, id, |path| { + let sp = path.subpaths.get_mut(si).ok_or_else(|| EngineError::Other("no such subpath".into()))?; + if seg >= sp.segment_count() { + return Err(EngineError::Other("no such segment".into())); + } + Ok(sp.insert_anchor(seg, t)) + })?; + // Type on a path is selected whole and keeps no direct-selected anchors, as `path.removeAnchor` + // leaves it: the arrow keys and `path.moveAnchors` move anchors of paths only. + if matches!(d.node(id).map(|n| &n.kind), Some(NodeKind::Text(_))) { + if select_anchor || !sel.contains(id) { + sel.clear(); + } + sel.anchors.remove(&id); + sel.segments.remove(&id); + if sel.key_anchor.is_some_and(|(k, _)| k == id) { + sel.key_anchor = None; + } + sel.add(id); + return Ok(idx); } - let idx = sp.insert_anchor(seg, t); renumber_after_insert(sel, id, si, idx); // A path that wasn't selected becomes the selection, its new anchor direct-selected, so // the point added shows and can be edited at once (#4237). `selectAnchor` does the same diff --git a/crates/engine/src/tests/pathtype.rs b/crates/engine/src/tests/pathtype.rs index 5ceba16c10..5209950383 100644 --- a/crates/engine/src/tests/pathtype.rs +++ b/crates/engine/src/tests/pathtype.rs @@ -519,3 +519,138 @@ fn type_on_a_path_made_with_the_type_tool_has_brackets_at_once() { assert!(ink(&s, id).y0 > 299.0, "{tool}: below the path"); } } + +/// Press and release `tool` at `p`. +fn click(s: &mut Session, tool: &str, p: Point) { + let v = ViewInfo::default(); + s.select_tool(tool, v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap(); + } + assert!(!s.in_interaction()); +} + +/// Type along "M100 300 L300 300 L500 300" turned a quarter turn, so a document-space edit isn't +/// the path's own, and selected; with its path in document space. +fn turned_path_type(s: &mut Session) -> NodeId { + let id = path_type(s, "M100 300 L300 300 L500 300", [100.0, 310.0], "Reshaped type"); + s.execute("object.transform", &json!({"ids": [id.0], "matrix": [0, 1, -1, 0, 600, 0]})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + id +} + +fn type_path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData { + text(s, id).type_path().unwrap() +} + +fn close(a: Point, b: Point) -> bool { + near(a.x, b.x) && near(a.y, b.y) +} + +/// #10862: the Anchor Point tool drags handles out of an anchor of selected type on a path's path, +/// in document space through the type's transform, as one undo step, and the type reflows. +#[test] +fn anchor_point_tool_pulls_handles_out_of_type_on_a_path() { + let mut s = session(); + let id = turned_path_type(&mut s); + let middle = type_path(&s, id).subpaths[0].anchors[1].p; + let (glyphs, n) = (origins(&s, id), undo_len(&s)); + let to = middle + vectorcraft_geom::Vec2::new(40.0, 0.0); + drag(&mut s, "anchorPoint", middle, to, Mods::default()); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(close(a.p, middle) && close(a.h_out, to) && close(a.h_in, middle - (to - middle)), "{a:?}"); + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth); + assert_ne!(origins(&s, id), glyphs, "the type reflows along the curved path"); + assert_eq!(undo_len(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!type_path(&s, id).subpaths[0].anchors[1].has_out()); +} + +/// #10862: the rest of the Anchor Point tool's gestures on type on a path's path: a click makes a +/// smooth anchor a corner, a handle drag moves that handle alone, Shift at the press moves the +/// anchor, and a segment drag bends the segment. +#[test] +fn anchor_point_tool_reshapes_type_on_a_path() { + let mut s = session(); + let id = turned_path_type(&mut s); + let [first, middle, last] = [0, 1, 2].map(|i| type_path(&s, id).subpaths[0].anchors[i].p); + let up = vectorcraft_geom::Vec2::new(40.0, 0.0); + drag(&mut s, "anchorPoint", middle, middle + up, Mods::default()); + // A handle end, dragged, moves alone and makes the anchor a corner. + let handle = middle + vectorcraft_geom::Vec2::new(40.0, 30.0); + drag(&mut s, "anchorPoint", middle + up, handle, Mods::default()); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(close(a.h_out, handle) && close(a.h_in, middle - up) && a.kind == vectorcraft_geom::AnchorKind::Corner, "{a:?}"); + // A click on the anchor takes its handles back. + click(&mut s, "anchorPoint", middle); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(!a.has_in() && !a.has_out(), "{a:?}"); + // Shift at the press moves the anchor. + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut s, "anchorPoint", middle, middle + up, shift); + assert!(close(type_path(&s, id).subpaths[0].anchors[1].p, middle + up)); + // A drag on the first segment bends it; its anchors stay. + let on_segment = first.midpoint(middle + up); + drag(&mut s, "anchorPoint", on_segment, on_segment + vectorcraft_geom::Vec2::new(0.0, 30.0), Mods::default()); + let sp = &type_path(&s, id).subpaths[0]; + assert!(close(sp.anchors[0].p, first) && close(sp.anchors[2].p, last)); + assert!(sp.anchors[0].has_out() && sp.anchors[1].has_in(), "the segment curves: {sp:?}"); +} + +/// #10862: the Add and Delete Anchor Point tools add an anchor to type on a path's path and delete +/// one, and Pen + Alt pulls handles out of one; Delete leaves the path two anchors at least, and +/// Scissors does not cut the type. +#[test] +fn add_delete_and_pen_alt_edit_type_on_a_path() { + let mut s = session(); + let id = turned_path_type(&mut s); + let [first, middle] = [0, 1].map(|i| type_path(&s, id).subpaths[0].anchors[i].p); + let quarter = first.midpoint(middle); + click(&mut s, "addAnchor", quarter); + let sp = type_path(&s, id).subpaths[0].clone(); + assert_eq!(sp.anchors.len(), 4); + assert!(close(sp.anchors[1].p, quarter), "{sp:?}"); + let alt = Mods { alt: true, ..Mods::default() }; + let to = quarter + vectorcraft_geom::Vec2::new(0.0, 25.0); + drag(&mut s, "pen", quarter, to, alt); + let a = type_path(&s, id).subpaths[0].anchors[1]; + assert!(close(a.p, quarter) && close(a.h_out, to) && a.kind == vectorcraft_geom::AnchorKind::Smooth, "{a:?}"); + // The Pen's Auto Add/Delete adds an anchor on a segment and deletes it again. + let last = type_path(&s, id).subpaths[0].anchors[3].p; + let three_quarters = middle.midpoint(last); + click(&mut s, "pen", three_quarters); + assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 5); + click(&mut s, "pen", three_quarters); + assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 4); + click(&mut s, "deleteAnchor", quarter); + click(&mut s, "deleteAnchor", middle); + assert_eq!(type_path(&s, id).subpaths[0].anchors.len(), 2); + let n = undo_len(&s); + let r = s.execute("path.removeAnchor", &json!({"id": id.0, "anchor": 0})); + assert!(r.is_err(), "type on a path keeps two anchors: {r:?}"); + assert_eq!((type_path(&s, id).subpaths[0].anchors.len(), undo_len(&s)), (2, n)); + let end = type_path(&s, id).subpaths[0].anchors[1].p; + click(&mut s, "scissors", first.midpoint(end)); + assert!(matches!(text(&s, id).kind, TextKind::OnPath { .. })); + assert_eq!(undo_len(&s), n, "Scissors leaves the type whole"); +} + +/// #10862: `path.insertAnchor` on type on a path, unselected or with `selectAnchor`, leaves the type +/// selected whole with no direct-selected anchors, so `path.moveAnchors` (the arrow keys) moves +/// the type instead of failing on an anchor that is not a path's. +#[test] +fn an_anchor_added_to_type_on_a_path_leaves_it_selected_whole() { + let mut s = session(); + let id = turned_path_type(&mut s); + for select_anchor in [false, true] { + if !select_anchor { + s.execute("select.set", &json!({"ids": []})).unwrap(); + } + s.execute("path.insertAnchor", &json!({"id": id.0, "segment": 0, "t": 0.5, "selectAnchor": select_anchor})).unwrap(); + let sel = &s.doc().unwrap().selection; + assert!(sel.contains(id) && sel.partial(id).is_none() && !sel.anchors.contains_key(&id), "selectAnchor {select_anchor}"); + let before = type_path(&s, id).subpaths[0].anchors[0].p; + s.execute("path.moveAnchors", &json!({"dx": 10, "dy": 0})).unwrap(); + assert!(close(type_path(&s, id).subpaths[0].anchors[0].p, before + vectorcraft_geom::Vec2::new(10.0, 0.0))); + } +} diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cf3551fc19..1e748eab11 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -834,6 +834,23 @@ fn type_path_handles(cx: &ToolContext) -> Vec { out } +/// The anchors and direction handles of selected, editable type on a path's path, for the tools +/// that edit them besides Direct Selection (the Anchor Point, Add and Delete Anchor Point tools and +/// the Pen, #10862): the canvas draws only a path's own. +pub(crate) fn type_path_overlays(cx: &ToolContext) -> Vec { + let editable = cx.doc.editable(); + let mut out = vec![]; + for &id in &cx.selection.objects { + let Some(path) = cx.doc.node(id).filter(|n| is_path_type(n) && editable(id)).and_then(editable_path) else { continue }; + let color = cx.doc.layer_color(id); + out.extend(path.anchors().map(|(_, _, a)| Overlay::Anchor { p: a.p, color, filled: false, size: 5.0 })); + } + if !out.is_empty() { + out.extend(type_path_handles(cx)); + } + out +} + /// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and /// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path, /// subpath, anchor, is_out). diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 7e334ce31f..3b5cd4b4b9 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -377,7 +377,18 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect /// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]). pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec { - let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect(); + candidates(cx, false) +} + +/// [`candidate_paths`], with selected type on a path outside perspective among the selected ones: +/// the objects whose anchors the Add, Delete and Anchor Point tools edit (#10862). +pub(crate) fn anchor_owners(cx: &ToolContext) -> Vec { + candidates(cx, true) +} + +fn candidates(cx: &ToolContext, path_type: bool) -> Vec { + let picks = |n: &vectorcraft_doc::Node| n.path_data().is_some() || (path_type && crate::select::is_path_type(n)); + let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(picks)).collect(); let mut rest = vec![]; walk_pickable(cx, |n| { if let NodeKind::Path { guide: false, .. } = &n.kind { @@ -407,9 +418,28 @@ pub(crate) fn editable_paths<'a>(cx: &'a ToolContext) -> impl Iterator(cx: &'a ToolContext) -> impl Iterator + 'a { + let editable = cx.doc.editable(); + cx.selection.objects.iter().copied().filter(move |&id| { + editable(id) && cx.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. }) || crate::select::is_path_type(n)) + }) +} + /// The paths whose anchors show with the Pen: the selected ones, and those inside selected groups -/// and compound paths (not guides, nor locked or hidden ones). Pen + Alt converts their anchors. +/// and compound paths (not guides, nor locked or hidden ones). pub(crate) fn shown_paths(cx: &ToolContext) -> Vec { + shown(cx, false) +} + +/// [`shown_paths`] with selected type on a path outside perspective, as the Anchor Point tool the +/// Pen lends takes it ([`anchor_owners`]): the objects whose anchors Pen + Alt converts (#10862). +pub(crate) fn shown_anchor_owners(cx: &ToolContext) -> Vec { + shown(cx, true) +} + +fn shown(cx: &ToolContext, path_type: bool) -> Vec { fn inside(n: &vectorcraft_doc::Node, v: &mut Vec) { match &n.kind { NodeKind::Path { guide: false, .. } => v.push(n.id), @@ -424,7 +454,11 @@ pub(crate) fn shown_paths(cx: &ToolContext) -> Vec { } let mut v = vec![]; for n in cx.selection.objects.iter().filter_map(|id| cx.doc.node(*id)) { - inside(n, &mut v); + if path_type && crate::select::is_path_type(n) { + v.push(n.id); + } else { + inside(n, &mut v); + } } let editable = cx.doc.editable(); v.retain(|id| editable(*id)); @@ -436,11 +470,17 @@ pub(crate) fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId anchor_in(cx, candidate_paths(cx), p, tol) } -/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). +/// [`hit_anchor`] on the [`anchor_owners`], selected type on a path's path included. +pub(crate) fn hit_owner_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> { + anchor_in(cx, anchor_owners(cx), p, tol) +} + +/// Nearest anchor within `tol` on the first of `ids` that has one: (path, subpath, anchor). Type on +/// a path among `ids` offers its path's anchors ([`vectorcraft_doc::Node::anchor_path`]). pub(crate) fn anchor_in(cx: &ToolContext, ids: impl IntoIterator, p: Point, tol: f64) -> Option<(NodeId, usize, usize)> { let mut best: Option<((NodeId, usize, usize), f64)> = None; for id in ids { - let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue }; for (si, ai, a) in pd.anchors() { let d = a.p.distance(p); if d <= tol && best.is_none_or(|b| d < b.1 - 1e-9) { @@ -459,11 +499,16 @@ pub(crate) fn hit_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeI segment_in(cx, candidate_paths(cx), p, tol) } +/// [`hit_segment`] on the [`anchor_owners`], selected type on a path's path included. +pub(crate) fn hit_owner_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> { + segment_in(cx, anchor_owners(cx), p, tol) +} + /// Nearest point within `tol` on a segment of the first of `ids` that passes there: (path, -/// subpath, segment, t). +/// subpath, segment, t). Type on a path among `ids` offers its path's segments. pub(crate) fn segment_in(cx: &ToolContext, ids: impl IntoIterator, p: Point, tol: f64) -> Option<(NodeId, usize, usize, f64)> { for id in ids { - let Some(pd) = cx.doc.node(id).and_then(|n| n.path_data()) else { continue }; + let Some(pd) = cx.doc.node(id).and_then(|n| n.anchor_path()) else { continue }; if let Some((si, seg, t, _, d)) = pd.nearest(p) && d <= tol { diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 5a92f70faa..5d6e7ec8e7 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -14,12 +14,14 @@ //! follow the same conversions (#2544). //! Scissors: hover and click snap as the Pen does; click a path to split it there (Alt = add, //! as the Add Anchor Point tool does). +//! Add, Delete and Anchor Point edit the path of selected type on a path outside perspective as +//! they edit a path's (#10862); Delete leaves it two anchors at least, and Scissors does not cut it. use serde_json::json; use vectorcraft_doc::NodeId; use vectorcraft_geom::{ParamCurve, Point}; -use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor}; +use super::{FEEDBACK, hit_anchor, hit_owner_anchor, hit_owner_segment, hit_segment, insert_anchor, remove_anchor}; use crate::direct::hit_handle; use crate::guides::{DrawSnap, HandleSnap}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -276,14 +278,14 @@ impl AnchorTool { } fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { - cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) + cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) } /// Where anchor `ai` is in the document a preview edits: the document as the interaction /// began, since each preview runs on that, otherwise the document `cx` shows. fn began_anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option { let d = cx.interaction_doc.unwrap_or(cx.doc); - d.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) + d.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) } /// Where a blend's spine point `ai` is in the spine a spine edit changes: the spine pinned @@ -342,9 +344,9 @@ impl AnchorTool { let (point, tol) = (cx.point_tol(), cx.pick_tol()); let mut target = if let Some((id, si, ai, out)) = hit_handle(cx, p, point) { State::Handle { id, si, ai, out, start: p, began: false } - } else if let Some((id, si, ai)) = hit_anchor(cx, p, point) { + } else if let Some((id, si, ai)) = hit_owner_anchor(cx, p, point) { State::Convert { id, si, ai, start: p, began: false } - } else if let Some((id, si, seg, t)) = hit_segment(cx, p, tol) { + } else if let Some((id, si, seg, t)) = hit_owner_segment(cx, p, tol) { State::Reshape { id, si, seg, t, start: p, began: false, spine: false } } else { State::Idle @@ -402,12 +404,10 @@ impl AnchorTool { /// instead of converting it. Any other press is kept. fn moving(cx: &ToolContext, st: State) -> State { match st { - State::Convert { id, si, ai, start, .. } => { - match cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) { - Some(from) => State::Move { id, si, ai, from, start, began: false }, - None => st, - } - } + State::Convert { id, si, ai, start, .. } => match Self::anchor_pos(cx, id, si, ai) { + Some(from) => State::Move { id, si, ai, from, start, began: false }, + None => st, + }, State::SpineConvert { id, ai, start, .. } => { match crate::direct::spines(cx) .into_iter() @@ -471,11 +471,11 @@ impl AnchorTool { } fn add(cx: &ToolContext, p: Point) -> Vec { - hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect() + hit_owner_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect() } fn delete(cx: &ToolContext, p: Point) -> Vec { - hit_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect() + hit_owner_anchor(cx, p, cx.point_tol()).map(remove_anchor).into_iter().collect() } } @@ -708,8 +708,8 @@ impl Tool for AnchorTool { let has_handles = cx .doc .node(id) - .and_then(|n| n.path_data()) - .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) + .and_then(|n| n.anchor_path()) + .and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied()) .is_some_and(|a| a.has_in() || a.has_out()); if has_handles { vec![Action::Exec("path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": "corner"}))] @@ -743,7 +743,8 @@ impl Tool for AnchorTool { )] } State::Handle { id, si, ai, out, began: false, .. } => { - let Some(a) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai)) else { + let Some(a) = cx.doc.node(id).and_then(|n| n.anchor_path()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).copied()) + else { return vec![]; }; vec![Action::Exec( @@ -780,6 +781,10 @@ impl Tool for AnchorTool { } fn overlays(&self, cx: &ToolContext) -> Vec { let mut out = if self.id == "anchorPoint" { Self::spine_overlays(cx) } else { vec![] }; + if self.id != "scissors" { + // These tools edit selected type on a path's path, whose anchors the canvas leaves out. + out.extend(crate::direct::type_path_overlays(cx)); + } if matches!(self.state, State::Handle { .. }) { out.extend(self.guides.iter().cloned()); } diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index 9f66d7162c..44bc68cbe1 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -672,6 +672,62 @@ fn anchor_tools_leave_out_shaper_sources_and_art_outside_isolation() { assert_eq!(picked(Some(rect), "deleteAnchor", 100.0, 100.0), Some(rect)); } +/// #10862: selected type on a path's path takes the Anchor Point, Add and Delete Anchor Point tools +/// as a path does; Scissors leaves it alone, and type that is not selected is not picked. +#[test] +fn anchor_tools_edit_selected_type_on_a_path() { + let (d, text) = doc_with_path_type(); + let p = paint(); + let mut s = Selection::default(); + s.add(text); + let names = |a: &[Action]| -> Vec<(String, u64)> { + a.iter() + .filter_map(|x| match x { + Action::Preview(c, v) | Action::Exec(c, v) => Some((c.clone(), v["id"].as_u64()?)), + _ => None, + }) + .collect() + }; + let gesture = |sel: &Selection, tool: &str, from: (f64, f64), to: (f64, f64)| { + let cx = cx(&d, sel, &p); + let mut t = AnchorTool::new(tool); + let mut out = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, from.0, from.1)); + if from != to { + out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1))); + } + out.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1))); + names(&out) + }; + let convert = gesture(&s, "anchorPoint", (400.0, 300.0), (420.0, 260.0)); + assert!(convert.contains(&("path.convertAnchor".into(), text.0)), "{convert:?}"); + assert_eq!(gesture(&s, "addAnchor", (250.0, 300.0), (250.0, 300.0)), vec![("path.insertAnchor".to_string(), text.0)]); + assert_eq!(gesture(&s, "deleteAnchor", (400.0, 300.0), (400.0, 300.0)), vec![("path.removeAnchor".to_string(), text.0)]); + assert!(gesture(&s, "scissors", (250.0, 300.0), (250.0, 300.0)).is_empty(), "Scissors does not cut type"); + let none = Selection::default(); + assert!(gesture(&none, "anchorPoint", (400.0, 300.0), (420.0, 260.0)).is_empty(), "type that is not selected"); +} + +/// #10862: the anchors of selected type on a path's path show with the tools that edit them (the +/// canvas draws only a path's own), not with Scissors, and not when the type is not selected. +#[test] +fn anchor_tools_show_the_anchors_of_selected_type_on_a_path() { + let (d, text) = doc_with_path_type(); + let p = paint(); + let mut s = Selection::default(); + s.add(text); + let anchors = + |o: Vec| -> Vec { o.into_iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(p) } else { None }).collect() }; + let ends = [Point::new(100.0, 300.0), Point::new(400.0, 300.0)]; + let selected = cx(&d, &s, &p); + for tool in ["anchorPoint", "addAnchor", "deleteAnchor"] { + assert_eq!(anchors(AnchorTool::new(tool).overlays(&selected)), ends, "{tool}"); + } + assert_eq!(anchors(crate::pen::PenTool::default().overlays(&selected)), ends, "pen"); + assert!(anchors(AnchorTool::new("scissors").overlays(&selected)).is_empty()); + let none = Selection::default(); + assert!(anchors(AnchorTool::new("anchorPoint").overlays(&cx(&d, &none, &p))).is_empty()); +} + #[test] fn anchor_point_drag_pulls_handles_click_converts() { let (d, id) = doc_with_rect(); diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 3fd145868c..07ba0a3161 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -36,7 +36,7 @@ use vectorcraft_doc::{NodeId, NodeKind}; use vectorcraft_geom::{Anchor, BezPath, Point, Vec2}; use crate::direct::hit_handle; -use crate::draw2::{AnchorTool, editable_paths, shown_paths}; +use crate::draw2::{AnchorTool, editable_anchor_owners, shown_anchor_owners, shown_paths}; use crate::guides::{DrawSnap, Leave}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -225,21 +225,21 @@ fn pick_endpoint(first: Option, last: Point, p: Point, tol: f64, tie: End (None, None) => None, } } -/// Alt held over a handle end, an anchor or a segment of a selected path: the Anchor Point tool's -/// gesture, within its tolerance. +/// Alt held over a handle end, an anchor or a segment of a selected path, or of selected type on a +/// path's path: the Anchor Point tool's gesture, within its tolerance. fn alt_converts(cx: &ToolContext, p: Point, m: Mods) -> bool { let point = cx.point_tol(); m.alt && (hit_handle(cx, p, point).is_some() - || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() - || crate::draw2::segment_in(cx, crate::draw2::shown_paths(cx), p, cx.pick_tol()).is_some()) + || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() + || crate::draw2::segment_in(cx, shown_anchor_owners(cx), p, cx.pick_tol()).is_some()) } /// The cursor where [`alt_converts`]: Alt lends the Anchor Point tool, so its caret over a handle /// end or an anchor, the Reshape Segment cursor over a segment. fn alt_cursor(cx: &ToolContext, p: Point) -> Cursor { let point = cx.point_tol(); - if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, crate::draw2::shown_paths(cx), p, point).is_some() { + if hit_handle(cx, p, point).is_some() || crate::draw2::anchor_in(cx, shown_anchor_owners(cx), p, point).is_some() { Cursor::AnchorPoint } else { Cursor::ReshapeSegment @@ -526,7 +526,8 @@ impl Tool for PenTool { if let Some(t) = &self.convert { return t.overlays(cx); } - let mut o = vec![]; + // Pen + Alt and Auto Add/Delete edit selected type on a path's path, so its anchors show. + let mut o = crate::direct::type_path_overlays(cx); // The rubber band preference hides only the preview segment; Measurement Labels decides the readout. if self.drag.is_none() && self.handle.is_none() @@ -752,15 +753,16 @@ pub(crate) fn continue_from(cx: &ToolContext, id: NodeId, si: usize, at_first: b out } -/// Auto Add/Delete: what a click at `p` does to a selected path. On one of its anchors it deletes -/// it; else, where one of its segments passes within `tol`, it adds an anchor. None when the -/// preference turns it off, Shift is held, or no selected path is there. +/// Auto Add/Delete: what a click at `p` does to a selected path, or to selected type on a path's +/// path. On one of its anchors it deletes it; else, where one of its segments passes within `tol`, +/// it adds an anchor. None when the preference turns it off, Shift is held, or no selected path is +/// there. fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option { if !cx.auto_add_delete || m.shift { return None; } - let anchor = crate::draw2::anchor_in(cx, editable_paths(cx), p, tol).map(crate::draw2::remove_anchor); - anchor.or_else(|| crate::draw2::segment_in(cx, editable_paths(cx), p, tol).map(crate::draw2::insert_anchor)) + let anchor = crate::draw2::anchor_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::remove_anchor); + anchor.or_else(|| crate::draw2::segment_in(cx, editable_anchor_owners(cx), p, tol).map(crate::draw2::insert_anchor)) } /// A click on a selected blend's spine: delete the point under `p` when no key object sits on it diff --git a/docs/mcp.md b/docs/mcp.md index 45f227884a..c5c7fcbdcc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9486,6 +9486,14 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. `path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that keeps its kind, leave the document as it is and record no undo step. +`path.convertAnchor`, `path.reshapeSegment`, `path.setHandle`, `path.moveAnchor`, `path.insertAnchor` and +`path.removeAnchor` also take the `id` of type on a path outside perspective and edit its path in document space, so +the Anchor Point, Add Anchor Point and Delete Anchor Point tools, the Pen with Alt and the Pen's Auto Add/Delete work +on selected type on a path as on a path (#10862); the type lays out again along the edited path, and its brackets keep +their fractions of the path. `path.removeAnchor` refuses to leave the type's path with fewer than two anchors, and an +edit that would put it past the canvas is refused; the document does not change. `path.insertAnchor` leaves the type +selected whole, with no direct-selected anchors, so the arrow keys and `path.moveAnchors` move the whole type. The +Scissors tool does not cut type on a path. On a path with Live Corners that store a radius (rounded, or straightened by an earlier move), `path.moveAnchor` and `path.moveAnchors` (and the arrow keys) move the uncut corner each moved anchor belongs to by the drag delta and cut the corners again at their radii. The corners stay live; a live diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3a0971d182..35df23d3d4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -832,6 +832,7 @@ since 2026-10-01. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. - **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/it/direct_handle_mirror.rs`. +- **Anchor tools on type on a path (#10862):** on selected type on a path outside perspective, the Anchor Point tool and the Pen with Alt (which uses the Anchor Point tool's gestures) pull handles out of, convert, move and bend the type's path, and the Add and Delete Anchor Point tools and the Pen's Auto Add/Delete add and delete its anchors, as on a path; the type lays out again along the edited path, and its path keeps two anchors at least. Type on a path in perspective is not edited by these tools. An anchor added to the type leaves the type selected whole. Regression tests: `anchor_point_tool_pulls_handles_out_of_type_on_a_path`, `anchor_point_tool_reshapes_type_on_a_path`, `add_delete_and_pen_alt_edit_type_on_a_path` and `an_anchor_added_to_type_on_a_path_leaves_it_selected_whole` in `crates/engine/src/tests/pathtype.rs`, `anchor_tools_edit_selected_type_on_a_path` in `crates/tools/src/draw2/anchor/tests.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Commands run during a tool drag:** by VectorCraft's own rule, a command that changes the document while a tool drag is in progress (from a panel, a menu or `run_command`) records its own undo step before the drag's. The drag goes on with the art the command left, Escape cancels only the drag, and Undo takes back the drag first and the command next, with Real-time Drawing on or off. A selection the command makes does not change which objects the drag moves. Commands that keep the drag as a step first (Undo, Redo, `command.batch` and others), a Quick Pen press, and a copy made with `object.transform` during an Alt-drag work as before. Regression tests: `crates/engine/src/tests/interaction_commands.rs` and `tests::drag_commands` in `crates/ui-egui`.