Merge pull request #3051 from yoriswind/codex/2312-bezier-space-anchor

Add Anchor: move the new anchor while Space is held
This commit is contained in:
FredApps authored and GitHub committed 2026-11-27 23:07:04 +01:00
commit e293aff875
7 files changed
+404 -48

No files matched your search

+52 -33
View File
@@ -77,7 +77,8 @@ pub enum BezierTool {
/// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
/// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does
/// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is
/// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to
/// selected. Holding Space during that drag moves the anchor and both handles; releasing it resumes pulling.
/// A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to
/// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the
/// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it
/// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does
@@ -250,16 +251,20 @@ enum Target {
t: f64,
from: Point,
},
/// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of
/// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and
/// `in_ctrl` the in handle ⌥ left once it broke the pair.
/// Add Anchor's drag from a segment: `from` stays the original curve point, while Space moves the anchor by
/// `by` with both handles. `last` tracks pointer travel; `out` is the last out handle, and `in_ctrl` the in
/// handle ⌥ left once it broke the pair.
Pull {
path: u64,
segment: KnotRef,
t: f64,
from: Point,
by: Vec2,
out: Point,
in_ctrl: Option<Point>,
last: Pos2,
/// A translated handle stays put until the pointer or its constraints change.
translated_mods: Option<Mods>,
},
/// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point.
Duplicate {
@@ -305,6 +310,7 @@ struct Pointing<'a> {
start: PressStart,
pos: Pos2,
mods: Mods,
space: bool,
}
/// The kind of a part of the overlay.
@@ -623,7 +629,7 @@ impl<'a> BezierOverlay<'a> {
// Anchor's with ⌥, moves it.
BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => {
let from = Self::segment_point(paths, path, segment, t);
Target::Pull { path, segment, t, from, out: from, in_ctrl: None }
Target::Pull { path, segment, t, from, by: Vec2::ZERO, out: from, in_ctrl: None, last: start.origin, translated_mods: None }
}
BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => {
Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) }
@@ -752,34 +758,46 @@ impl<'a> BezierOverlay<'a> {
PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from }
}
&Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from },
&Target::Pull { path, segment, t, from, in_ctrl, .. } => {
&Target::Pull { path, segment, t, from, by, in_ctrl, .. } => {
let to = from + delta;
let out = if mods.shift { handle_45(from, to) } else { snapped(to) };
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
let out = if mods.shift { handle_45(from + by, to) } else { snapped(to) };
PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl }
}
&Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from },
Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None,
})
}
/// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag
/// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass.
fn edit_pulled(
view: &CanvasView,
snap: Option<&Snap>,
tool: BezierTool,
target: &mut Target,
origin: Pos2,
pointer: Pos2,
mods: Mods,
) -> Option<PathEdit> {
if let Target::Pull { from, out, in_ctrl, .. } = target
&& mods.alt
&& in_ctrl.is_none()
{
*in_ctrl = Some(*from - (*out - *from));
/// Keeps Add Anchor's anchor and handles together while Space is held; otherwise pulls the handles.
/// ⌥ leaves the previous in handle in place until Space moves the whole knot again.
fn edit_pulled(tool: BezierTool, target: &mut Target, at: Pointing<'_>) -> Option<PathEdit> {
let Pointing { view, snap, start, pos, mods, space } = at;
if let Target::Pull { path, segment, t, from, by, out, in_ctrl, last, translated_mods } = target {
if space {
let delta = view.to_doc(pos) - view.to_doc(*last);
*by += delta;
*out += delta;
if let Some(incoming) = in_ctrl {
*incoming += delta;
}
*last = pos;
*translated_mods = Some(mods);
return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl });
}
// Space keeps translation priority; on release, Alt can break the pair without moving its geometry.
if mods.alt && in_ctrl.is_none() {
let anchor = *from + *by;
*in_ctrl = Some(anchor - (*out - anchor));
}
// Space moves by raw travel, including off the snap targets. Releasing it is not a pointer move:
// keep that geometry on every stationary pass, but still read modifier-only constraint changes.
if *last == pos && *translated_mods == Some(mods) {
return Some(PathEdit::PullAnchor { path: *path, segment: *segment, t: *t, by: *by, out: *out, in_ctrl: *in_ctrl });
}
*translated_mods = None;
*last = pos;
}
let edit = Self::edit(view, snap, tool, target, origin, pointer, mods);
let edit = Self::edit(view, snap, tool, target, start.origin, pos, mods);
if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) {
*out = *pulled;
}
@@ -846,6 +864,7 @@ impl<'a> BezierOverlay<'a> {
fn run_pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, scene: &Scene, paths: &[EditPath]) {
let snap = canvas_snap(&cx.env);
let view = &space.view;
let space_held = space.space_held();
let mut hovered: Option<(u8, BezierHit, Mods)> = None;
let mut pressed = false;
for item in &scene.items {
@@ -882,10 +901,10 @@ impl<'a> BezierOverlay<'a> {
}
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => {
let first = matches!(press.phase, PressPhase::DragStart { .. });
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, Some(item), paths, first);
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, Some(item), paths, first);
}
PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => {
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths);
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths);
}
PressPhase::Cancel { .. } => *cx.press_slot::<Held>() = None,
_ => {}
@@ -904,10 +923,10 @@ impl<'a> BezierOverlay<'a> {
}
PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => {
let first = matches!(press.phase, PressPhase::DragStart { .. });
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, None, paths, first);
self.drag(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, None, paths, first);
}
PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => {
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods }, click, paths);
self.release(cx, Pointing { view, snap: snap.as_ref(), start, pos, mods: press.mods, space: space_held }, click, paths);
}
PressPhase::Cancel { .. } => *cx.press_slot::<Held>() = None,
_ => {}
@@ -945,7 +964,7 @@ impl<'a> BezierOverlay<'a> {
/// One pass of a press dragged to `pos`; `first` on the pass the drag begins.
fn drag(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, item: Option<&Item>, paths: &[EditPath], first: bool) {
let Pointing { view, snap, start, pos, mods } = at;
let Pointing { view, start, pos, mods, .. } = at;
let kept = cx.press_slot::<Held>().take().filter(|held| held.origin == start.origin);
let mut held = match (kept, item) {
(Some(held), _) => held,
@@ -974,7 +993,7 @@ impl<'a> BezierOverlay<'a> {
}
}
_ => {
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) {
if let Some(edit) = Self::edit_pulled(self.tool, &mut held.target, at) {
self.propose(cx, &held.start, edit);
}
}
@@ -985,7 +1004,7 @@ impl<'a> BezierOverlay<'a> {
/// The release of a press at `pos`: a drag commits, a click does what its tool's click does.
fn release(&mut self, cx: &mut Cx<'_, Self>, at: Pointing<'_>, click: bool, paths: &[EditPath]) {
let Pointing { view, snap, start, pos, mods } = at;
let Pointing { view, start, pos, mods, .. } = at;
// A press reports its Down, and its drag start, before its release, and the overlay holds the press from
// either: a release with nothing held is of a press the overlay let go (a cancelled one), and does nothing.
let Some(held) = cx.press_slot::<Held>().take().filter(|held| held.origin == start.origin) else { return };
@@ -1003,7 +1022,7 @@ impl<'a> BezierOverlay<'a> {
}
if held.began {
let mut target = held.target.clone();
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) {
if let Some(edit) = Self::edit_pulled(self.tool, &mut target, at) {
self.propose(cx, &held.start, edit);
}
// The copy is what was dragged: it ends up selected, not the source.
+13 -3
View File
@@ -452,7 +452,8 @@ pub enum PathEdit {
},
/// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its
/// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth
/// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot.
/// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot. `by` moves the new anchor from
/// the original segment point; both handles are absolute document positions, including that move.
#[non_exhaustive]
PullAnchor {
/// The path's host key.
@@ -461,7 +462,9 @@ pub enum PathEdit {
segment: KnotRef,
/// Position along the segment, 0..=1.
t: f64,
/// The new anchor's out handle.
/// The move of the new anchor from the original segment point, in document units.
by: Vec2,
/// The new anchor's out handle, in document coordinates.
out: Point,
/// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`.
in_ctrl: Option<Point>,
@@ -546,7 +549,14 @@ impl PathEdit {
/// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out`
/// and mirrored, or with the in handle at `in_ctrl`.
pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option<Point>) -> Self {
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
Self::pull_anchor_moved(path, segment, t, Vec2::ZERO, out, in_ctrl)
}
/// Add Anchor's insert with its anchor moved by `by` from the original segment point.
/// `out` and `in_ctrl` are absolute document positions; `None` mirrors `out` through the moved anchor.
/// Hosts applying edits themselves must apply `by` to the inserted anchor before setting the handles.
pub fn pull_anchor_moved(path: u64, segment: KnotRef, t: f64, by: Vec2, out: Point, in_ctrl: Option<Point>) -> Self {
PathEdit::PullAnchor { path, segment, t, by, out, in_ctrl }
}
/// The Curvature tool's toggle of `knot` between smooth and corner.
+13 -6
View File
@@ -137,9 +137,9 @@ impl PathEdit {
/// `by`, then the subpath reflowed.
/// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no
/// reflow and no smoothing, so a straight segment gets a corner knot.
/// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in
/// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when
/// a handle is not finite.
/// - `PullAnchor`: [`EditSubpath::insert_at`], then the new anchor moved by `by`, its out handle at
/// `out` and its in handle at `in_ctrl` (a corner), or mirrored through the moved anchor (smooth).
/// Nothing changes when the offset, moved anchor or a resulting handle is not finite.
/// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner
/// becomes smooth, then the subpath reflows.
/// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`;
@@ -206,16 +206,23 @@ impl PathEdit {
k.in_ctrl += *by;
k.out_ctrl += *by;
}
PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => {
PathEdit::PullAnchor { segment, t, by, out, in_ctrl, .. } => {
let finite = |p: &Point| p.x.is_finite() && p.y.is_finite();
if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) {
if !by.x.is_finite() || !by.y.is_finite() || !finite(out) || !in_ctrl.as_ref().is_none_or(finite) {
return false;
}
let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false };
let Some(at) = sp.insert_at(segment.knot, *t) else { return false };
let k = &mut sp.knots[at];
let anchor = k.anchor + *by;
let incoming = in_ctrl.unwrap_or(anchor - (*out - anchor));
if !finite(&anchor) || !finite(&incoming) {
*path = before;
return false;
}
k.anchor = anchor;
k.out_ctrl = *out;
k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor));
k.in_ctrl = incoming;
k.smooth = in_ctrl.is_none();
}
PathEdit::Convert { knot, out, .. } => {
+301 -5
View File
@@ -1,12 +1,13 @@
//! `BezierOverlay`: the pure path operations, and the overlay's pointer, keyboard and tools through the public API.
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2};
use craft_behavior::{CanvasView, EditEvent};
use craft_draw::ui::{
AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef,
PathEdit, PathSelection, PathTool, SegmentMark,
};
use craft_ui::canvas::{Canvas, Guide, ToolHost, tool_pass};
use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHost, tool_pass};
use craft_ui::canvas_controls::Guides;
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft_ui::primitives::cancel_press_of;
@@ -176,6 +177,7 @@ struct State {
paths: Vec<EditPath>,
selection: PathSelection,
guides: Vec<Guide>,
snap: Option<Snap>,
tool: BezierTool,
handles: HandlesShown,
anchors: AnchorsShown,
@@ -199,6 +201,8 @@ struct State {
tool_clicks: usize,
/// The anchor tool the canvas runs under the overlay, if any.
canvas_tool: Option<PathTool>,
/// The app-owned momentary navigation set, enabled by tests that exercise Space-to-Hand routing.
momentary: Option<Momentary>,
/// Passes in which that tool ran a gesture.
tool_gestures: usize,
}
@@ -246,6 +250,7 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
paths,
selection: PathSelection::default(),
guides: Vec::new(),
snap: None,
tool: BezierTool::Direct,
handles: HandlesShown::Selected,
anchors: AnchorsShown::All,
@@ -264,6 +269,7 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
lone_selects: 0,
tool_clicks: 0,
canvas_tool: None,
momentary: None,
tool_gestures: 0,
}));
let shown = Rc::clone(&state);
@@ -285,6 +291,10 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
let canvas_id = ui.scope_id().with("document canvas");
let canvas = Canvas::new("Document").id(canvas_id).view(view).precise_cursors(st.precise);
let canvas = if st.pans { canvas.document(Size::new(4000.0, 4000.0)) } else { canvas };
let canvas = match &st.snap {
Some(snap) => canvas.snap(snap.clone()),
None => canvas,
};
let mut reply = None;
let canvas = canvas.show(ui, |ui, body| {
// The guides lie under the paths: a stack position hides the levels of the ones below it.
@@ -298,18 +308,25 @@ fn harness_with(paths: Vec<EditPath>, pans: bool) -> Harness {
.segment_mark(st.segment_mark)
.show_at(ui, body.rect);
if let (Some(tool), Some(pass)) = (st.canvas_tool, tool_pass(&body.env)) {
reply = Some(ToolHost::new().run(ui, &pass, &mut AnchorTool::new(tool)));
let mut host = ToolHost::new();
if let Some(momentary) = st.momentary.as_mut() {
host = host.momentary(momentary);
}
reply = Some(host.run(ui, &pass, &mut AnchorTool::new(tool)));
}
output
});
if canvas.output.click_at().is_some() {
st.tool_clicks += 1;
}
if let Some(reply) = reply {
let tool_view = if let Some(reply) = reply {
st.tool_gestures += usize::from(reply.gesture.is_some());
}
reply.view
} else {
None
};
if st.pans {
st.view = canvas.output.view.or(st.view);
st.view = tool_view.or(canvas.output.view).or(st.view);
}
let Some(output) = canvas.inner else { return };
st.id = output.edit.response.id;
@@ -1416,3 +1433,282 @@ fn a_cancelled_press_reports_nothing_on_release() {
assert_eq!(st.changes.len(), changes, "{:?}", st.changes);
assert_eq!(st.paths, before);
}
// Add Anchor owns one drag while Space temporarily translates the new anchor and its handles. Letting Space go
// resumes pulling the handles from that translated anchor; the canvas never takes this owned drag to pan.
#[trial]
fn space_moves_the_pulled_anchor_then_release_resumes_its_handles() {
let space_key = |pressed| egui::Event::Key {
key: egui::Key::Space,
physical_key: Some(egui::Key::Space),
pressed,
repeat: false,
modifiers: egui::Modifiers::NONE,
};
let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6;
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let pulled_at = at + vec2(0.0, 60.0);
h.press_at(at);
h.move_to(at + vec2(0.0, 30.0));
h.move_to(pulled_at);
let (pulled, view) = {
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5);
assert_eq!(st.selection, sel(1, &[(0, 1)]));
let knot = st.paths[0].subpaths[0].knots[1];
assert!(knot.anchor.distance(p(110.0, 60.0)) < 1e-3);
assert!(close(knot.out_ctrl - knot.anchor, Vec2::new(0.0, 60.0)) && knot.smooth);
(knot, st.view.expect("the canvas showed"))
};
h.fixture.frame(vec![space_key(true)]);
{
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots[1], pulled, "Space down alone must not jump the anchor or handles");
}
let moved_at = pulled_at + vec2(30.0, 20.0);
h.move_to(pulled_at + vec2(15.0, 10.0));
h.move_to(moved_at);
let moved = {
let st = h.state.borrow();
let knot = st.paths[0].subpaths[0].knots[1];
let by = Vec2::new(30.0, 20.0);
assert!(close(knot.anchor - pulled.anchor, by), "the held key moves the new anchor with the pointer: {knot:?}");
assert!(
close(knot.out_ctrl - pulled.out_ctrl, by) && close(knot.in_ctrl - pulled.in_ctrl, by),
"both handles travel with the anchor: {knot:?}"
);
assert!(knot.smooth);
assert_eq!(st.view.expect("the canvas showed").center, view.center, "an overlay-owned drag must not turn into a pan");
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "Space adds no second knot");
assert_eq!(st.selection, sel(1, &[(0, 1)]));
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert!(!st.seen.contains(&Seen::Commit) && !st.seen.contains(&Seen::Cancel));
knot
};
h.fixture.frame(vec![space_key(false)]);
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space up alone preserves the current geometry");
let end = moved_at + vec2(20.0, 10.0);
h.move_to(moved_at + vec2(10.0, 5.0));
h.move_to(end);
{
let st = h.state.borrow();
let knot = st.paths[0].subpaths[0].knots[1];
assert!(knot.anchor.distance(moved.anchor) < 1e-6, "released Space leaves the translated anchor in place");
assert!(knot.out_ctrl.distance(view.to_doc(end)) < 1e-6, "the handle follows the pointer again");
assert!(close(knot.in_ctrl - knot.anchor, -(knot.out_ctrl - knot.anchor)) && knot.smooth);
assert!(!close(knot.out_ctrl - knot.anchor, moved.out_ctrl - moved.anchor), "pulling resumes rather than freezing the handles");
assert_eq!(st.view.expect("the canvas showed").center, view.center);
}
h.release_at(end);
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5);
assert_eq!(st.selection, sel(1, &[(0, 1)]));
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit)));
assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set));
assert!(st.inserts.is_empty(), "this drag is not an Insert-key report");
drop(st);
space_before_the_first_movement_translates_from_the_press(space_key);
space_release_preserves_raw_geometry_until_constraints_change(space_key);
space_release_applies_only_an_alt_modifier_still_held(space_key);
}
fn space_before_the_first_movement_translates_from_the_press(space_key: fn(bool) -> egui::Event) {
// Space after the press but before the first movement translates from the press, not from a first pulled handle.
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let to = at + vec2(30.0, 20.0);
h.press_at(at);
h.fixture.frame(vec![space_key(true)]);
h.move_to(to);
let translated = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(translated.anchor.distance(p(140.0, 80.0)) < 1e-3, "the first Space move includes all travel from the press: {translated:?}");
assert!(near(translated.in_ctrl, translated.anchor) && near(translated.out_ctrl, translated.anchor));
h.fixture.frame(vec![space_key(false)]).frame(Vec::new());
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], translated);
let end = to + vec2(20.0, 10.0);
h.move_to(end);
let resumed = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(resumed.anchor, translated.anchor) && resumed.out_ctrl.distance(h.state.borrow().view.unwrap().to_doc(end)) < 1e-6);
h.release_at(end);
assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(h.state.borrow().seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
}
fn space_release_preserves_raw_geometry_until_constraints_change(space_key: fn(bool) -> egui::Event) {
// A real canvas Snap would pull x=160 to the guide at x=165. Space keeps raw translation; release alone must
// not apply that snap, including later stationary passes. Moving or changing Shift/Alt still reads constraints.
let mut targets = SnapTargets::new();
targets.add(SnapTarget::new(craft_behavior::Axis::Y, 165.0, SnapKind::Guide));
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
st.snap = Some(Snap::new(std::sync::Arc::new(targets), SnapOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let pulled_at = at + vec2(20.0, 60.0);
h.press_at(at);
h.move_to(at + vec2(10.0, 30.0));
h.move_to(pulled_at);
let pulled = h.state.borrow().paths[0].subpaths[0].knots[1];
h.fixture.frame(vec![space_key(true)]);
let moved_at = pulled_at + vec2(30.0, 20.0);
h.move_to(moved_at);
let moved = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(moved.anchor, pulled.anchor + Vec2::new(30.0, 20.0)));
assert!(moved.out_ctrl.distance(p(160.0, 140.0)) < 1e-3 && near(moved.in_ctrl, pulled.in_ctrl + Vec2::new(30.0, 20.0)));
h.fixture.frame(vec![space_key(false)]).frame(Vec::new()).frame(Vec::new());
h.move_to(moved_at);
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "no delayed stationary snap after Space release");
// Modifier-only frames travel through the real input/press route: no synthetic PathEdit calls.
h.fixture.hold(egui::Modifiers::SHIFT).frame(Vec::new());
let locked = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(
near(locked.anchor, moved.anchor) && locked.out_ctrl.distance(p(140.0, 140.0)) < 1e-3,
"stationary Shift still locks the handle: {locked:?}"
);
h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new());
let snapped = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(snapped.out_ctrl.distance(p(165.0, 140.0)) < 1e-3, "releasing Shift reevaluates the actual enabled guide snap: {snapped:?}");
h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new());
let alone = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(alone.in_ctrl, snapped.in_ctrl) && !alone.smooth, "stationary Alt still breaks the handle pair: {alone:?}");
let end = moved_at + vec2(20.0, 10.0);
h.move_to(end);
let resumed = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(near(resumed.anchor, moved.anchor) && resumed.out_ctrl.distance(p(180.0, 150.0)) < 1e-3 && near(resumed.in_ctrl, alone.in_ctrl));
h.fixture.hold(egui::Modifiers::NONE);
h.release_at(end);
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots.len(), 5);
assert_eq!(st.selection, sel(1, &[(0, 1)]));
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set));
}
fn space_release_applies_only_an_alt_modifier_still_held(space_key: fn(bool) -> egui::Event) {
// Alt held at Space-up breaks the pair, but an Alt tap released entirely during Space must not latch.
for keep_alt in [true, false] {
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let at = h.screen(p(110.0, 60.0));
let pulled_at = at + vec2(0.0, 60.0);
h.press_at(at);
h.move_to(at + vec2(0.0, 30.0));
h.move_to(pulled_at);
h.fixture.frame(vec![space_key(true)]);
let moved_at = pulled_at + vec2(30.0, 20.0);
h.move_to(moved_at);
let moved = h.state.borrow().paths[0].subpaths[0].knots[1];
assert!(moved.smooth, "the translated pair starts smooth");
h.fixture.hold(egui::Modifiers::ALT).frame(Vec::new());
assert_eq!(h.state.borrow().paths[0].subpaths[0].knots[1], moved, "Space keeps translation priority over Alt");
if !keep_alt {
h.fixture.hold(egui::Modifiers::NONE).frame(Vec::new());
}
let modifiers = if keep_alt { egui::Modifiers::ALT } else { egui::Modifiers::NONE };
let space_up = egui::Event::Key { key: egui::Key::Space, physical_key: Some(egui::Key::Space), pressed: false, repeat: false, modifiers };
h.fixture.frame(vec![space_up]).frame(Vec::new());
let released = h.state.borrow().paths[0].subpaths[0].knots[1];
assert_eq!((released.anchor, released.in_ctrl, released.out_ctrl), (moved.anchor, moved.in_ctrl, moved.out_ctrl));
assert_eq!(released.smooth, !keep_alt, "only Alt still held at Space-up breaks the pair");
h.release_at(moved_at);
let st = h.state.borrow();
assert_eq!(st.paths[0].subpaths[0].knots[1], released, "mouse-up without travel commits the same geometry and smooth state");
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1);
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Commit).count(), 1);
assert!(!st.seen.contains(&Seen::Cancel) && !st.seen.contains(&Seen::Set));
}
}
// Without an overlay-owned press, the same held key still gives the canvas its ordinary hand drag.
#[trial]
fn space_still_pans_when_add_anchor_has_no_drag() {
let space_key = |pressed| egui::Event::Key {
key: egui::Key::Space,
physical_key: Some(egui::Key::Space),
pressed,
repeat: false,
modifiers: egui::Modifiers::NONE,
};
let mut h = harness_with(vec![path_a(), path_b()], true);
h.update(|st| {
st.tool = BezierTool::AddAnchor;
st.canvas_tool = Some(PathTool::AddAnchor);
st.momentary = Some(Momentary::new(NavigationOptions::default()));
});
let (before, paths, selection) = {
let st = h.state.borrow();
(st.view.expect("the canvas showed"), st.paths.clone(), st.selection.clone())
};
// This empty corner is clear of both paths. Drag toward the document interior, away from the origin clamp.
let at = before.rect.right_bottom() - vec2(24.0, 24.0);
h.move_to(at);
h.fixture.frame(vec![space_key(true)]);
h.drag(at, vec2(-60.0, -40.0));
h.fixture.frame(vec![space_key(false)]).settle();
let st = h.state.borrow();
let after = st.view.expect("the canvas showed");
assert!(
after.center.x > before.center.x && after.center.y > before.center.y && (after.center - before.center).hypot() > 1.0,
"ordinary Space still pans: {:?} -> {:?}",
before.center,
after.center
);
assert_eq!(st.paths, paths, "panning does not edit the paths");
assert_eq!(st.selection, selection);
assert!(st.changes.is_empty() && st.inserts.is_empty() && st.deletes.is_empty());
assert!(!st.seen.contains(&Seen::Begin) && !st.seen.contains(&Seen::Commit));
}
// The translated public edit mirrors around the translated anchor and refuses nonfinite resulting geometry
// without partially inserting a knot. The original zero-translation constructor remains covered above.
#[trial]
fn a_translated_pull_mirrors_around_its_anchor_and_refuses_nonfinite_geometry() {
let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false));
let mut path = straight();
let by = Vec2::new(12.0, 7.0);
let out = p(80.0, 40.0);
assert!(PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path));
let knot = path.subpaths[0].knots[1];
assert!(near(knot.anchor, p(50.0, 0.0) + by) && near(knot.out_ctrl, out) && knot.smooth);
assert!((knot.in_ctrl - knot.anchor + (knot.out_ctrl - knot.anchor)).hypot() < 1e-6, "the mirror is about the moved anchor: {knot:?}");
let huge = f64::MAX * 0.75;
let far_x = f64::MAX * 0.25;
let far = ops_path(EditSubpath::new(vec![Knot::corner(p(far_x, 0.0)), Knot::corner(p(far_x, 100.0))], false));
let at = far.subpaths[0].segment(0).unwrap().eval(0.5);
assert!(at.x.is_finite() && at.y.is_finite(), "the input curve is finite before translation");
for (why, mut path, by, out) in [
("NaN offset", straight(), Vec2::new(f64::NAN, 0.0), p(50.0, 30.0)),
("infinite offset", straight(), Vec2::new(0.0, f64::INFINITY), p(50.0, 30.0)),
("overflowing anchor", far, Vec2::new(f64::MAX, 0.0), p(0.0, 0.0)),
("overflowing mirrored handle", straight(), Vec2::new(huge, 0.0), p(-huge, 0.0)),
] {
let before = path.clone();
assert!(!PathEdit::pull_anchor_moved(7, kr(0), 0.5, by, out, None).apply(&mut path), "{why}");
assert_eq!(path, before, "{why}: a refused edit changes nothing");
}
}
+3 -1
View File
@@ -831,7 +831,9 @@ impl<'a> Canvas<'a> {
let press = if self.settled.is_some_and(|settled| settled.swallowing) { PressState::IDLE } else { self.background_press(cx).0 };
let caps_lock = lock_keys::caps_lock(&cx.response.ctx);
let scheme = Env::of_root(&cx.response.ctx).view().get::<ZoomScheme>();
let space = self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key), caps_lock, scheme);
let space = self
.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key), caps_lock, scheme)
.map(|space| space.with_space_held(tool_host::space_held(&cx.response.ctx)));
ToolPass {
id: cx.response.id,
rect: cx.response.rect,
+17
View File
@@ -38,6 +38,7 @@ pub struct CanvasSpace {
pasteboard: PasteboardColor,
precise: bool,
zoom_scheme: ZoomScheme,
space_held: bool,
/// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a
/// measuring pass.
picture: Option<PaintSlot>,
@@ -63,6 +64,7 @@ impl CanvasSpace {
pasteboard: PasteboardColor::Default,
precise: false,
zoom_scheme: ZoomScheme::PHOTOSHOP,
space_held: false,
picture: None,
wheel: None,
zoom_anchor: None,
@@ -123,6 +125,21 @@ impl CanvasSpace {
self.precise
}
/// This space with Space held or released for this pass. A `Canvas` supplies the same real and injected key
/// state its tool reads; a space built with [`new`](Self::new) starts with Space released.
#[must_use]
pub fn with_space_held(mut self, held: bool) -> Self {
self.space_held = held;
self
}
/// Whether Space is held this pass, including an injected held key. A canvas control that owns a drag can
/// read it without turning a key press into a repeat or changing who owns the pointer. This does not claim
/// the key or start a pan; the canvas's tool host still handles momentary tools.
pub fn space_held(&self) -> bool {
self.space_held
}
/// This space with the keys the canvas left to its body in the pass.
#[must_use]
pub fn with_keys(mut self, keys: BodyKeys) -> Self {
+5
View File
@@ -456,6 +456,11 @@ fn held_momentary(ctx: &Context, canvas: Id, around: &commands::CommandChain, ho
})
}
/// Space for canvas controls, sampled from the same real and injected held keys as `ToolContext::held`.
pub(super) fn space_held(ctx: &Context) -> bool {
keys::held(ctx).contains(&Key::Space)
}
/// The tool input a canvas publishes to its body.
#[derive(Clone, PartialEq, crate::contract::MemoProps)]
#[memo_props(every_pass = "a context the canvas rebuilds each pass")]