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` |