From dcff4edc3d61ba43eb8d0c3c76b5eacab4c34bb8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:55:41 -0800 Subject: [PATCH 1/6] Selection: Cmd/Ctrl lends Direct Selection until it is released With the Selection tool chosen, holding Cmd (Ctrl on Windows and Linux) now lends Direct Selection, or Group Selection when that was chosen last, for each press; the Selection tool is back on the release. With Group Selection chosen, Cmd lends the Selection tool, as it already did with Direct Selection. Selection & Anchor Display > Command Click to Select Objects Behind keeps a Cmd press on a selected object, away from its anchors, handles, mesh points and spine, for selecting the object behind it. A wide stroke's painted area counts as on the object there. - The double-click or triple-click after Cmd-clicks goes to the tool the clicks went to. - Cmd pressed once a drag is under way lends nothing, and the pointer stays the active tool's. - While Cmd is held, the status bar's Current Tool and the help bar name the lent tool, and the canvas shows the lent tool's marks and widgets (blend, Shaper, mirror, trace divider and repeat handles) for the pointer's position in the same frame. - The help bar has hints for Group Selection. The helper that finds a selected object's editable parts under the pointer follows the one in pull request 6597 by SofiaAFigueredo. Docs: docs/ui-parity.md, docs/control-protocol.md (ui.pointer). Co-authored-by: SofiaAFigueredo <223278896+SofiaAFigueredo@users.noreply.github.com> --- crates/engine/src/lib.rs | 10 ++ crates/engine/src/session/documents.rs | 3 + crates/engine/src/tests/draw2.rs | 155 ++++++++++++++++++ crates/engine/src/tooling.rs | 107 ++++++++++-- crates/tools/src/direct.rs | 69 +++++++- crates/tools/src/direct/tests.rs | 27 +++ crates/tools/src/select.rs | 34 ++++ crates/ui-egui/src/canvas.rs | 34 ++-- crates/ui-egui/src/canvas/drag.rs | 8 +- crates/ui-egui/src/canvas/input.rs | 4 +- crates/ui-egui/src/canvas/overlays.rs | 42 +++-- .../src/canvas/selection_marks/tests.rs | 4 +- crates/ui-egui/src/canvas/tests.rs | 38 +++++ crates/ui-egui/src/canvas/tool_overlays.rs | 34 ++-- crates/ui-egui/src/chrome/hints.rs | 12 +- crates/ui-egui/src/chrome/status_bar.rs | 10 +- crates/ui-egui/src/chrome/tests.rs | 13 +- docs/control-protocol.md | 2 +- docs/ui-parity.md | 2 +- 19 files changed, 532 insertions(+), 76 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..e2e329dae1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -106,6 +106,16 @@ pub struct Session { /// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd /// lends the other tools. None until one is chosen. pub(crate) last_selection_tool: Option<&'static str>, + /// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the + /// Selection tool. None until one is chosen. + pub(crate) last_part_selection_tool: Option<&'static str>, + /// The selection tool Cmd lent the last press, which also takes the double-click or + /// triple-click that follows it. None when the press was not lent. + pub(crate) press_lent: Option<&'static str>, + /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] + /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none). None when it was last asked + /// without Cmd. + pub(crate) hover_lent: Option>, pub(crate) last_view: ViewInfo, /// The selection tools' measurements for the active document as it is: a pointer move or a /// cursor asked for again over an unchanged document and selection measures nothing again. diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..7930095b6e 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -65,6 +65,9 @@ impl Session { selection_at_lend: None, lent_selection: None, last_selection_tool: None, + last_part_selection_tool: None, + press_lent: None, + hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), depth: 0, diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..f53a55e1e4 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4698,6 +4698,161 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() { s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap(); } +#[test] +fn cmd_lends_the_selection_tool_direct_selection_or_group_selection_chosen_last() { + // Cmd held with the Selection tool: Direct Selection takes the press until the release, so a + // Cmd-click picks one path inside a group where a plain click picks the group. + let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() }); + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&none), None); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&none), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the Cmd-click picks the path, not its group"); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap(); + assert!(s.active().unwrap().selection.contains(group), "a plain click picks the group"); + // Cmd pressed once a drag is under way lends nothing: the pointer and the named tool stay. + s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 500.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 650.0, 550.0), v).unwrap(); + assert_eq!(s.cursor(Point::new(650.0, 550.0), cmd, v), s.cursor(Point::new(650.0, 550.0), none, v)); + assert_eq!(s.shown_tool_id(&cmd), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 650.0, 550.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + // Group Selection lends the Selection tool, and once chosen, is what the Selection tool borrows. + s.select_tool("groupSelection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("selection")); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("groupSelection")); + s.select_tool("directSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); +} + +#[test] +fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() { + // With the Selection tool, Cmd-clicks go to Direct Selection, and so does the double-click + // after them: it does not isolate the group as the Selection tool's double-click would. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.tool_id(), "selection"); + assert_eq!(s.doc().unwrap().isolation, None, "Direct Selection's double-click does not isolate the group"); + // With Group Selection chosen last, the second click selects the group, and the double-click + // still goes to Group Selection, as both clicks did. + s.select_tool("groupSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.doc().unwrap().isolation, None, "Group Selection's double-click does not isolate the group"); + s.execute("select.none", &json!({})).unwrap(); + // A plain double-click is the Selection tool's: it isolates the group. + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0), v).unwrap(); + } + assert!(s.doc().unwrap().isolation.is_some()); +} + +#[test] +fn a_cmd_press_on_a_selected_object_keeps_select_behind() { + // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; + // with Select Behind off, Direct Selection takes the press there too. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The canvas shows the marks of the tool a press at the pointer takes. + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + s.cursor(Point::new(500.0, 500.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + // On a selected object's anchor, Direct Selection takes the press. + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.prefs.ctrl_click_selects_behind = false; + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { + // Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which + // the Selection tool still hits: a Cmd press there selects the object behind. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + assert!(!s.prefs.use_preview_bounds); + let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // 15 pt outside the path, on its stroke. + let at = Point::new(200.0, 135.0); + assert_eq!(s.hover_tool_at(Some(at), &cmd, v), "selection", "the press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn the_marks_follow_this_frames_pointer_with_cmd_held() { + // The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for + // the pointer where it is now, and with the pointer off the canvas, the tool Cmd lends. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection", "away from the selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "over the selection"); + assert_eq!(s.hover_tool_at(None, &cmd, v), "directSelection", "off the canvas"); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "kept while the view moves"); + assert_eq!(s.hover_tool_at(None, &Mods::default(), v), "selection", "without Cmd"); +} + #[test] fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() { // #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor, diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..ba4f4089e4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -204,6 +204,9 @@ impl Session { } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); + if id != "selection" { + self.last_part_selection_tool = Some(self.tool.id()); + } self.select_whole_instance(id); } Ok(()) @@ -247,8 +250,10 @@ impl Session { /// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract). /// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the /// object (#3901; ). + /// Group Selection lends the Selection tool, and the Selection tool lends Direct Selection or + /// Group Selection, whichever was chosen last (Direct Selection until one is). /// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane. - /// None for the other selection tools and the view tools. + /// None for the view tools. fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> { use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool}; if matches!(id, "hand" | "zoom" | "rotateView") { @@ -257,6 +262,12 @@ impl Session { if id == "directSelection" && mods.cmd { return Some(if mods.alt { "groupSelection" } else { "selection" }); } + if id == "groupSelection" && mods.cmd { + return Some("selection"); + } + if id == "selection" && mods.cmd { + return Some(self.last_part_selection_tool.unwrap_or("directSelection")); + } if id == "perspectiveSelection" && mods.cmd && mods.alt { return None; } @@ -276,15 +287,80 @@ impl Session { self.lent_tool(self.tool.id(), mods) } - /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the - /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, - /// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event - /// for the tool, and the warnings of a preview that keeping the typing applied. - fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec)> { - if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() { + /// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd + /// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and + /// the active tool is not computing an edit, else the active tool. Over a selected object where + /// a Cmd press selects behind, it still names the tool Cmd lends elsewhere. + pub fn shown_tool_id(&self, mods: &Mods) -> &'static str { + match self.lent_tool_id(mods) { + Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The tool whose marks the canvas shows with `mods` held: the selection tool a Cmd press at + /// the pointer would borrow, as [`Self::hover_tool_at`] or [`Self::cursor`] last found it + /// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas + /// asks this while the view moves, when it does not hit-test the art under the pointer. + pub fn hover_tool_id(&self, mods: &Mods) -> &'static str { + let lent = self.hover_lent.unwrap_or_else(|| self.lent_tool_id(mods)); + match lent { + Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the + /// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow + /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the + /// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move. + pub fn hover_tool_at(&mut self, p: Option, mods: &Mods, view: ViewInfo) -> &'static str { + let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = match p { + _ if !lends => None, + Some(p) => self.lent_tool_at(p, mods, view), + None => self.lent_tool_id(mods), + }; + self.hover_lent = lends.then_some(lent); + lent.unwrap_or(self.tool.id()) + } + + /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when + /// the Selection tool keeps a Cmd press on a selected object to select the object behind it + /// (Selection & Anchor Display › Command Click to Select Objects Behind). + fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { + let id = self.lent_tool(self.tool.id(), mods)?; + let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); + (!behind).then_some(id) + } + + /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks + /// before the press, to tell a gesture of the tool in hand from one of a lent tool. + pub fn press_lends_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> bool { + ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.lent_tool_at(ev.pos, &ev.mods, view).is_some() + } + + /// A press with Cmd held (Ctrl elsewhere): the selection tool [`Self::lent_tool_at`] names + /// takes the gesture, pressing without Cmd (a plain click, not Select Behind). The tool lent to + /// stays as it was, unaware, until the release. With a selection tool active, the double-click + /// or triple-click that follows Cmd-clicks goes to the tool the clicks went to, with Cmd kept + /// (Cmd+Shift releases a guide), and that tool is given back after it. → the event for the tool, + /// and the warnings of a preview that keeping the typing applied. + fn lend_selection_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<(PointerEvent, Vec)> { + let follow_up = + matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick) && vectorcraft_tools::catalog::is_selection_tool(self.tool.id()); + if ev.kind == PointerKind::Down { + self.press_lent = None; + } + if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() { return Ok((*ev, vec![])); } - let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) }; + // A follow-up goes where the press before it went, whatever that press selected. + let id = if follow_up { self.press_lent } else { self.lent_tool_at(ev.pos, &ev.mods, view) }; + let Some(id) = id else { return Ok((*ev, vec![])) }; + if !follow_up { + self.press_lent = Some(id); + } // Typing in progress is kept as its own step first: the lent tool's drag previews from the // document its interaction started from, which would drop the typing (#1881). When it // can't be kept, the press is not lent. @@ -312,7 +388,8 @@ impl Session { } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); - Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) + let cmd = follow_up && ev.mods.cmd; + Ok((PointerEvent { mods: Mods { cmd, ..ev.mods }, ..*ev }, settled)) } /// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the @@ -331,6 +408,9 @@ impl Session { let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; + // Back with the Selection or Group Selection tool, a symbol part the lent Direct + // Selection picked gives way to its instance, as choosing the tool does. + self.select_whole_instance(self.tool.id()); if let Some(points) = mesh_points { self.tool.set_option("meshPoints", &points); } @@ -754,7 +834,7 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); - let (ev, settled) = self.lend_selection_tool(ev)?; + let (ev, settled) = self.lend_selection_tool(ev, view)?; let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -778,7 +858,7 @@ impl Session { PointerKind::Up => self.press_point = None, _ => {} } - if ev.kind == PointerKind::Up { + if ev.kind == PointerKind::Up || (lent && matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick)) { self.give_back_tool(view)?; } r @@ -1321,7 +1401,10 @@ impl Session { /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. - let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None }; + // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. + let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None }; + self.hover_lent = lends.then_some(lent); let c = match lent { Some(id) => { let lent = self.make_tool(id); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c889671a6e..7b224e0717 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -385,23 +385,26 @@ pub(crate) fn in_scope(doc: &vectorcraft_doc::Document, scope: Option, i /// shapes, its first child, are left out unless they are the isolated object (Construction mode), /// as clicks leave them out. fn walk_pickable<'a>(doc: &'a vectorcraft_doc::Document, scope: Option, mut f: impl FnMut(&'a Node)) { - fn walk<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { - f(n); - for c in n.children().into_iter().flatten().skip(usize::from(n.extras().shaper.is_some())) { - walk(c, f); - } - } if let Some(id) = scope && let Some(n) = doc.node(id) { - walk(n, &mut f); + walk_pickable_from(n, &mut f); } else if scope.is_none() { for l in &doc.layers { - walk(l, &mut f); + walk_pickable_from(l, &mut f); } } } +/// Visit `n` and the nodes inside it that Direct Selection may pick: a Shaper Group's original +/// shapes are left out ([`walk_pickable`]). +fn walk_pickable_from<'a>(n: &'a Node, f: &mut impl FnMut(&'a Node)) { + f(n); + for c in n.children().into_iter().flatten().skip(usize::from(n.extras().shaper.is_some())) { + walk_pickable_from(c, f); + } +} + /// The spines of the editable blends, topmost first: (blend, spine). pub(crate) fn spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { let mut v = vec![]; @@ -594,6 +597,56 @@ fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, us }) } +/// Is `p` on a part of a selected object that Direct Selection edits: a gradient mesh point, a +/// blend's spine point or segment, an anchor, the end of a direction handle or a segment, within +/// the selection tolerance? A selected group or compound path counts through the editable paths +/// inside it. +pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { + if cx.selection.objects.is_empty() { + return false; + } + let tol = cx.point_tol(); + let seg_tol = cx.pick_tol(); + if hit_handle(cx, p, tol).is_some() + || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() + || selected_spines(cx).iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) + || hit_spine_segment(cx, p, seg_tol).is_some() + { + return true; + } + // The editable paths' control bounds are listed once per document state and selection; a + // hover measures only the paths whose bounds it is near. + let boxes = crate::select::selected_part_boxes(cx, || { + let editable = cx.doc.editable(); + let mut v = vec![]; + for root in cx.selection.objects.iter().filter_map(|&id| cx.doc.node(id)) { + walk_pickable_from(root, &mut |n| { + if editable(n.id) + && let Some(b) = editable_path(n).and_then(|pd| pd.control_bounds()) + { + v.push((n.id, b)); + } + }); + } + v.into() + }); + let reach = tol.max(seg_tol); + boxes.iter().any(|&(id, b)| { + b.inflate(reach, reach).contains(p) + && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { + #[cfg(test)] + MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); + nearest_anchor(&pd, p, tol, None).is_some() || pd.nearest(p).is_some_and(|(.., d)| d <= seg_tol) + }) + }) +} + +#[cfg(test)] +thread_local! { + /// How many paths [`over_selected_part`] has measured on this thread. + static MEASURED_PARTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Is `p` within a press's reach of an anchor of type on a path's path? The anchor wins over a /// bracket standing on it (the end bracket on the last anchor, #3980); the bracket's stem above it /// still drags the bracket. diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 4f3b795921..3cef62fab1 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2794,3 +2794,30 @@ fn a_marquee_skips_the_anchors_and_segments_of_guides_that_cannot_be_picked() { assert!(!crossed(&marquee(false, (140.0, 80.0), (160.0, 120.0))), "locked or hidden: no segment"); assert!(crossed(&marquee(true, (140.0, 80.0), (160.0, 120.0))), "shown and unlocked"); } + +/// A hover over a large selected group measures only the paths near the pointer when it asks +/// whether a Cmd press there lands on a part Direct Selection edits. +#[test] +fn over_selected_part_measures_only_the_paths_near_the_pointer() { + use vectorcraft_doc::{Appearance, Node}; + let mut d = vectorcraft_doc::Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let squares: Vec> = (0..400) + .map(|i| { + let (x, y) = (f64::from(i % 20) * 50.0, f64::from(i / 20) * 50.0); + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)); + std::sync::Arc::new(Node::path(d.alloc_id(), r, Appearance::default_art())) + }) + .collect(); + let g = d.alloc_id(); + d.insert(Some(l), 0, Node::group(g, squares)).unwrap(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(g); + let c = cx(&d, &picked, &p); + let before = MEASURED_PARTS.get(); + assert!(over_selected_part(&c, Point::new(520.0, 520.0)), "on a square's corner"); + assert!(!over_selected_part(&c, Point::new(535.0, 535.0)), "between the squares"); + let measured = MEASURED_PARTS.get() - before; + assert!(measured < 10, "{measured} of 400 paths measured"); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index eee6600591..458ac68232 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -518,6 +518,10 @@ struct Measured { bounds: Option>, oriented: Option>, by_object: HashMap>>, + /// [`painted_bounds`]. + painted: Option>, + /// [`selected_part_boxes`]. + part_boxes: Option>, } impl Measured { @@ -549,6 +553,8 @@ impl PreviewMemo { bounds: None, oriented: None, by_object: HashMap::new(), + painted: None, + part_boxes: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { st.entry = Some(fresh()); @@ -594,6 +600,19 @@ pub fn selection_box(cx: &ToolContext) -> Option { remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } +/// The selection's visual bounds as drawn, its strokes and effects included, whatever Use Preview +/// Bounds says: every point where a hit test finds a selected object is inside them. +fn painted_bounds(cx: &ToolContext) -> Option { + remembered(cx, |m| &mut m.painted, || vectorcraft_effects::preview::bounds_of(cx.doc, &cx.selection.objects, true)) +} + +/// `measure`'s list of the selected objects' editable paths with their control bounds, kept in the +/// session's [`PreviewMemo`] while the document and the selection stay as they are +/// ([`crate::direct::over_selected_part`]). +pub(crate) fn selected_part_boxes(cx: &ToolContext, measure: impl FnOnce() -> std::sync::Arc<[(NodeId, Rect)]>) -> std::sync::Arc<[(NodeId, Rect)]> { + remembered(cx, |m| &mut m.part_boxes, measure) +} + /// [`selection_box`] while the canvas shows it (View › Show Bounding Box, and no anchors selected /// on their own): its handles take a press only then. A path the Pen is drawing keeps its end /// anchor selected, so Cmd/Ctrl lending the Selection tool doesn't scale it by hidden handles (#4980). @@ -1499,6 +1518,21 @@ impl Tool for SelectionTool { } } +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and a +/// selected object under the pointer, away from the anchors, handles and segments Direct +/// Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the press to +/// Direct Selection or Group Selection. +pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { + let tol = cx.pick_tol(); + // The selection's painted bounds come first: away from them, no document walk is needed. They + // take in a wide stroke's outer half, which the bounding box leaves out without Use Preview + // Bounds. + cx.select_behind + && painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) + && objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation).iter().any(|id| cx.selection.contains(*id)) + && !crate::direct::over_selected_part(cx, p) +} + /// Select Behind: of the objects under `p` (topmost first), the one below the lowest selected /// one, back to the topmost after the bottom one; the topmost when none is selected. fn object_behind(cx: &ToolContext, p: Point) -> Option { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b366665d4..cd375d0952 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -43,7 +43,7 @@ pub use cursor::{HOVER_STILL_SECS, STILL_SECS, ViewKey}; use cursor::{cursor_icon, hover_cursor, hover_wait, still_wait}; use drag::drag_id; pub use drag::{apply_requests, dispatch, mods}; -pub(crate) use drag::{art_out, end_art_move, end_document_drag, pose_on_page, release_art_in_window, release_over_panel}; +pub(crate) use drag::{art_out, end_art_move, end_document_drag, held_mods, pose_on_page, release_art_in_window, release_over_panel}; #[cfg(test)] use drag::{frame_moves, tool_drag_doc_id, tool_drag_moved, tool_frame_moves, tool_press_doc_id}; pub use fill::Fill; @@ -413,6 +413,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // 600% zoom, a line at every document pixel over the art, so the pixels it rasterizes to show. let revolve_edit = app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active); let view_info = app.view_info(); + let shown_tool = marks_tool(app, ui.ctx(), hover_still, view_info); if !presenting { if app.ui.view.pixel_preview && v.zoom >= PIXEL_GRID_ZOOM && app.session.prefs.show_pixel_grid { grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false }); @@ -431,7 +432,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } original_path_overlay(app, &painter, &xf); - let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, view_info); + let overlays = selection_visuals(app, &painter, &xf, (hidden_chars, selection_marks, hover_still), revolve_edit, (view_info, shown_tool)); draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs), &mut shared_paths); app.canvas.shared_paths = shared_paths; crate::panels::tabs::paint_stop_guide(app, &painter, &xf); @@ -441,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let quiet = space || ui.data(|d| d.get_temp::(drag_id())).is_some(); overlay_hover_text(ui, &xf, &overlays, quiet, |p| artboards::artboard_name_at(app, ui, &xf, p).is_some()); if !revolve_edit { - shaper_widget_overlay(app, &painter, &xf); + shaper_widget_overlay(app, &painter, &xf, shown_tool); crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); } } @@ -1647,14 +1648,23 @@ pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections: .collect() } -/// The selection's visuals and the tools' overlays, to be drawn. +/// The tool whose marks and widgets the canvas draws this frame: while Cmd is held, the selection +/// tool a press at the pointer borrows. While the view moves (`hover_still` false), the art under +/// the pointer is not hit-tested again (#2452), and the last answer stays. +fn marks_tool(app: &mut VectorcraftApp, ctx: &egui::Context, hover_still: bool, view: vectorcraft_engine::ViewInfo) -> &'static str { + let held = held_mods(app, ctx); + if hover_still { app.session.hover_tool_at(app.hover_doc, &held, view) } else { app.session.hover_tool_id(&held) } +} + +/// The selection's visuals and the tools' overlays, to be drawn. `tool` is the tool whose marks +/// and widgets show ([`vectorcraft_engine::Session::hover_tool_at`]). fn selection_visuals( app: &mut VectorcraftApp, painter: &egui::Painter, xf: &Xf, (hidden_chars, mut marks, hover_still): (HiddenChars, SelectionMarks, bool), revolve_edit: bool, - view_info: vectorcraft_engine::ViewInfo, + (view_info, tool): (vectorcraft_engine::ViewInfo, &str), ) -> Vec { // View → Hide Gradient Annotator hides the Gradient tool's annotator. let mut overlays = if !revolve_edit && (app.session.tool_id() != "gradient" || app.ui.view.gradient_annotator) { @@ -1670,15 +1680,15 @@ fn selection_visuals( overlays.extend(crate::dialogs::live_paint_gaps::overlays(app)); if app.ui.view.edges && !revolve_edit { if hover_still { - hover_highlight(app, painter, xf); + hover_highlight(app, painter, xf, tool); } - selection_overlay(app, painter, xf, overlays.iter().any(|o| matches!(o, Overlay::CurvePoint { .. })), &mut marks); + selection_overlay(app, painter, xf, (tool, overlays.iter().any(|o| matches!(o, Overlay::CurvePoint { .. }))), &mut marks); app.canvas.selection_marks = marks; draw_inside_overlay(app, painter, xf); - mirror_axis_overlay(app, painter, xf); - grid_repeat_overlay(app, painter, xf); - radial_repeat_overlay(app, painter, xf); - trace_split_overlay(app, painter, xf); + mirror_axis_overlay(app, painter, xf, tool); + grid_repeat_overlay(app, painter, xf, tool); + radial_repeat_overlay(app, painter, xf, tool); + trace_split_overlay(app, painter, xf, tool); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); @@ -1694,7 +1704,7 @@ fn selection_visuals( } } if !revolve_edit { - blend_widgets_overlay(app, painter, xf); + blend_widgets_overlay(app, painter, xf, tool); } // Edit › Spelling › Auto Spell Check: shown with the edges hidden too, as it marks the type // rather than the selection. diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 512df6e9a9..953bb29b51 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -272,6 +272,12 @@ pub fn mods(m: egui::Modifiers, space: bool) -> Mods { Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl, space } } +/// The keys held now, with `space` set while Space lends a view tool ([`space_lends_view_tools`]). +pub(crate) fn held_mods(app: &VectorcraftApp, ctx: &egui::Context) -> Mods { + let (m, space) = ctx.input(|i| (i.modifiers, i.key_down(egui::Key::Space))); + mods(m, space_lends_view_tools(app, m, space)) +} + /// Whether Space, held with the modifiers `m`, lends the Hand, Rotate View or Zoom tool. While the /// Type tool edits text, Space types a space, and only Cmd+Space still lends the Zoom tool. pub(super) fn space_lends_view_tools(app: &VectorcraftApp, m: egui::Modifiers, space: bool) -> bool { @@ -384,7 +390,7 @@ pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_e return; } // A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key. - if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() { + if ev.kind == PointerKind::Down && !app.session.press_lends_tool(ev, view) { crate::shortcuts::note_tool_use(app); } let r = app.session.pointer(ev, view); diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index a6a0509de5..eebc036716 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -709,8 +709,10 @@ fn double_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { // the type was clicked, so typing edits it at once. if before != "type" && app.session.tool_id() == "type" { app.session.set_tool_option("prevTool", &json!(before)); + // Without Cmd, so the Type tool takes the click instead of lending a selection tool. + let mods = Mods { cmd: false, ..ev.mods }; for kind in [PointerKind::Down, PointerKind::Up] { - dispatch(app, &PointerEvent { kind, ..ev }, view); + dispatch(app, &PointerEvent { kind, mods, ..ev }, view); } } } diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..02318ad688 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -10,18 +10,19 @@ use super::outline::{KEY_OUTLINE, c32, node_outline, selection_hit_at, stroke_pa use super::selection_marks::{MarkOptions, SelectionMarks}; use super::{BezPath, Color32, CornerRadius, NodeKind, Overlay, Pos2, Shape, Stroke, StrokeKind, Tokens, VectorcraftApp, Xf, vec2}; -pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// Object Highlighting for `tool`, the tool whose marks the canvas shows. +pub(super) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { let Some(h) = app.hover_doc else { return }; // Smart Guides › Object Highlighting: a Smart Guides display option, so it needs them on and Snap to Grid and Pixel Preview off. if !app.ui.view.smart_guides || !app.session.prefs.object_highlighting || app.ui.view.snap_to_grid || app.ui.view.pixel_preview { return; } - if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection") { + if app.session.tool_busy() || !matches!(tool, "selection" | "directSelection" | "groupSelection") { return; } let Some(st) = app.session.active() else { return }; let Some(hit) = selection_hit_at(app, h, xf.zoom) else { return }; - let id = if app.session.tool_id() == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; + let id = if tool == "selection" { hit.top_object(st.isolation) } else { hit.leaf }; if st.selection.contains(id) { return; } @@ -105,9 +106,8 @@ pub(super) fn curve_point(p: &egui::Painter, c: Pos2, color: Color32, filled: bo p.circle(c, size / 2.0, if filled { color } else { Color32::WHITE }, Stroke::new(1.0, color)); } -/// How the current tool and preferences draw the selection's marks. -pub(super) fn mark_options(app: &VectorcraftApp, curve_points_from_tool: bool) -> MarkOptions<'_> { - let tool = app.session.tool_id(); +/// How `tool` and the preferences draw the selection's marks. +pub(super) fn mark_options<'a>(app: &'a VectorcraftApp, tool: &str, curve_points_from_tool: bool) -> MarkOptions<'a> { MarkOptions { direct: vectorcraft_tools::catalog::edits_anchors(tool), curvature: tool == "curvature", @@ -118,7 +118,15 @@ pub(super) fn mark_options(app: &VectorcraftApp, curve_points_from_tool: bool) - } /// Draw selection marks and widgets, keeping the box but hiding dot marks during Halftone Preview. -pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool, marks: &mut SelectionMarks) { +/// `shown` is the tool whose marks show: while Cmd is held, the selection tool a press at the +/// pointer borrows ([`vectorcraft_engine::Session::hover_tool_at`]). +pub(super) fn selection_overlay( + app: &mut VectorcraftApp, + p: &egui::Painter, + xf: &Xf, + (shown, curve_points_from_tool): (&str, bool), + marks: &mut SelectionMarks, +) { // The Selection tool's bounding box (rotated with the objects after a rotation), also shown by // the shape tools that keep a shape just drawn ready to adjust while they draw none (#5477). It // hides while a drag moves, rotates or resizes the selection, so only the art is seen going with @@ -134,11 +142,11 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: let shape_tool = vectorcraft_tools::shape::shows_shape_widgets(app.session.tool_id()); // A shape tool drawing a shape shows none of its widgets; adjusting a widget, it shows the widgets. let drawing = shape_tool && app.session.tool_busy() && !app.session.tool_transforming(); - // Cmd held lends the Selection tool to a press (Direct Selection's included, #3901): its box - // shows while the key is down, where its handles take that press. - let held = super::drag::mods(p.ctx().input(|i| i.modifiers), false); - let lends_selection = !app.session.tool_busy() && app.session.lent_tool_id(&held) == Some("selection"); - let show_box = (app.session.tool_id() == "selection" || lends_selection || (shape_tool && (!app.session.tool_busy() || follows))) + // Cmd held lends a selection tool to a press (Direct Selection's included, #3901): while the + // key is down, the marks are the lent tool's, so the Selection tool's box shows only when it is + // the Selection tool whose handles take that press. + let own = shown == app.session.tool_id(); + let show_box = (shown == "selection" || (shape_tool && own && (!app.session.tool_busy() || follows))) && (follows || !app.session.tool_transforming()) && app.ui.view.bounding_box; let selected_whole = app.session.active().is_some_and(|st| !st.selection.is_empty() && st.selection.anchors.is_empty()); @@ -166,11 +174,11 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: let app = &*app; let Some(st) = app.session.active() else { return }; let symbols = st.doc.symbol_boxes(); - let tool = app.session.tool_id(); + let tool = shown; let direct = vectorcraft_tools::catalog::edits_anchors(tool); // Selection & Anchor Display › Size (1–7, 3 the default): anchors, handles and the bounding // box's handles a point bigger or smaller per step. - let options = mark_options(app, curve_points_from_tool); + let options = mark_options(app, tool, curve_points_from_tool); let grow = options.look.grow; let anchor = |direct: bool| grow + if direct { 5.0 } else { 4.0 }; // The temporary halftone selects its dots; their marks obscure the art (#6369). @@ -286,10 +294,10 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: /// by a line to the spine's halfway point: the Appearance widget hollow above it, the Easing widget /// filled below it. For a blend without a spine the line goes to the halfway point of the straight /// lines between its key centers, which are not drawn. Drawn with the edges hidden too, as they are -/// controls. -pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// controls. `tool` is the tool whose widgets the canvas shows. +pub(super) fn blend_widgets_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { use vectorcraft_tools::blendwidget::{BlendControl, BlendWidget, RADIUS_PX}; - if !matches!(app.session.tool_id(), "selection" | "blend") { + if !matches!(tool, "selection" | "blend") { return; } let Some(st) = app.session.active() else { return }; diff --git a/crates/ui-egui/src/canvas/selection_marks/tests.rs b/crates/ui-egui/src/canvas/selection_marks/tests.rs index 98ef0fdfbc..73dacfd8f0 100644 --- a/crates/ui-egui/src/canvas/selection_marks/tests.rs +++ b/crates/ui-egui/src/canvas/selection_marks/tests.rs @@ -42,7 +42,7 @@ const VIEW: (f64, f64) = (200.0, 150.0); /// The marks drawn one shape at a time, as a frame draws them with nothing kept. fn plain(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool) { let st = app.session.active().unwrap(); - let MarkOptions { direct, curvature, look, all_handles, .. } = mark_options(app, curve_points_from_tool); + let MarkOptions { direct, curvature, look, all_handles, .. } = mark_options(app, app.session.tool_id(), curve_points_from_tool); let symbols = st.doc.symbol_boxes(); let anchor = |direct: bool| look.grow + if direct { 5.0 } else { 4.0 }; let (mut handles, mut with_handles) = (vec![], 0); @@ -264,7 +264,7 @@ fn assert_same(a: &Picture, b: &Picture, what: &str, allowed_per_mille: usize) { fn paint(marks: &mut SelectionMarks, app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, curve_points_from_tool: bool) { let st = app.session.active().unwrap(); let key = st.selection.key; - marks.paint(st, p, xf, &mark_options(app, curve_points_from_tool), key, &st.selection.objects); + marks.paint(st, p, xf, &mark_options(app, app.session.tool_id(), curve_points_from_tool), key, &st.selection.objects); } /// Kept marks, marks built from nothing and plain shapes all draw the same pixels. Kept marks may diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..508ccb03a0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7121,6 +7121,44 @@ fn hidden_shape_widgets_leave_the_bounding_box() { assert_eq!(app.session.cursor(at, Mods::default(), view), Cursor::CornerRadius); } +/// With the Selection tool, Cmd held lends Direct Selection away from the selection, and a selected +/// blend's widgets, which only the Selection and Blend tools press, hide while the key is down. +#[test] +fn blend_widgets_hide_while_cmd_lends_direct_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 90, "y": 190, "width": 20, "height": 20})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 290, "y": 190, "width": 20, "height": 20})).unwrap()); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let blend = id(app.session.execute("object.blend.make", &json!({})).unwrap()); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); + let ctx = egui::Context::default(); + let widgets = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + app.canvas.selection_marks = Default::default(); + let events = vec![egui::Event::ModifiersChanged(modifiers)]; + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let r = vectorcraft_tools::blendwidget::RADIUS_PX; + let mut n = 0; + let mut count = |s: &Shape| n += usize::from(matches!(s, Shape::Circle(c) if c.radius == r)); + for c in &out.shapes { + match &c.shape { + Shape::Vec(v) => v.iter().for_each(&mut count), + s => count(s), + } + } + n + }; + let plain = widgets(&mut app, egui::Modifiers::NONE); + assert!(plain >= 2, "the Appearance and Easing widgets: {plain}"); + let held = widgets(&mut app, egui::Modifiers::COMMAND); + assert!(held + 2 <= plain, "hidden while Cmd lends Direct Selection: {held} of {plain}"); + assert_eq!(widgets(&mut app, egui::Modifiers::NONE), plain, "back when the key is let go"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 958872d6b0..c6d3855403 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -619,10 +619,11 @@ pub(super) fn print_tiling_overlay(app: &mut VectorcraftApp, p: &egui::Painter, const PRINT_TILING: Color32 = Color32::from_gray(96); /// A Shaper Group's mode widget (Shaper and Selection tools), drawn with selection edges shown or -/// hidden: an arrow pointing right in Face Selection mode and left in Construction mode. -pub(super) fn shaper_widget_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// hidden: an arrow pointing right in Face Selection mode and left in Construction mode. `tool` is +/// the tool whose widgets the canvas shows. +pub(super) fn shaper_widget_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { let Some(st) = app.session.active() else { return }; - if matches!(app.session.tool_id(), "shaper" | "selection") + if matches!(tool, "shaper" | "selection") && let Some(w) = vectorcraft_tools::shaperwidget::ShaperWidget::of(&st.doc, &st.selection, st.isolation, xf.zoom) { let (c, r) = (xf.to_screen(w.at), vectorcraft_tools::shaperwidget::RADIUS_PX); @@ -635,9 +636,10 @@ pub(super) fn shaper_widget_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: } } -/// High-contrast live controls, using the same geometry as the Selection tool's hit testing. -pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { +/// High-contrast live controls, using the same geometry as the Selection tool's hit testing, while +/// `tool`, the tool whose widgets the canvas shows, is the Selection tool. +pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { + if tool != "selection" || !app.ui.view.bounding_box { return; } let Some(st) = app.session.active() else { return }; @@ -664,9 +666,9 @@ pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & /// The Split view's divider of the selected Image Trace object, where the Selection tool's hit /// testing finds it: a line across the source image with a grip in its middle, at its place in the /// zoomed, scrolled or turned view. Hidden with the bounding box and in Outline mode, as the hit -/// testing is. -pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box || app.outline_view() { +/// testing is. Drawn while `tool`, the tool whose widgets the canvas shows, is the Selection tool. +pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { + if tool != "selection" || !app.ui.view.bounding_box || app.outline_view() { return; } let Some(st) = app.session.active() else { return }; @@ -691,10 +693,11 @@ pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & } /// A selected grid repeat's row, column and corner handles and its spacing sliders (#2691), at -/// the places the Selection tool's hit testing finds them. -pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// the places the Selection tool's hit testing finds them, while `tool`, the tool whose widgets the +/// canvas shows, is the Selection tool. +pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { use vectorcraft_tools::repeat_grid::{GridHandles, GridPart, HANDLE_RADIUS, SLIDER_HALF}; - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { + if tool != "selection" || !app.ui.view.bounding_box { return; } let frame = app.selection_box(); @@ -722,10 +725,11 @@ pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, x /// A selected radial repeat's circle with its radius handle and its splitter on it, and its /// instances handle below it, at the places the Selection tool's hit testing finds them. The -/// splitter also has a short line across the circle. -pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { +/// splitter also has a short line across the circle. Drawn while `tool`, the tool whose widgets +/// the canvas shows, is the Selection tool. +pub(super) fn radial_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf, tool: &str) { use vectorcraft_tools::repeat_radial::{HANDLE_RADIUS, RadialHandles, RadialPart}; - if app.session.tool_id() != "selection" || !app.ui.view.bounding_box { + if tool != "selection" || !app.ui.view.bounding_box { return; } let frame = app.selection_box(); diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 2c679c72a1..99dc7fdc25 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -27,6 +27,14 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> { ("Shift+Click", true), (" to add", false), ], + "groupSelection" => &[ + ("Click", true), + (" an object in a group to select it | ", false), + ("Click again", true), + (" to add the group it is in | ", false), + ("Shift+Click", true), + (" to add", false), + ], "pen" => &[ ("Click", true), (" to add a corner point | ", false), @@ -252,7 +260,9 @@ pub fn hint_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let segments = if let Some(d) = app.ui.dialog.as_ref().filter(|d| crate::dialogs::revolve_gizmo::active(d)) { vec![(crate::dialogs::revolve_gizmo::hint(d).into(), false)] } else { - let tool = app.session.tool_id(); + // While Cmd is held, the hints of the selection tool it lends. + let held = crate::canvas::held_mods(app, ui.ctx()); + let tool = app.session.shown_tool_id(&held); let hint = if tool == "zoom" && crate::canvas::animated_zoom(&app.session.prefs) { ANIMATED_ZOOM_HINT } else { tool }; hint_segments(hint) }; diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 126cc956f3..3f42999f87 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -73,7 +73,8 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { app.status(e); } ui.separator(); - let (info, next) = info_text(app); + let held = crate::canvas::held_mods(app, ui.ctx()); + let (info, next) = info_text(app, &held); if let Some(secs) = next { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } @@ -183,12 +184,13 @@ pub fn set_status_bar_show(app: &mut VectorcraftApp, p: &serde_json::Value) -> R } /// The info field's text for the choice in the Show menu, and for Date and Time the seconds until -/// the minute it shows ends (when the bar draws again). -pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option) { +/// the minute it shows ends (when the bar draws again). Current Tool names the selection tool Cmd +/// lends while it is held (`held`). +pub(super) fn info_text(app: &VectorcraftApp, held: &vectorcraft_tools::Mods) -> (String, Option) { let st = app.session.active(); match app.ui.status_bar_show { StatusBarShow::CurrentTool => { - let tool = vectorcraft_tools::tool_info(app.session.tool_id()) + let tool = vectorcraft_tools::tool_info(app.session.shown_tool_id(held)) .map(|t| { // The catalog keys carry the full label ("Selection Tool"); only English drops the suffix. let shown = tl!(t.label); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 3b889b1f09..dd83a691b6 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1099,6 +1099,17 @@ fn text_center(texts: &[StatusText], text: &str) -> egui::Pos2 { at.clip.intersect(at.bounds).center() } +/// While Cmd/Ctrl is held, Current Tool names the selection tool a press would borrow: Direct +/// Selection with the Selection tool chosen, and the Selection tool again once the key is let go. +#[test] +fn current_tool_names_the_selection_tool_cmd_lends() { + let (app, _ctx) = status_readout_app(); + let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() }; + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(super::status_bar::info_text(&app, &cmd).0, "Direct Selection"); + assert_eq!(super::status_bar::info_text(&app, &Default::default()).0, "Selection"); +} + /// The status bar's info field shows the readout `view.statusBarShow` chooses: the navigator's /// artboard name, the tool in use, the date and time, the undo and redo counts, or the document's /// color profile. @@ -1130,7 +1141,7 @@ fn the_status_bar_info_field_shows_the_chosen_readout() { // The labels take the UI language's colon (#7991). let fr = crate::i18n::Lang::from_code("fr").unwrap(); crate::i18n::set_current(fr); - let (french, _) = super::status_bar::info_text(&app); + let (french, _) = super::status_bar::info_text(&app, &Default::default()); crate::i18n::set_current(crate::i18n::Lang::EN); assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos"))); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..58c13dbe9b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is), and the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool, and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object away from its anchors, handles and segments while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9fd857a9d..f9f140fc76 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -366,7 +366,7 @@ tools, never checked side by side) isn't captured row by row. | Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | | Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | | A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); engine pointer and canvas regressions | +| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, away from its anchors, handles and segments, still selects the object behind it while Command Click to Select Objects Behind is on; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool it lends ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Work with selections"); engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | | Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | From 555b6192283c61fd23e2a9e3faad39c3ddf286ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:34:20 -0800 Subject: [PATCH 2/6] Selection: Cmd Select Behind works on grouped art and line art A Cmd press with the Selection tool now selects behind on a group that holds a selected member, as it does on a selected object, so repeated Cmd-clicks on grouped art reach the object behind the group. A path's segments no longer keep the press for Direct Selection, so a Cmd-click on a selected stroke-only path selects behind it. Select Behind needs another object under the pointer: on a lone object the press is lent. The bounding box's handles and rotate zones also lend the press. - A double-click that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing, also when the press and the double-click come in one frame. After an edit or a selection change, or after a press that drags or is released away from where it began, it is an ordinary double-click. - Whether a press selects behind is kept for the pointer's position while the document, the selection, the live inputs and the hit-test settings stay as they are, so the cursor, the canvas marks and the press do not walk the document again. A layer or group effect that draws art widens the area checked; raster effects and color adjustments do not. - The selected blends' spines are built once per check. - The status bar and the help bar name the tool a press at the pointer takes, which is the Selection tool where the press selects behind, and they are drawn again when it changes. The canvas drops a hover's decision once the tool, the selection or a preference it depends on changes. Docs: docs/mcp.md (pointer_gesture, and Cmd+Alt with Direct Selection), docs/control-protocol.md, docs/ui-parity.md, docs/target-app-parity.md. --- crates/doc/src/hit.rs | 2 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/tests/draw2.rs | 192 +++++++++++++++- crates/engine/src/tests/dynamic_symbols.rs | 20 ++ crates/engine/src/tooling.rs | 49 ++++- crates/tools/src/direct.rs | 32 +-- crates/tools/src/direct/tests.rs | 27 +++ crates/tools/src/select.rs | 245 +++++++++++++++++++-- crates/ui-egui/src/canvas.rs | 12 +- crates/ui-egui/src/canvas/tests.rs | 105 +++++++++ docs/control-protocol.md | 2 +- docs/mcp.md | 9 +- docs/target-app-parity.md | 2 +- docs/ui-parity.md | 2 +- 14 files changed, 654 insertions(+), 50 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 7c0de44cab..8f96d46df2 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -189,7 +189,7 @@ pub fn set_live_art(f: LiveArt, inputs: LiveInputs) { } /// The registered [`LiveInputs`] now, 0 while nothing is registered. -fn live_inputs() -> u64 { +pub fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e329dae1..bbcba38fff 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -113,9 +113,10 @@ pub struct Session { /// triple-click that follows it. None when the press was not lent. pub(crate) press_lent: Option<&'static str>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] - /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none). None when it was last asked + /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with + /// the document state, active tool and keys it was found for. None when it was last asked /// without Cmd. - pub(crate) hover_lent: Option>, + pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>, pub(crate) last_view: ViewInfo, /// The selection tools' measurements for the active document as it is: a pointer move or a /// cursor asked for again over an unchanged document and selection measures nothing again. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index f53a55e1e4..3ffd8e4576 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4786,11 +4786,21 @@ fn a_cmd_press_on_a_selected_object_keeps_select_behind() { let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); s.select_tool("selection", v).unwrap(); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); - // The canvas shows the marks of the tool a press at the pointer takes. + // The canvas shows the marks of the tool a press at the pointer takes, and the status bar and + // the help bar name it. s.cursor(Point::new(200.0, 200.0), cmd, v); assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.shown_tool_id(&cmd), "selection", "the press selects behind: nothing is lent"); s.cursor(Point::new(500.0, 500.0), cmd, v); assert_eq!(s.hover_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + // The bounding box's top middle handle, on the middle of the top segment: the press is lent. + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 150.0)), &cmd, v), "directSelection", "on a box handle"); + // Turning Select Behind off changes what the bars name over the selection. + s.cursor(Point::new(200.0, 200.0), cmd, v); + s.prefs.ctrl_click_selects_behind = false; + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + s.prefs.ctrl_click_selects_behind = true; s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); assert_eq!(s.tool_id(), "selection"); s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); @@ -4833,6 +4843,186 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); } +#[test] +fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { + // The first Cmd-click on an unselected group lends Direct Selection, which selects the path + // under the pointer. The group holds that selected path, so the next Cmd-click there selects + // the object behind the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 210.0, 150.0, 40.0, 40.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 170.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 170.0).with_mods(cmd), v).unwrap(); + }; + click(&mut s); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the first Cmd-click picks the path"); + assert_eq!(s.hover_tool_at(Some(Point::new(170.0, 170.0)), &cmd, v), "selection", "the next press selects behind"); + click(&mut s); + // Made quickly, the two clicks are also a double-click, which neither isolates the group nor + // changes what the second click selected, also with Cmd let go before it. + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 170.0, 170.0), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group"); +} + +#[test] +fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { + // A double-click that follows a Cmd-click selecting behind keeps what it selected, but only + // while the document stays as that click left it. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() { + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() { + // A Cmd press that selects behind and then drags is not a click, also when the drag ends where + // it began and moves nothing, so a double-click there is a double-click of its own. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_select_behind() { + // The automation interface can send the release far from the press with no drag between. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 270.0, 270.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() { + // The second press and the double-click can come in one frame, before the release. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None, "the double-click neither isolates nor edits"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(front) && !picked.contains(back), "the press selects behind, back to the topmost"); +} + +#[test] +fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() { + // The group counts as selected wherever its art is, not only over its selected member. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 300.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member"); + s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group"); +} + +#[test] +fn a_cmd_click_on_a_selected_lines_segment_selects_behind() { + // An open, unfilled path is only hit near its segments: a Cmd press there selects the object + // behind it, and a Cmd press on its anchor is Direct Selection's. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = line(&mut s, 150.0, 150.0, 250.0, 250.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor"); + // On the segment, away from the anchors and the bounding box's handles. + s.pointer(&PointerEvent::new(PointerKind::Down, 180.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for() { + // While the view moves, the canvas reads the last hover's decision: it does not carry over to + // another tool or another selection. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "nothing is selected now"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection"); + s.select_tool("rectangle", v).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), s.lent_tool_id(&cmd).unwrap(), "the new tool's lend"); +} + #[test] fn the_marks_follow_this_frames_pointer_with_cmd_held() { // The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index e136d9f45b..7365d00c34 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1032,6 +1032,26 @@ fn select_part_refuses_hidden_and_locked_objects_of_the_art() { s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1, 1]})).unwrap(); } +#[test] +fn a_cmd_click_with_the_selection_tool_keeps_the_instance_selected_whole() { + // Cmd lends Direct Selection the Selection tool: the press picks one object of a dynamic + // instance, and back with the Selection tool after the release, the instance stays selected, + // whole, as choosing the Selection tool leaves it. + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Mods::default() }; + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.doc().unwrap().selection.symbol_part.is_some(), "the lent tool picks the object"); + s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let sel = &s.doc().unwrap().selection; + assert_eq!((&sel.objects, &sel.symbol_part), (&vec![inst], &None)); +} + #[test] fn choosing_the_selection_tool_again_picks_the_instance_whole() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ba4f4089e4..d9c2e6e4dc 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,6 +10,14 @@ use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEv use crate::{EngineError, Prefs, Result, Session}; +/// What a hover's lend decision holds for ([`Session::hover_tool_at`]): the active document's uid +/// and revision, the active tool, the keys, the selection tools chosen last and the preferences a +/// press's hit test reads (Command Click to Select Objects Behind, Object Selection by Path Only, +/// Type Object Selection by Path Only, Selection Tolerance, anchor Size; Use Preview Bounds, +/// Measure Type by Glyph Bounds, Show Handles When Multiple Anchors Are Selected). +pub(crate) type HoverKey = + (Option<(u64, u64)>, &'static str, Mods, (Option<&'static str>, Option<&'static str>), ((bool, bool, bool, f64, u32), (bool, bool, bool))); + /// The tool whose radius is General › Corner Radius. const ROUNDED_RECTANGLE: &str = "roundedRectangle"; @@ -290,9 +298,9 @@ impl Session { /// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd /// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and /// the active tool is not computing an edit, else the active tool. Over a selected object where - /// a Cmd press selects behind, it still names the tool Cmd lends elsewhere. + /// a Cmd press selects behind, as the cursor last found it, it names the active tool. pub fn shown_tool_id(&self, mods: &Mods) -> &'static str { - match self.lent_tool_id(mods) { + match self.hovered_lent(mods) { Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id, _ => self.tool.id(), } @@ -303,13 +311,40 @@ impl Session { /// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas /// asks this while the view moves, when it does not hit-test the art under the pointer. pub fn hover_tool_id(&self, mods: &Mods) -> &'static str { - let lent = self.hover_lent.unwrap_or_else(|| self.lent_tool_id(mods)); - match lent { + match self.hovered_lent(mods) { Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id, _ => self.tool.id(), } } + /// The selection tool a Cmd press with `mods` would borrow at the pointer: the one + /// [`Self::hover_tool_at`] or [`Self::cursor`] last found, while the document, the selection, + /// the active tool and the keys are as they were then (none where the press selects behind), + /// else the one [`Self::lent_tool_id`] names. + fn hovered_lent(&self, mods: &Mods) -> Option<&'static str> { + match self.hover_lent { + Some((key, lent)) if key == self.hover_key(mods) => lent, + _ => self.lent_tool_id(mods), + } + } + + /// What a hover's lend decision holds for: the active document's state (its uid and revision, + /// which moves with the selection), the active tool, the keys, the selection tools chosen last + /// and the preferences a press's hit test reads. + fn hover_key(&self, mods: &Mods) -> HoverKey { + let p = &self.prefs; + let picks = + (p.ctrl_click_selects_behind, p.object_selection_by_path_only, p.type_selection_by_path_only, p.selection_tolerance, p.anchor_size); + let bounds = (p.use_preview_bounds, p.type_glyph_bounds, p.show_handles_multiple_anchors); + ( + self.active().map(|d| (d.uid, d.revision)), + self.tool.id(), + *mods, + (self.last_selection_tool, self.last_part_selection_tool), + (picks, bounds), + ) + } + /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the /// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the @@ -321,7 +356,8 @@ impl Session { Some(p) => self.lent_tool_at(p, mods, view), None => self.lent_tool_id(mods), }; - self.hover_lent = lends.then_some(lent); + let key = self.hover_key(mods); + self.hover_lent = lends.then_some((key, lent)); lent.unwrap_or(self.tool.id()) } @@ -1404,7 +1440,8 @@ impl Session { // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None }; - self.hover_lent = lends.then_some(lent); + let key = self.hover_key(&mods); + self.hover_lent = lends.then_some((key, lent)); let c = match lent { Some(id) => { let lent = self.make_tool(id); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 7b224e0717..e4a0d85829 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -444,7 +444,12 @@ fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usiz /// The segment of a selected blend's spine passing within `tol` of `p`: (blend, segment, t, whether /// it is straight). pub(crate) fn hit_spine_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { - selected_spines(cx).into_iter().find_map(|(id, path)| { + spine_segment_in(&selected_spines(cx), p, tol) +} + +/// [`hit_spine_segment`] over spines already built. +fn spine_segment_in(spines: &[(NodeId, PathData)], p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { + spines.iter().find_map(|&(id, ref path)| { let (si, seg, t, _, dist) = path.nearest(p)?; (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) }) @@ -597,21 +602,23 @@ fn hit_anchor(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, us }) } -/// Is `p` on a part of a selected object that Direct Selection edits: a gradient mesh point, a -/// blend's spine point or segment, an anchor, the end of a direction handle or a segment, within -/// the selection tolerance? A selected group or compound path counts through the editable paths -/// inside it. +/// Is `p` on a point of a selected object that Direct Selection edits: a gradient mesh point, a +/// blend's spine point or segment, an anchor or the end of a direction handle, within the +/// selection tolerance? A selected group or compound path counts through the editable paths +/// inside it. A path's segments do not count: a Cmd press there with Select Behind on selects +/// the object behind, which a stroke-only path can only be pressed on. pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { if cx.selection.objects.is_empty() { return false; } let tol = cx.point_tol(); let seg_tol = cx.pick_tol(); - if hit_handle(cx, p, tol).is_some() - || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() - || selected_spines(cx).iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) - || hit_spine_segment(cx, p, seg_tol).is_some() - { + if hit_handle(cx, p, tol).is_some() || MeshEdit::default().hit(cx, &cx.selection.objects, p).is_some() { + return true; + } + // The selected blends' spines are built once for both of their checks. + let spines = selected_spines(cx); + if spines.iter().any(|(_, path)| path.anchors().any(|(_, _, a)| a.p.distance(p) <= tol)) || spine_segment_in(&spines, p, seg_tol).is_some() { return true; } // The editable paths' control bounds are listed once per document state and selection; a @@ -630,13 +637,12 @@ pub fn over_selected_part(cx: &ToolContext, p: Point) -> bool { } v.into() }); - let reach = tol.max(seg_tol); boxes.iter().any(|&(id, b)| { - b.inflate(reach, reach).contains(p) + b.inflate(tol, tol).contains(p) && cx.doc.node(id).and_then(editable_path).is_some_and(|pd| { #[cfg(test)] MEASURED_PARTS.set(MEASURED_PARTS.get() + 1); - nearest_anchor(&pd, p, tol, None).is_some() || pd.nearest(p).is_some_and(|(.., d)| d <= seg_tol) + nearest_anchor(&pd, p, tol, None).is_some() }) }) } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 3cef62fab1..a9d5aab0c5 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2821,3 +2821,30 @@ fn over_selected_part_measures_only_the_paths_near_the_pointer() { let measured = MEASURED_PARTS.get() - before; assert!(measured < 10, "{measured} of 400 paths measured"); } + +/// The cursor, the canvas marks and a press each ask whether a Cmd press at the pointer selects +/// behind: while the document and the selection stay as they are, the selection's paths are +/// measured once for a point. +#[test] +fn select_behind_is_measured_once_for_a_point() { + use vectorcraft_doc::{Appearance, Node}; + let mut d = vectorcraft_doc::Document::new(400.0, 400.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let square = vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)); + d.insert(Some(l), 0, Node::path(id, square, Appearance::default_art())).unwrap(); + // Below it, an object to select behind. + let back = vectorcraft_geom::shapes::rectangle(Rect::new(50.0, 50.0, 250.0, 250.0)); + let back_id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(back_id, back, Appearance::default_art())).unwrap(); + let p = paint(); + let mut picked = Selection::default(); + picked.add(id); + let memo = crate::select::PreviewMemo::default(); + let c = ToolContext { preview_memo: Some(&memo), select_behind: true, ..cx(&d, &picked, &p) }; + let at = Point::new(150.0, 150.0); + let before = MEASURED_PARTS.get(); + assert!(crate::select::selects_behind_at(&c, at), "inside the selected square, away from its anchors"); + assert!(crate::select::selects_behind_at(&c, at)); + assert_eq!(MEASURED_PARTS.get() - before, 1, "measured for the first ask only"); +} diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 458ac68232..38040162aa 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -224,6 +224,11 @@ pub struct SelectionTool { /// Where the pointer was at the last press or drag: a widget drag released anywhere else is /// dragged there before it ends. held_at: Option, + /// Where the last press that selected the object behind (Cmd/Ctrl-click) was released: a + /// double-click there that follows it is that press clicked again, not a double-click that + /// isolates or edits. It holds the document's revision at the release too (None until then), + /// and an edit or a selection change after it ends it. + pressed_behind: Option<(Point, Option<(u64, u64)>)>, } /// What Distance Guides measure the selection to. @@ -513,20 +518,67 @@ struct MemoState { /// The measurements for one key; a slot holds `None` until it is measured. struct Measured { revision: (u64, u64), + /// The fonts, hyphenation exceptions and plug-ins live art is drawn and hit with + /// ([`vectorcraft_doc::hit::live_inputs`]). + live: u64, objects: Vec, measure: vectorcraft_effects::preview::Measure, bounds: Option>, oriented: Option>, by_object: HashMap>>, - /// [`painted_bounds`]. - painted: Option>, + /// [`painted_bounds`] in Preview and in Outline view. + painted: [Option>; 2], /// [`selected_part_boxes`]. part_boxes: Option>, + /// [`selection_holders`]. + holders: Option>>, + /// [`selects_behind_at`]'s last answer, with the point and settings it was for. + behind: Option<(BehindKey, bool)>, +} + +/// What [`selects_behind_at`] answers for besides the document and the selection: the point, the +/// tolerances (the zoom and the preferences) and the hit-test settings. +#[derive(Clone, Copy, PartialEq)] +struct BehindKey { + at: Point, + pick_tol: f64, + point_tol: f64, + scope: Option, + outline: bool, + path_only: bool, + type_path_only: bool, + skip_guides: bool, + handles_multiple: bool, + /// The zoom, which sets the mesh points' and the box handles' reach. + zoom: f64, + show_bbox: bool, +} + +impl BehindKey { + fn of(cx: &ToolContext, at: Point) -> Self { + let opt = cx.selection_hit_options(); + Self { + at, + pick_tol: cx.pick_tol(), + point_tol: cx.point_tol(), + scope: cx.isolation, + outline: opt.outline, + path_only: opt.path_only, + type_path_only: opt.type_path_only, + skip_guides: opt.skip_guides, + handles_multiple: cx.handles_multiple, + zoom: cx.zoom, + show_bbox: cx.show_bbox, + } + } } impl Measured { fn is_for(&self, cx: &ToolContext) -> bool { - self.revision == cx.revision && self.measure == cx.bounds_measure() && self.objects == cx.selection.objects + self.revision == cx.revision + && self.live == vectorcraft_doc::hit::live_inputs() + && self.measure == cx.bounds_measure() + && self.objects == cx.selection.objects } } @@ -548,13 +600,16 @@ impl PreviewMemo { st.checks += 1; let fresh = || Measured { revision: cx.revision, + live: vectorcraft_doc::hit::live_inputs(), objects: cx.selection.objects.clone(), measure: cx.bounds_measure(), bounds: None, oriented: None, by_object: HashMap::new(), - painted: None, + painted: [None, None], part_boxes: None, + holders: None, + behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { st.entry = Some(fresh()); @@ -569,10 +624,16 @@ impl PreviewMemo { { return v; } + let live = vectorcraft_doc::hit::live_inputs(); let v = measure(); + // Live inputs that changed while it measured leave the value unkept: only the entry for the + // inputs it was measured with takes it. if let Ok(mut st) = self.0.try_borrow_mut() { st.measurements += 1; - *slot(Self::current(&mut st, cx)) = Some(v.clone()); + let m = Self::current(&mut st, cx); + if m.live == live { + *slot(m) = Some(v.clone()); + } } v } @@ -600,10 +661,39 @@ pub fn selection_box(cx: &ToolContext) -> Option { remembered(cx, |m| &mut m.oriented, || vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, cx.bounds_measure())) } -/// The selection's visual bounds as drawn, its strokes and effects included, whatever Use Preview -/// Bounds says: every point where a hit test finds a selected object is inside them. +/// The bounds a hit test can find the objects in that a click selects for the selected art +/// ([`top_holder`]): their reach (a blend's spine included), their visual bounds as drawn +/// (strokes and effects included, whatever Use Preview Bounds says) and their geometric bounds +/// (where Outline view hits the paths), together, kept for each view mode. fn painted_bounds(cx: &ToolContext) -> Option { - remembered(cx, |m| &mut m.painted, || vectorcraft_effects::preview::bounds_of(cx.doc, &cx.selection.objects, true)) + let outline = cx.selection_hit_options().outline; + remembered( + cx, + |m| &mut m.painted[usize::from(outline)], + || { + let mut seen = std::collections::HashSet::new(); + let tops: Vec = cx.selection.objects.iter().map(|&id| top_holder(cx, id)).filter(|id| seen.insert(*id)).collect(); + // A layer or group above them with visible effects of its own that draw art (not raster + // effects, which a hit test leaves out, nor color adjustments) can draw (and hit) them + // anywhere. Outline view hits the paths where they are. + let moves_art = |e: &vectorcraft_doc::Effect| { + e.visible && !outline && !vectorcraft_effects::is_raster(&e.id) && !vectorcraft_effects::is_adjustment(&e.id) + }; + let above_has_effects = tops.iter().any(|id| { + cx.doc.ancestry(*id).is_some_and(|a| { + a.iter().take_while(|n| *n != id).any(|n| cx.doc.node(*n).is_some_and(|n| n.appearance.effects.iter().any(moves_art))) + }) + }); + if above_has_effects { + return Some(Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY)); + } + let symbols = cx.doc.symbol_boxes(); + let reach = tops.iter().filter_map(|id| cx.doc.node(*id)).filter_map(|n| n.reach_bounds_with(&symbols)); + let drawn = vectorcraft_effects::preview::bounds_of(cx.doc, &tops, true); + let geometric = vectorcraft_effects::preview::bounds_of(cx.doc, &tops, false); + reach.chain(drawn).chain(geometric).reduce(|a, b| a.union(b)) + }, + ) } /// `measure`'s list of the selected objects' editable paths with their control bounds, kept in the @@ -819,6 +909,25 @@ impl SelectionTool { } } + /// Each press, whatever takes it, starts with no Select Behind of its own, and the double-click + /// that follows one comes where that press is released, with the document as the release left + /// it, before the pointer moves away; a press that drags or is released away is not a click + /// ([`Self::pressed_behind`]). + fn note_pressed_behind(&mut self, cx: &ToolContext, ev: &PointerEvent) { + match ev.kind { + PointerKind::Down => self.pressed_behind = None, + PointerKind::Move | PointerKind::Drag => { + if self.pressed_behind.is_some_and(|(at, _)| at.distance(ev.pos) > cx.tol(1.0)) { + self.pressed_behind = None; + } + } + PointerKind::Up => { + self.pressed_behind = self.pressed_behind.filter(|(at, _)| at.distance(ev.pos) <= cx.tol(1.0)).map(|_| (ev.pos, Some(cx.revision))); + } + _ => {} + } + } + /// Notes where a press or a drag last held the pointer, and says whether a release lands /// somewhere else. fn note_held_at(&mut self, ev: &PointerEvent) -> bool { @@ -1080,10 +1189,16 @@ impl Tool for SelectionTool { } } + /// A press lent to another tool is not a Select Behind press of this tool. + fn press_elsewhere(&mut self) { + self.pressed_behind = None; + } + /// A press takes the selection's widgets, a ruler guide, a selected object's centre point or /// the art; the drags then move, scale, rotate, marquee or drag what it took. fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.note_loaded_at_press(ev.kind); + self.note_pressed_behind(cx, ev); let released_away = self.note_held_at(ev); let hovering = ev.kind == PointerKind::Move && matches!(self.state, State::Idle); self.bracket_hover = hovering.then_some(ev.pos); @@ -1146,6 +1261,7 @@ impl Tool for SelectionTool { { self.state = State::Moving { start: p, press: p, hold: p, grip: Grip::Point, began: false, deselect: None, key: None, exclude: None }; + self.pressed_behind = Some((p, None)); return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -1518,26 +1634,103 @@ impl Tool for SelectionTool { } } -/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and a -/// selected object under the pointer, away from the anchors, handles and segments Direct -/// Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the press to -/// Direct Selection or Group Selection. +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and an +/// object under the pointer selected or holding selected art (a group with a selected member), +/// with another object under the pointer too, away from the anchors, handles, mesh points and +/// spine Direct Selection edits ([`crate::direct::over_selected_part`])? Elsewhere Cmd lends the +/// press to Direct Selection or Group Selection. pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { + if !cx.select_behind { + return false; + } let tol = cx.pick_tol(); - // The selection's painted bounds come first: away from them, no document walk is needed. They - // take in a wide stroke's outer half, which the bounding box leaves out without Use Preview - // Bounds. - cx.select_behind - && painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) - && objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation).iter().any(|id| cx.selection.contains(*id)) - && !crate::direct::over_selected_part(cx, p) + // The answer is kept for the document and the selection as they are: the cursor, the canvas + // marks and a press at the same point ask again without walking the document again. + let key = BehindKey::of(cx, p); + if let Some(memo) = cx.preview_memo + && let Ok(mut st) = memo.0.try_borrow_mut() + && let Some((k, v)) = PreviewMemo::current(&mut st, cx).behind + && k == key + { + return v; + } + // The painted bounds of the objects holding the selection come first: away from them, no + // document walk is needed. They take in a wide stroke's outer half, which the bounding box + // leaves out without Use Preview Bounds, and a group's members that are not selected. With no + // other object under the pointer there is nothing to select behind: the press is lent. + // A shown bounding box's handles and rotate zones are not passed to Select Behind: the press + // there is lent. + let live = vectorcraft_doc::hit::live_inputs(); + let behind = painted_bounds(cx).is_some_and(|b| b.inflate(tol, tol).contains(p)) + && !shown_box(cx).is_some_and(|b| box_hit(cx, &b, p).is_some()) + && { + let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); + stack.len() > 1 && holds_selection(cx, &stack).is_some() + } + && !crate::direct::over_selected_part(cx, p); + if let Some(memo) = cx.preview_memo + && let Ok(mut st) = memo.0.try_borrow_mut() + { + st.measurements += 1; + // Only the entry for the live inputs it was found with keeps the answer. + let m = PreviewMemo::current(&mut st, cx); + if m.live == live { + m.behind = Some((key, behind)); + } + } + behind } -/// Select Behind: of the objects under `p` (topmost first), the one below the lowest selected -/// one, back to the topmost after the bottom one; the topmost when none is selected. +/// The index in `stack` (objects under the pointer, topmost first) of the lowest object that is +/// selected or holds selected art, such as a group with a member picked by Direct Selection or +/// Group Selection. +fn holds_selection(cx: &ToolContext, stack: &[NodeId]) -> Option { + let holders = selection_holders(cx); + stack.iter().rposition(|id| holders.contains(id)) +} + +/// The selected objects and every object that holds one (their groups and layers), kept in the +/// session's [`PreviewMemo`] while the document and the selection stay as they are. +fn selection_holders(cx: &ToolContext) -> std::sync::Arc> { + remembered( + cx, + |m| &mut m.holders, + || { + let set = cx.selection.objects.iter().flat_map(|&id| holder_chain(cx, id)).collect(); + std::sync::Arc::new(set) + }, + ) +} + +/// The selected object `id` and the objects holding it, outermost first, from the object a click +/// with the Selection tool selects for it ([`Hit::top_object`]): below its layers, the isolated +/// object and an envelope whose contents are edited. +fn holder_chain(cx: &ToolContext, id: NodeId) -> Vec { + let Some(a) = cx.doc.ancestry(id) else { return vec![id] }; + let isolated = cx.isolation.and_then(|s| a.iter().position(|n| *n == s)); + let contents = + a.iter().rposition(|n| cx.doc.node(*n).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Envelope { editing: true, .. }))); + // Below the isolated object or the envelope, the child holding `id` is the top object, a + // sublayer included; elsewhere layers and sublayers are skipped. + let chain: Vec = match isolated.max(contents) { + Some(i) => a.iter().skip(i + 1).copied().collect(), + None => a.iter().copied().skip_while(|n| cx.doc.node(*n).is_some_and(|n| n.is_layer())).collect(), + }; + if chain.is_empty() { vec![id] } else { chain } +} + +/// The object a click with the Selection tool selects for the selected object `id` +/// ([`holder_chain`]). +fn top_holder(cx: &ToolContext, id: NodeId) -> NodeId { + holder_chain(cx, id).first().copied().unwrap_or(id) +} + +/// Select Behind: of the objects under `p` (topmost first), the one below the lowest one that is +/// selected or holds selected art, back to the topmost after the bottom one; the topmost when +/// none is. fn object_behind(cx: &ToolContext, p: Point) -> Option { let stack = objects_at(cx.doc, p, cx.selection_hit_options(), cx.isolation); - let next = stack.iter().rposition(|id| cx.selection.contains(*id)).map_or(0, |i| i + 1); + let next = holds_selection(cx, &stack).map_or(0, |i| i + 1); stack.get(next).or(stack.first()).copied() } @@ -1853,6 +2046,14 @@ impl SelectionTool { fn double_click(&mut self, cx: &ToolContext, p: Point, m: Mods) -> Vec { self.state = State::Idle; + // Quick Cmd-clicks that select behind keep what the last one selected, before the widgets + // of that object answer, also when Cmd is let go before the release. Cmd+Shift on a guide + // still releases it. A double-click elsewhere, or after an edit or a selection change, is a + // double-click of its own. A press whose release has not come yet (both in one frame) + // still counts. + if self.pressed_behind.take().is_some_and(|(at, rev)| at.distance(p) <= cx.tol(1.0) && rev.is_none_or(|r| r == cx.revision)) { + return release_guide_at(cx, p, m).into_iter().collect(); + } // A threaded port: the thread breaks there. Any other port takes the double-click // too, so it neither edits the type nor isolates. if let Some((id, port)) = crate::text::port_at(cx, p) { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index cd375d0952..e44d7013d1 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1653,7 +1653,17 @@ pub(super) fn guide_labels(doc: &vectorcraft_doc::Document) -> std::collections: /// the pointer is not hit-tested again (#2452), and the last answer stays. fn marks_tool(app: &mut VectorcraftApp, ctx: &egui::Context, hover_still: bool, view: vectorcraft_engine::ViewInfo) -> &'static str { let held = held_mods(app, ctx); - if hover_still { app.session.hover_tool_at(app.hover_doc, &held, view) } else { app.session.hover_tool_id(&held) } + if !hover_still { + return app.session.hover_tool_id(&held); + } + let named = app.session.shown_tool_id(&held); + let tool = app.session.hover_tool_at(app.hover_doc, &held, view); + // The status bar and the help bar are drawn before the canvas: when the tool they name changes + // with this frame's pointer, they are drawn again. + if app.session.shown_tool_id(&held) != named { + ctx.request_repaint(); + } + tool } /// The selection's visuals and the tools' overlays, to be drawn. `tool` is the tool whose marks diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 508ccb03a0..21dd33b715 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7159,6 +7159,111 @@ fn blend_widgets_hide_while_cmd_lends_direct_selection() { assert_eq!(widgets(&mut app, egui::Modifiers::NONE), plain, "back when the key is let go"); } +/// One canvas frame with `modifiers` held and, when given, the pointer moved to `pointer` (in +/// screen points) → the shapes drawn, with the ones in shape lists listed one by one. +fn drawn_with(app: &mut VectorcraftApp, ctx: &egui::Context, modifiers: egui::Modifiers, pointer: Option) -> Vec { + app.canvas.selection_marks = Default::default(); + let mut events = vec![egui::Event::ModifiersChanged(modifiers)]; + events.extend(pointer.map(egui::Event::PointerMoved)); + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut drawn = vec![]; + for c in out.shapes { + match c.shape { + Shape::Vec(v) => drawn.extend(v), + s => drawn.push(s), + } + } + drawn +} + +/// The widgets only the Selection tool presses (a Shaper Group's mode widget, a mirror repeat's +/// axis, a grid or radial repeat's handles) hide while Cmd lends Direct Selection. +#[test] +fn selection_tool_widgets_hide_while_cmd_lends_direct_selection() { + let ctx = egui::Context::default(); + let count = |app: &mut VectorcraftApp, modifiers: egui::Modifiers, is_widget: &dyn Fn(&Shape) -> bool| { + drawn_with(app, &ctx, modifiers, None).iter().filter(|s| is_widget(s)).count() + }; + // Each widget that does not draw, hide or come back as it should. + let mut wrong = vec![]; + let mut check = |app: &mut VectorcraftApp, what: &str, is_widget: &dyn Fn(&Shape) -> bool| { + app.select_tool("selection"); + let plain = count(app, egui::Modifiers::NONE, is_widget); + let held = count(app, egui::Modifiers::COMMAND, is_widget); + let back = count(app, egui::Modifiers::NONE, is_widget); + if plain == 0 || held != 0 || back != plain { + wrong.push(format!("{what}: {plain} drawn, {held} with Cmd held, {back} after")); + } + }; + let new_app = || { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app + }; + let circle_of = |r: f32| move |s: &Shape| matches!(s, Shape::Circle(c) if c.radius == r); + + let mut app = new_app(); + for x in [0, 50] { + app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 100, "height": 100})).unwrap(); + } + app.run("shaper.scribble", json!({"points": [[25, 20], [75, 35], [30, 50], [125, 65]]})).unwrap(); + check(&mut app, "the Shaper Group's mode widget", &circle_of(vectorcraft_tools::shaperwidget::RADIUS_PX)); + + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 80})).unwrap(); + app.run("object.repeat.mirror", json!({})).unwrap(); + let selection = Tokens::get(&ctx).selection; + check( + &mut app, + "the mirror axis", + &move |s: &Shape| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == selection && stroke.width == 2.0), + ); + + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.grid", json!({"hSpacing": 10, "vSpacing": 10})).unwrap(); + check(&mut app, "the grid repeat's handles", &circle_of(vectorcraft_tools::repeat_grid::HANDLE_RADIUS)); + + let mut app = new_app(); + app.run("shape.rectangle", json!({"x": 180, "y": 40, "width": 40, "height": 40})).unwrap(); + app.run("object.repeat.radial", json!({"instances": 6, "radius": 60})).unwrap(); + check(&mut app, "the radial repeat's handles", &circle_of(vectorcraft_tools::repeat_radial::HANDLE_RADIUS)); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + +/// The canvas decides which tool's widgets to draw for the pointer where it is in the same frame: +/// over the selected blend a Cmd press selects behind, so the Selection tool's blend widgets stay; +/// moved away in the next frame, where Cmd lends Direct Selection, they hide in that frame. +#[test] +fn the_widgets_follow_the_pointer_in_the_frame_it_moves() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + // Behind the blend, an object to select behind. + app.session.execute("shape.rectangle", &json!({"x": 20, "y": 120, "width": 360, "height": 160})).unwrap(); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 60, "y": 160, "width": 80, "height": 80})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 260, "y": 160, "width": 80, "height": 80})).unwrap()); + app.session.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let blend = id(app.session.execute("object.blend.make", &json!({})).unwrap()); + app.select_tool("selection"); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); + let ctx = egui::Context::default(); + let r = vectorcraft_tools::blendwidget::RADIUS_PX; + let widgets = |app: &mut VectorcraftApp, modifiers: egui::Modifiers, at: Option| { + let pointer = at.map(|p| Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(p)); + drawn_with(app, &ctx, modifiers, pointer).iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == r)).count() + }; + let plain = widgets(&mut app, egui::Modifiers::NONE, None); + assert!(plain >= 2, "the Appearance and Easing widgets: {plain}"); + // Inside the first key object, away from its anchors and the spine. + let over = widgets(&mut app, egui::Modifiers::COMMAND, Some(Point::new(80.0, 175.0))); + assert_eq!(over, plain, "over the selected blend, the press selects behind"); + let away = widgets(&mut app, egui::Modifiers::COMMAND, Some(Point::new(200.0, 380.0))); + assert!(away + 2 <= plain, "away from it, hidden in the same frame: {away} of {plain}"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 58c13dbe9b..3727b6c798 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -96,7 +96,7 @@ the two can still win that race. | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | -| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool, and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object away from its anchors, handles and segments while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | +| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick\|tripleclick, x, y, space?: "doc"\|"screen", mods?}]}` | drive the active tool exactly like the mouse (`doubleclick` follows the second click's `up`, and `tripleclick` the third's): `mods.cmd` held at a press with any tool but a selection tool drags with the selection tool chosen last (Direct Selection with the Pen until one is); with Direct Selection or Group Selection it drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection), and with the Selection tool it drags with Direct Selection or Group Selection, whichever was chosen last, except on a selected object (or a group holding a selected member) with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones while `ctrlClickSelectsBehind` is on, where the press selects the object behind; the release gives the tool back as it was; the reply lists `selection`, `key` (the key object, null without one) and `tool`. With the Shape Builder or the Live Paint Bucket and a selection of more than 128 segments, the app finds the regions off the UI thread, so a `move` replies before the region under the pointer is highlighted, and the highlight shows in the first frame after the regions are found. With the Shape Builder and such a selection, the app also merges off the UI thread: the reply to the events that end a click or drag comes once the merge is applied. A click or drag made before the regions are found does not wait for them; the app records it and makes it once they are found. Until then the canvas keeps drawing, with the touched regions highlighted and the busy pointer. A click or drag sent meanwhile, with `mods.cmd` too, and the Shape Builder's arrow keys are made after the merge in the order sent, and the reply to such a request comes once its events are made and any merge they start is applied; a request of `move` events alone is answered at once. A command that can edit, select, save or redraw the documents (an edit, an undo, a selection, a save or an export, a tool option, another tool, another document, closing, a dialog's preview, a menu item, a command of the app's own such as `ui.recolorDialog`, the proof and separations views, a preference, added fonts) waits for the merge and the input sent before it, and runs after them; queries that only read, such as `document.inspect`, run at once on the document before the merge | | `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | synthetic keyboard input | | `ui.move` | `{x, y}` | screen-point pointer move | | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..4f3c98abb7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7080,7 +7080,14 @@ there too and a `brush.freehand` call does not change the path's brush or the se A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing -the path it had begun while that stays selected. Its reply's `tool` is the tool given back. +the path it had begun while that stays selected. With Direct Selection or Group Selection, `mods.cmd` drags with the +Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection). With the Selection tool, it drags +with Direct Selection or Group Selection, whichever was chosen last +(Direct Selection until one is), except where the press lands on a selected object, or on a group holding a selected +member, with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and +the bounding box's handles and rotate zones, while `ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the +object behind. A double-click or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went +to, and one that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool given back. `tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..817e79d3ac 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1523,7 +1523,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. + - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f9f140fc76..8fdb42793c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -366,7 +366,7 @@ tools, never checked side by side) isn't captured row by row. | Space: Hand; Cmd+Space / Cmd+Alt+Space: zoom in/out; middle button pans | done | Space pressed after a tool takes a drag keeps the view still and shows that tool's cursor. Shape and anchor tools may use Space to move the geometry being drawn. Cmd+Space pressed mid-drag likewise keeps the active tool cursor. Space held before a press starts a view gesture, and its view cursor returns after release. `space_during_a_pencil_drag_keeps_the_pencil_cursor`, `cmd_space_mid_tool_drag_keeps_the_active_tool_cursor` | | Document window scroll bars along the right and bottom edges (Normal and Full Screen Mode with Menu Bar; none in Full Screen and Presentation Mode): a thumb as long as the view against the art and the artboards; dragging it scrolls, a click on the track pages, the wheel over a bar scrolls along it; in a rotated view they follow the screen's axes | partial | #2322. The span is the art and the artboards with half a window around them, not Illustrator's 227 in canvas: VectorCraft has no bounded drawing area (#2284). A track click pages rather than jumping to the click; the page size and the rotated-view behaviour are our own choice (the public documentation gives neither) | | A tool drag held near an edge of the canvas scrolls the view (#8551): zoomed in, a selection moved, a shape drawn or a marquee dragged towards the panels goes on past what shows | partial | Within 24 points of the canvas edge, once the pointer has moved 3 points from the press, the view scrolls away from that edge, faster nearer it (up to 900 points a second at the edge, and no faster in a corner, where it scrolls both ways), and keeps scrolling while the pointer stays still; the tool gets the pointer's new place in the document, so moved art stays under the pointer. Back away from the edge it stops. A click near the edge, the Hand, Zoom and Rotate View drags and Space panning do not scroll. The pointer past the canvas edge does not scroll: over a panel the Selection tools hand the art to the panels (#2826). The zone and speeds are VectorCraft's own (the public documentation gives none). Tests: `canvas::tests_edge_scroll` | -| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, away from its anchors, handles and segments, still selects the object behind it while Command Click to Select Objects Behind is on; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool it lends ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Work with selections"); engine pointer and canvas regressions | +| Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); Cmd lends Group Selection the Selection tool, and the Selection tool Direct Selection or Group Selection, whichever was chosen last, except that a Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, still selects the object behind it while Command Click to Select Objects Behind is on, so repeated Cmd-clicks select behind as "Select behind an object" (Ctrl+click twice, Command+click twice on macOS) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists; Cmd pressed once a drag is under way lends nothing; while Cmd is held, the status bar's Current Tool and the help bar name the tool a press at the pointer takes; engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | | Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | From 210fc900d54009ee744dc11901b5a2eb9fa3dca7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:47:10 -0800 Subject: [PATCH 3/6] Tests: Cmd on a lone object and under a layer effect Adds tests for two Select Behind rules: a Cmd press on a selected object with nothing behind it is lent to Direct Selection, and a layer effect that moves the art moves where a Cmd press selects behind, in Preview after Outline view too, while a drop shadow is not hit. The hover's lend decision key is a named struct. The pointer_gesture paragraph in docs/mcp.md is wrapped to the file's width, and the Temporary tools line in docs/target-app-parity.md cites the default keyboard shortcuts page. --- crates/engine/src/tests/draw2.rs | 53 ++++++++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 49 +++++++++++++++++++---------- docs/mcp.md | 13 ++++---- docs/target-app-parity.md | 2 +- 4 files changed, 93 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 3ffd8e4576..c497fed246 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4843,6 +4843,59 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); } +#[test] +fn a_cmd_press_on_a_lone_selected_object_is_lent() { + // With nothing behind the selected object, there is nothing to select behind: Direct Selection + // takes the press. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() { + // A layer effect draws the selected object 250 pt to the right of its path, over the object + // behind it: a Cmd press where it is drawn selects behind. A drop shadow there is not hit, so + // the press is lent. Outline view hits the path where it is, and Preview afterwards still finds + // the moved art. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let outline = ViewInfo { outline: true, ..view() }; + let drawn = Point::new(450.0, 200.0); + // On both rectangles' top edges, which Outline view hits, away from the box's handles. + let path = Point::new(170.0, 150.0); + for effect in ["distort.transform", "stylize.dropShadow"] { + let mut s = session(); + let back = rect(&mut s, 50.0, 150.0, 700.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + let layer = s.doc().unwrap().doc.layers[0].id; + let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) }; + s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The back rectangle is drawn moved too, so it is under both points. + if effect == "distort.transform" { + assert_eq!(s.hover_tool_at(Some(path), &cmd, outline), "selection", "Outline view: on the path"); + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "selection", "Preview: where the effect draws it"); + s.pointer(&PointerEvent::new(PointerKind::Down, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + } else { + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "directSelection", "on the shadow"); + } + } +} + #[test] fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { // The first Cmd-click on an unselected group lends Direct Selection, which selects the path diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index d9c2e6e4dc..736b99617a 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,13 +10,24 @@ use vectorcraft_tools::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEv use crate::{EngineError, Prefs, Result, Session}; -/// What a hover's lend decision holds for ([`Session::hover_tool_at`]): the active document's uid -/// and revision, the active tool, the keys, the selection tools chosen last and the preferences a -/// press's hit test reads (Command Click to Select Objects Behind, Object Selection by Path Only, -/// Type Object Selection by Path Only, Selection Tolerance, anchor Size; Use Preview Bounds, -/// Measure Type by Glyph Bounds, Show Handles When Multiple Anchors Are Selected). -pub(crate) type HoverKey = - (Option<(u64, u64)>, &'static str, Mods, (Option<&'static str>, Option<&'static str>), ((bool, bool, bool, f64, u32), (bool, bool, bool))); +/// What a hover's lend decision holds for ([`Session::hover_tool_at`]). +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct HoverKey { + /// The active document's uid and revision, which moves with the selection. + doc: Option<(u64, u64)>, + tool: &'static str, + mods: Mods, + /// The selection tool and the part selection tool chosen last. + last_tools: (Option<&'static str>, Option<&'static str>), + ctrl_click_selects_behind: bool, + object_selection_by_path_only: bool, + type_selection_by_path_only: bool, + selection_tolerance: f64, + anchor_size: u32, + use_preview_bounds: bool, + type_glyph_bounds: bool, + show_handles_multiple_anchors: bool, +} /// The tool whose radius is General › Corner Radius. const ROUNDED_RECTANGLE: &str = "roundedRectangle"; @@ -333,16 +344,20 @@ impl Session { /// and the preferences a press's hit test reads. fn hover_key(&self, mods: &Mods) -> HoverKey { let p = &self.prefs; - let picks = - (p.ctrl_click_selects_behind, p.object_selection_by_path_only, p.type_selection_by_path_only, p.selection_tolerance, p.anchor_size); - let bounds = (p.use_preview_bounds, p.type_glyph_bounds, p.show_handles_multiple_anchors); - ( - self.active().map(|d| (d.uid, d.revision)), - self.tool.id(), - *mods, - (self.last_selection_tool, self.last_part_selection_tool), - (picks, bounds), - ) + HoverKey { + doc: self.active().map(|d| (d.uid, d.revision)), + tool: self.tool.id(), + mods: *mods, + last_tools: (self.last_selection_tool, self.last_part_selection_tool), + ctrl_click_selects_behind: p.ctrl_click_selects_behind, + object_selection_by_path_only: p.object_selection_by_path_only, + type_selection_by_path_only: p.type_selection_by_path_only, + selection_tolerance: p.selection_tolerance, + anchor_size: p.anchor_size, + use_preview_bounds: p.use_preview_bounds, + type_glyph_bounds: p.type_glyph_bounds, + show_handles_multiple_anchors: p.show_handles_multiple_anchors, + } } /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the diff --git a/docs/mcp.md b/docs/mcp.md index 4f3c98abb7..afa53faaa8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7082,12 +7082,13 @@ macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool` Curvature and anchor tools until one is chosen; the release gives the tool back as it was, so the Pen goes on drawing the path it had begun while that stays selected. With Direct Selection or Group Selection, `mods.cmd` drags with the Selection tool (with Direct Selection and `mods.alt` held too, with Group Selection). With the Selection tool, it drags -with Direct Selection or Group Selection, whichever was chosen last -(Direct Selection until one is), except where the press lands on a selected object, or on a group holding a selected -member, with another object under the pointer, away from its anchors, direction handles, mesh points, blend spine and -the bounding box's handles and rotate zones, while `ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the -object behind. A double-click or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went -to, and one that follows a Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool given back. +with Direct Selection or Group Selection, whichever was chosen last (Direct Selection until one is), except where the +press lands on a selected object, or on a group holding a selected member, with another object under the pointer, away +from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, while +`ctrlClickSelectsBehind` is on: there the Selection tool keeps the press and selects the object behind. A double-click +or triple-click made with Cmd still held after Cmd-clicks goes to the tool the clicks went to, and one that follows a +Cmd-click selecting behind keeps what that click selected, without isolating or editing. Its reply's `tool` is the tool +given back. `tool.selectLastSelection` (Select Last Selection Tool, `{}`) chooses the selection tool chosen last, as Ctrl+` does on Windows and Linux ([the help page](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 817e79d3ac..f70d0f6c0f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1523,7 +1523,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Composition's leading-space reduction stays along the line when a character rotates. An opening bracket trimmed by Line-end Punctuation Half Width Mojikumi keeps that placement under Character Rotation; its turning point follows the composition adjustment, and removing the rotation keeps the trim. Scores and estimates are unchanged. A character rotated near or at a quarter turn follows a Touch Type drag across its line as well as along it: baseline shift moves a character up from its line at any rotation, and the character turns about its shifted pen position. Right-to-left characters can also move along their line when a preceding logical character is on that line. Positive `text.touchType` `dx` follows reading order, toward the left in horizontal right-to-left text; the first logical character still moves only up and down. These direction rules are VectorCraft's choices; the public Touch Type page describes moving a character without specifying this case. Scores and estimates are unchanged. - - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. + - **Temporary tools:** Cmd with any other tool drags with the selection tool used last (Selection, Direct Selection or Group Selection). With the Selection tool, Cmd lends Direct Selection or Group Selection, whichever was chosen last, until the key is released; with Group Selection it lends the Selection tool. A Cmd press on a selected object, or on a group holding a selected member, with another object under the pointer and away from its anchors, direction handles, mesh points, blend spine and the bounding box's handles and rotate zones, keeps Select Behind while Command Click to Select Objects Behind is on, as "Select behind an object" (Ctrl+click twice) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists (#5970, #6583). Held Space pans and Cmd+Space zooms (Cmd+Alt+Space out) whatever the tool. A single-key tool shortcut held for 0.25 s or more, or held while its tool is used, chooses that tool only until the key is let go, and the tool active before comes back (after a drag in progress ends); a quicker press chooses the tool for good. This is VectorCraft's own rule and its own threshold, and General › Hold a Tool Shortcut to Use the Tool Temporarily (`holdToolKeys`, on by default) turns it off. Space held while the Zoom tool drags a marquee moves the marquee and keeps its size ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). When Space is let go, the drag sizes the marquee again from where it moved to. A Space+Shift drag rotates the view whatever the tool, as a Rotate View tool drag does, and Shift does not round the angle to 15°. While the Type tool edits text, Space types a space: held, it does not show the hand, pan or rotate the view, and Cmd+Space still zooms ([the help page](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) lists the Spacebar as the Hand tool when not in text-edit mode). Test: `canvas::tests::space_types_a_space_while_editing_text_and_does_not_pan`. From cfbb1cdf67c30d6d1fb52ea40fac66cbd01d9573 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:40:07 -0800 Subject: [PATCH 4/6] Selection: pie widgets hide while Cmd lends Direct Selection With a shape tool active and Direct Selection chosen last, Cmd held lends Direct Selection, which does not press a live ellipse's pie widgets. The canvas now draws them for a shape tool only while that tool is the one shown, as the bounding box already does. --- crates/ui-egui/src/canvas/overlays.rs | 8 ++++---- crates/ui-egui/src/canvas/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 02318ad688..b79206662d 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -276,10 +276,10 @@ pub(super) fn selection_overlay( p.add(Shape::convex_polygon(diamond, Color32::WHITE, Stroke::new(1.0, color))); } } - // Pie widgets (Selection tool, with View › Show Bounding Box and Show Shape Widgets, on live - // ellipses): each joined by a line to the outline's point at its angle. They stay while one is - // dragged. - if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box && shape_widgets { + // Pie widgets (Selection tool and the shape tools while no other tool is lent, with View › Show + // Bounding Box and Show Shape Widgets, on live ellipses): each joined by a line to the outline's + // point at its angle. They stay while one is dragged. + if (tool == "selection" || (shape_tool && own && !drawing)) && app.ui.view.bounding_box && shape_widgets { for w in vectorcraft_tools::pie::PieWidget::of(&st.doc, &st.selection, xf.zoom) { let (on, c, r, color) = (xf.to_screen(w.on), xf.to_screen(w.at), vectorcraft_tools::pie::RADIUS_PX, c32(st.doc.layer_color(w.id))); p.line_segment([on, c], Stroke::new(1.0, color)); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 21dd33b715..963bbc3289 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -7264,6 +7264,27 @@ fn the_widgets_follow_the_pointer_in_the_frame_it_moves() { assert!(away + 2 <= plain, "away from it, hidden in the same frame: {away} of {plain}"); } +/// With a shape tool, Cmd held lends the selection tool chosen last; when that is Direct +/// Selection, which does not press them, a selected live ellipse's pie widgets hide while the key +/// is down. +#[test] +fn pie_widgets_hide_while_cmd_lends_direct_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 100})).unwrap(); + app.session.execute("object.setLiveShape", &json!({"pieStart": 0, "pieEnd": 90})).unwrap(); + app.select_tool("directSelection"); + app.select_tool("ellipse"); + let ctx = egui::Context::default(); + let r = vectorcraft_tools::pie::RADIUS_PX; + let widgets = |app: &mut VectorcraftApp, modifiers: egui::Modifiers| { + drawn_with(app, &ctx, modifiers, None).iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == r && c.fill == Color32::WHITE)).count() + }; + assert_eq!(widgets(&mut app, egui::Modifiers::NONE), 2, "the Ellipse tool shows them"); + assert_eq!(widgets(&mut app, egui::Modifiers::COMMAND), 0, "hidden while Cmd lends Direct Selection"); + assert_eq!(widgets(&mut app, egui::Modifiers::NONE), 2, "back when the key is let go"); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] From 2592dde6c8076582520249b4f0993f5b3e092e33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:07:03 -0800 Subject: [PATCH 5/6] Selection: a Cmd double-click after a tool switch is the new tool's The double-click or triple-click that follows a lent Cmd-click went to the tool lent to that press even after another tool or document was chosen. The lent tool is now kept with the document and the tool it was lent from, and a follow-up in another document or after a tool switch goes to the active tool. --- crates/engine/src/lib.rs | 6 ++++-- crates/engine/src/tests/draw2.rs | 26 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 12 +++++++++--- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index bbcba38fff..244da31e5d 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -110,8 +110,10 @@ pub struct Session { /// Selection tool. None until one is chosen. pub(crate) last_part_selection_tool: Option<&'static str>, /// The selection tool Cmd lent the last press, which also takes the double-click or - /// triple-click that follows it. None when the press was not lent. - pub(crate) press_lent: Option<&'static str>, + /// triple-click that follows it, with the uid of the document and the id of the tool it was + /// lent from: a follow-up in another document or after a tool switch is not lent. None when + /// the press was not lent. + pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with /// the document state, active tool and keys it was found for. None when it was last asked diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index c497fed246..740b99f42a 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4775,6 +4775,32 @@ fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() { assert!(s.doc().unwrap().isolation.is_some()); } +#[test] +fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() { + // With the Selection tool, a Cmd-click on type goes to Direct Selection, and so does the + // Cmd double-click after it, which edits the type. Once another tool is chosen, the + // double-click is that tool's: Group Selection's does not edit the type. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 200, "size": 48, "text": "Type"})).unwrap()["id"].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().center(); + let clicks = |s: &mut Session, then: Option<&str>| { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, c.x, c.y).with_mods(cmd), v).unwrap(); + } + if let Some(tool) = then { + s.select_tool(tool, v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y).with_mods(cmd), v).unwrap() + }; + assert_eq!(clicks(&mut s, None), [UiRequest::SwitchTool("type".into())], "Direct Selection's double-click edits the type"); + assert_eq!(clicks(&mut s, Some("groupSelection")), [], "Group Selection's double-click does not"); + assert_eq!(s.tool_id(), "groupSelection"); +} + #[test] fn a_cmd_press_on_a_selected_object_keeps_select_behind() { // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 736b99617a..b023ca1f7f 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -406,11 +406,17 @@ impl Session { if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() { return Ok((*ev, vec![])); } - // A follow-up goes where the press before it went, whatever that press selected. - let id = if follow_up { self.press_lent } else { self.lent_tool_at(ev.pos, &ev.mods, view) }; + // A follow-up goes where the press before it went, whatever that press selected, while the + // document and the active tool are the ones that press found. + let at = (self.active().map(|d| d.uid), self.tool.id()); + let id = if follow_up { + self.press_lent.filter(|(doc, tool, _)| (*doc, *tool) == at).map(|(.., id)| id) + } else { + self.lent_tool_at(ev.pos, &ev.mods, view) + }; let Some(id) = id else { return Ok((*ev, vec![])) }; if !follow_up { - self.press_lent = Some(id); + self.press_lent = Some((at.0, at.1, id)); } // Typing in progress is kept as its own step first: the lent tool's drag previews from the // document its interaction started from, which would drop the typing (#1881). When it From ece910a3b72fb8477f7c74756459941fa7f9b2d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:45:24 -0800 Subject: [PATCH 6/6] Selection: a Cmd double-click after switching back is the active tool's A switch from the Selection tool to another tool and back kept the record of the selection tool Cmd lent the last press, so the Cmd double-click that followed still went to Direct Selection. The record is now cleared whenever the active tool changes and whenever the tool starts afresh (a switch to another document or another view of it). --- crates/engine/src/lib.rs | 4 ++-- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/draw2.rs | 30 ++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 3 +++ 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 244da31e5d..b213394c0c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -111,8 +111,8 @@ pub struct Session { pub(crate) last_part_selection_tool: Option<&'static str>, /// The selection tool Cmd lent the last press, which also takes the double-click or /// triple-click that follows it, with the uid of the document and the id of the tool it was - /// lent from: a follow-up in another document or after a tool switch is not lent. None when - /// the press was not lent. + /// lent from: a follow-up in another document, after a tool switch (also one back to the same + /// tool) or after the tool starts afresh is not lent. None when the press was not lent. pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7930095b6e..e800a9c572 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -209,6 +209,7 @@ impl Session { return; } self.press_type_selection = None; + self.press_lent = None; let view = self.last_view; // The edit the tool computes on another thread and the input held for it belong to the // document being left. The switch goes on whatever they did, as for the deactivation. diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 740b99f42a..34254b3513 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -4801,6 +4801,36 @@ fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() { assert_eq!(s.tool_id(), "groupSelection"); } +#[test] +fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() { + // A Cmd-click with the Selection tool goes to Direct Selection. After a switch to another tool + // and back to the Selection tool, or a fresh start of the tool (another view of the document), + // the Cmd double-click is the Selection tool's: it isolates the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + for reset in [false, true] { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + if reset { + s.reset_tool(); + } else { + s.select_tool("rectangle", v).unwrap(); + s.select_tool("selection", v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + assert!(s.doc().unwrap().isolation.is_some(), "the Selection tool's double-click isolates the group (reset: {reset})"); + s.execute("object.exitIsolation", &json!({})).unwrap(); + } +} + #[test] fn a_cmd_press_on_a_selected_object_keeps_select_behind() { // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index b023ca1f7f..761c9af469 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -198,6 +198,9 @@ impl Session { if self.tool.id() == id { return Ok(()); } + // A double-click or triple-click after the switch is the new tool's, also when the switch + // comes back to the tool a Cmd press was lent from. + self.press_lent = None; // Sampling type keeps its highlighted characters as the target, and a whole story that // Select All selected. Capture before the Type tool deactivates (which commits typing and // clears its editing state).