diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6d5cb0f1a5..1a6ca42642 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -731,6 +731,152 @@ fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: O tops } +/// The most hits [`leaves_at`] lists. +pub const MAX_LEAVES_AT: usize = 256; + +/// The hits under `p`, topmost first, at most [`MAX_LEAVES_AT`]: one for each object a click with +/// Direct Selection picks there (a path, a compound path or an image, also inside a group), each +/// found by a hit test ([`hit_test`]) that passes over the ones found before it. In isolation mode +/// (`opt.scope`) only what is inside the isolated group or object is hit. Cmd/Ctrl-clicks with the +/// Selection tool step through them (Select Behind). +pub fn leaves_at(doc: &Document, p: Point, opt: HitOptions) -> Vec { + let _walk = ArtWalk::open(); + // A clipping mask, or a group drawn with its own geometry effects, hits by rules the single + // traversal leaves to the hit test: the repeated hit test finds the rest, after the hits found + // above them, which the art walked for them already counted against. + leaves_at_once(doc, p, opt).unwrap_or_else(|above| leaves_at_repeated_after(doc, p, opt, above)) +} + +/// [`leaves_at`] by repeated hit tests, each passing over the objects found before it. +#[cfg(test)] +fn leaves_at_repeated(doc: &Document, p: Point, opt: HitOptions) -> Vec { + leaves_at_repeated_after(doc, p, opt, vec![]) +} + +/// [`leaves_at`] by repeated hit tests after `hits`, the topmost hits already found. +fn leaves_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, mut hits: Vec) -> Vec { + let mut found: HashSet = hits.iter().map(|h| h.leaf).collect(); + while hits.len() < MAX_LEAVES_AT + && let Some(h) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true) + { + if !found.insert(h.leaf) { + break; + } + hits.push(h); + } + hits +} + +/// [`leaves_at`] in one traversal of the document, in the order repeated hit tests +/// ([`hit_test_skipping`]) find them. `Err` with the hits found above it when a container under +/// `p` clips or draws its art with its own geometry effects ([`leaves_in`]). +fn leaves_at_once(doc: &Document, p: Point, opt: HitOptions) -> Result, Vec> { + let finish = |mut h: Hit| { + h.contents_of = h.ancestry.iter().rev().copied().find(|a| doc.node(*a).is_some_and(edits_contents)); + h.layers = h.ancestry.iter().take_while(|a| doc.node(**a).is_some_and(Node::is_layer)).count(); + h + }; + let locks = doc.locked_artboards_kept(); + let on_locked = |id: NodeId| { + !locks.is_empty() && doc.parent_of(id).and_then(|l| doc.node(l)).is_some_and(Node::is_layer) && doc.node(id).is_some_and(|n| locks.holds(n)) + }; + let symbols = doc.kept_symbol_boxes().keeping(&locks.symbols); + let mut hits = Vec::new(); + if let Some(scope) = opt.scope + && let Some(isolated) = doc.node(scope) + && let Some(mut chain) = doc.ancestry(scope) + { + if !doc.is_editable_with(&locks, scope) { + return Ok(hits); + } + let whole = if isolated.is_container() { + leaves_in(isolated, p, opt, &symbols, &on_locked, &mut chain, &mut hits) + } else { + // A single object isolated: only it hits, among its siblings. + chain.pop(); + let Some(parent) = chain.last().and_then(|id| doc.node(*id)) else { return Ok(hits) }; + leaves_in(parent, p, opt, &symbols, &|id| id != scope || on_locked(id), &mut chain, &mut hits) + }; + let hits = hits.into_iter().map(finish).collect(); + return if whole { Ok(hits) } else { Err(hits) }; + } + let mut chain = Vec::new(); + for layer in doc.layers.iter().rev() { + if !layer.visible || layer.locked || layer.is_template() || doc.pattern_edit.as_ref().is_some_and(|e| e.layer != layer.id) { + continue; + } + chain.push(layer.id); + let opt = if !opt.ignore_layer_preview && previews_off(layer) { HitOptions { outline: true, ..opt } } else { opt }; + if !leaves_in(layer, p, opt, &symbols, &on_locked, &mut chain, &mut hits) { + return Err(hits.into_iter().map(finish).collect()); + } + chain.pop(); + if hits.len() >= MAX_LEAVES_AT { + break; + } + } + Ok(hits.into_iter().map(finish).collect()) +} + +/// Every editable hit under `p` in `parent`, topmost first, added to `hits` up to +/// [`MAX_LEAVES_AT`]: what [`hit_children`] finds first, then what it finds passing over each hit +/// found before. `false` when `parent` or a container in it under `p` clips or draws its art with +/// its own geometry effects, which [`hit_children`] hits by rules of their own. +fn leaves_in( + parent: &Node, + p: Point, + opt: HitOptions, + symbols: &SymbolBoxes, + skip: &dyn Fn(NodeId) -> bool, + chain: &mut Vec, + hits: &mut Vec, +) -> bool { + let Some(children) = parent.children() else { return true }; + if parent.clips() || drawn_art(symbols, parent, opt.outline).is_some() { + return false; + } + for i in hit_order(parent, children, p) { + if hits.len() >= MAX_LEAVES_AT { + return true; + } + let Some(c) = children.get(i) else { continue }; + if !may_hit(parent, i, c, p, opt, symbols, true) || skip(c.id) { + continue; + } + chain.push(c.id); + let leaf = |hits: &mut Vec, chain: &[NodeId]| { + if let Some(kind) = hit_leaf(c, p, opt, symbols) { + hits.push(Hit { leaf: c.id, ancestry: chain.to_vec(), kind, contents_of: None, layers: 1 }); + } + }; + let whole = match &c.kind { + NodeKind::Layer { preview: false, .. } if !opt.ignore_layer_preview => { + leaves_in(c, p, HitOptions { outline: true, ..opt }, symbols, skip, chain, hits) + } + NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. } | NodeKind::Envelope { editing: true, .. } => { + leaves_in(c, p, opt, symbols, skip, chain, hits) + } + // A blend's key objects first; its steps hit as the blend. + NodeKind::Blend { .. } => { + let whole = leaves_in(c, p, opt, symbols, skip, chain, hits); + if whole && hits.len() < MAX_LEAVES_AT { + leaf(hits, chain); + } + whole + } + _ => { + leaf(hits, chain); + true + } + }; + chain.pop(); + if !whole { + return false; + } + } + true +} + /// The most objects [`locked_objects_at`] lists. pub const MAX_LOCKED_AT: usize = 20; diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index a16b3ad149..071138d0de 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1992,10 +1992,58 @@ fn objects_at_matches_repeated_hits_on_random_documents() { let p = Point::new(f64::from(next(120)), f64::from(next(120))); let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; assert_eq!(objects_at(&d, p, opt, None), objects_at_repeated(&d, p, opt, None), "round {round}, {p:?}, {opt:?}"); + assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "leaves: round {round}, {p:?}, {opt:?}"); + // Isolated in a group of the document, now and then. + let groups: Vec = + d.layers[0].children().into_iter().flatten().filter(|n| n.is_container() && !n.is_layer()).map(|n| n.id).collect(); + if let Some(&g) = groups.first().filter(|_| next(3) == 0) { + let opt = HitOptions { scope: Some(g), ..opt }; + assert_eq!(leaf_chains(leaves_at(&d, p, opt)), leaf_chains(leaves_at_repeated(&d, p, opt)), "isolated: round {round}, {p:?}"); + } } } } +/// A hit's leaf, ancestry, kind, layer count and edited envelope. +type LeafChain = (NodeId, Vec, HitKind, usize, Option); + +/// Each hit's [`LeafChain`], to compare two lists. +fn leaf_chains(hits: Vec) -> Vec { + hits.into_iter().map(|h| (h.leaf, h.ancestry, h.kind, h.layers, h.contents_of)).collect() +} + +/// Select Behind steps through the members of groups one by one, front to back, in one traversal +/// for a large stack, as the hit test repeated over what is left finds them. +#[test] +fn leaves_at_lists_group_members_one_by_one() { + let mut d = Document::new(100.0, 100.0); + let layer = d.layers[0].id; + let square = |d: &mut Document| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d); + let below_id = below.id; + d.insert(Some(layer), usize::MAX, below).unwrap(); + let members: Vec = (0..300).map(|_| square(&mut d)).collect(); + let mut ids: Vec = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(layer), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + ids.reverse(); + ids.push(below_id); + let p = Point::new(25.0, 25.0); + let hits = leaves_at(&d, p, HitOptions::default()); + assert_eq!(hits.len(), MAX_LEAVES_AT, "the list stops at its limit"); + assert_eq!(hits.iter().map(|h| h.leaf).collect::>(), ids[..MAX_LEAVES_AT], "the group's members, topmost first"); + assert!(hits.iter().all(|h| h.ancestry.contains(&g))); + assert_eq!(leaf_chains(hits), leaf_chains(leaves_at_repeated(&d, p, HitOptions::default()))); + // Hidden past the limit, the object below the group comes after the members that are left. + for id in &ids[3..300] { + d.node_mut(*id).unwrap().visible = false; + } + let shown: Vec = leaves_at(&d, p, HitOptions::default()).iter().map(|h| h.leaf).collect(); + assert_eq!(shown, [ids[0], ids[1], ids[2], below_id]); + let isolated = leaves_at(&d, p, HitOptions { scope: Some(g), ..Default::default() }); + assert!(!isolated.iter().any(|h| h.leaf == below_id), "isolated: only the group's members"); +} + /// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the /// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option, mut tops: Vec) -> Vec { @@ -2322,6 +2370,40 @@ fn select_behind_keeps_one_art_limit_when_it_falls_back() { assert!(arts <= 34, "root that is not a layer: {arts} instances' art walked"); } +/// [`leaves_at`] falls back to repeated hit tests at a clip group, after the hits its single +/// traversal found above it: an instance hit by its art, with the limit of symbol art then used +/// up, stays in the list. +#[test] +fn leaves_at_keeps_the_hits_above_a_clip_group_it_falls_back_at() { + let p = Point::new(150.0, 50.0); + let mut d = Document::new(600.0, 400.0); + clipped_symbol(&mut d, false); + // A clip group at the bottom of the layer, its art under (150, 50). + let square = |id| Arc::new(Node::path(id, shapes::rectangle(Rect::new(120.0, 20.0, 180.0, 80.0)), Appearance::default_art())); + let (mask, art) = (d.alloc_id(), d.alloc_id()); + let mut clip_group = Node::group(d.alloc_id(), vec![square(mask), square(art)]); + clip_group.set_clips(true); + let l = d.layers[0].id; + d.insert(Some(l), 0, clip_group).unwrap(); + let (mut shown_mask, shown_art) = half_clipped(&mut d); + shown_mask.appearance.effects.push(test_move()); + let mut shown = Node::group(d.alloc_id(), vec![Arc::new(shown_mask), Arc::new(shown_art)]); + shown.set_clips(true); + group_symbol(&mut d, "Shown", vec![Arc::new(shown)]); + let hit = instance_of(&mut d, "Shown"); + let hit_id = hit.id; + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(hit)).unwrap(); + for _ in 0..32 { + let inst = instance_of(&mut d, "Clipped"); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(inst)).unwrap(); + } + let (hits, _, arts) = with_art_limit(100, || leaves_at(&d, p, HitOptions::default())); + let leaves: Vec = hits.iter().map(|h| h.leaf).collect(); + assert_eq!(leaves.first(), Some(&hit_id), "hit before the fallback: {leaves:?}"); + assert!(leaves.contains(&art), "the clipped art after it: {leaves:?}"); + assert!(arts <= 34, "{arts} instances' art walked"); +} + #[test] fn locked_and_hidden_skip() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 15fedf19dc..bcb65125e1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -121,6 +121,10 @@ pub struct Session { /// 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 uid of the document in which a Cmd press with the Selection tool armed Select Behind + /// ([`Session::behind_armed`]): Cmd has been held since. None once Cmd is let go, the tool + /// changes or another document becomes active. + pub(crate) behind_armed: Option>, /// 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/session/documents.rs b/crates/engine/src/session/documents.rs index 2890618dd8..07a4ea4ffc 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -72,6 +72,7 @@ impl Session { last_selection_tool: None, last_part_selection_tool: None, press_lent: None, + behind_armed: None, hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), @@ -227,6 +228,7 @@ impl Session { } self.press_type_selection = None; self.press_lent = None; + self.behind_armed = 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 6aec396704..7fd3b2a70c 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -5160,14 +5160,15 @@ fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() { #[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. + // Over a selected object, a Cmd-click with the Selection tool after an earlier Cmd press + // 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(); + arm_select_behind(&mut s, v); s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); // The canvas shows the marks of the tool a press at the pointer takes, and the status bar and // the help bar name it. @@ -5206,7 +5207,7 @@ fn a_cmd_press_on_a_selected_object_keeps_select_behind() { #[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. + // the Selection tool still hits: once armed, a Cmd press there selects the object behind. let cmd = Mods { cmd: true, ..Mods::default() }; let v = view(); let mut s = session(); @@ -5214,7 +5215,7 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { 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(); + arm_select_behind(&mut s, v); 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); @@ -5229,12 +5230,12 @@ fn a_cmd_press_on_a_wide_strokes_outer_half_selects_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. + // takes the press, also once a Cmd press has armed Select Behind. 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(); + arm_select_behind(&mut s, v); 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(); @@ -5262,7 +5263,7 @@ fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() { 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(); + arm_select_behind(&mut s, v); 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" { @@ -5310,6 +5311,105 @@ fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group"); } +/// A back rectangle under a group whose small top member lies over a large one, all three under +/// (200, 200): (back, group, large, small). +fn stacked_group(s: &mut Session) -> (NodeId, NodeId, NodeId, NodeId) { + let back = rect(s, 100.0, 100.0, 200.0, 200.0); + let large = rect(s, 120.0, 120.0, 160.0, 160.0); + let small = rect(s, 170.0, 170.0, 60.0, 60.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [large.0, small.0]})).unwrap()["id"].as_u64().unwrap()); + (back, group, large, small) +} + +/// A Cmd-click at (200, 200), Cmd held before and after it. +fn cmd_click(s: &mut Session, v: ViewInfo) { + let cmd = Mods { cmd: true, ..Mods::default() }; + for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 200.0, 200.0).with_mods(cmd), v).unwrap(); + } +} + +/// Arms Select Behind with a Cmd-click with the Selection tool on empty canvas, away from the art +/// of the tests, Cmd still held: the next Cmd-click over the selection selects behind. +fn arm_select_behind(s: &mut Session, v: ViewInfo) { + let cmd = Mods { cmd: true, ..Mods::default() }; + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 900.0, 900.0).with_mods(cmd), v).unwrap(); + } + assert!(s.behind_armed()); +} + +#[test] +fn cmd_clicks_step_through_the_members_of_a_group_then_behind_it() { + // With Cmd held, the first click picks the group's top member, and each further one the object + // under it, the group's other member included, then back to the top member. + let v = view(); + let mut s = session(); + let (back, group, large, small) = stacked_group(&mut s); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for (i, want) in [small, large, back, small].into_iter().enumerate() { + cmd_click(&mut s, v); + let picked = &s.active().unwrap().selection.objects; + assert_eq!(picked, &vec![want], "Cmd-click {}", i + 1); + assert!(!picked.contains(&group), "Cmd-click {} picks one object", i + 1); + } +} + +#[test] +fn the_first_cmd_click_on_a_selected_group_does_not_select_behind() { + // The first Cmd-click over the selected group is Direct Selection's: it does not select the + // object behind the group. Clicking on with Cmd held reaches the object behind. + let v = view(); + let mut s = session(); + let (back, group, ..) = stacked_group(&mut s); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let cmd = Mods { cmd: true, ..Mods::default() }; + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection", "not armed yet: the press is lent"); + cmd_click(&mut s, v); + assert!(!s.active().unwrap().selection.contains(back), "the first Cmd-click does not select behind"); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "armed: the next press selects behind"); + let reached = (0..3).any(|_| { + cmd_click(&mut s, v); + s.active().unwrap().selection.contains(back) + }); + assert!(reached, "further Cmd-clicks reach the object behind the group"); +} + +#[test] +fn letting_go_of_cmd_ends_select_behind() { + // After a Cmd-click, Cmd let go and pressed again: the next Cmd-click is Direct Selection's + // again, which keeps the picked member, and does not step to the one under it. + let v = view(); + let mut s = session(); + let (_, _, large, small) = stacked_group(&mut s); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + cmd_click(&mut s, v); + assert!(s.behind_armed()); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap(); + assert!(!s.behind_armed(), "Cmd let go"); + cmd_click(&mut s, v); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(small) && !picked.contains(large), "the Cmd-click after letting go keeps the top member"); + // Cmd let go between frames, with no pointer event, also ends it. + cmd_click(&mut s, v); + assert!(s.active().unwrap().selection.contains(large), "armed again: the Cmd-click steps under"); + s.hover_tool_at(Some(Point::new(200.0, 200.0)), &Mods::default(), v); + assert!(!s.behind_armed(), "the frame found Cmd up"); + // So does a key pressed without Cmd, as the automation interface sends it. + cmd_click(&mut s, v); + s.tool_key(ToolKey::Tab, Mods::default(), v).unwrap(); + assert!(!s.behind_armed(), "the key came without Cmd"); + // Choosing a tool ends it too. + cmd_click(&mut s, v); + s.select_tool("rectangle", v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert!(!s.behind_armed(), "the tool changed"); +} + #[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 @@ -5319,7 +5419,7 @@ fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { 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(); + arm_select_behind(&mut s, v); 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(); @@ -5336,7 +5436,7 @@ fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() { 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(); + arm_select_behind(&mut s, v); 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(); @@ -5356,7 +5456,7 @@ fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() { 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(); + arm_select_behind(&mut s, v); 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(); @@ -5375,7 +5475,7 @@ fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_sele 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(); + arm_select_behind(&mut s, v); 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(); @@ -5392,7 +5492,7 @@ fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() 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(); + arm_select_behind(&mut s, v); 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(); @@ -5402,8 +5502,10 @@ fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() } #[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. +fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_that_member() { + // Select Behind counts the members of a group one by one: with one member selected, a Cmd-click + // on another member picks that member, not the object behind the group, also when armed. The + // Cmd-click after it selects the object behind. let cmd = Mods { cmd: true, ..Mods::default() }; let v = view(); let mut s = session(); @@ -5411,13 +5513,19 @@ fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_ 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(); + arm_select_behind(&mut s, v); 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(); + assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "directSelection", "on the unselected member"); + let click = |s: &mut Session| { + 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(); + }; + click(&mut s); let picked = &s.active().unwrap().selection; - assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group"); + assert!(picked.contains(b) && !picked.contains(back) && !picked.contains(a), "the Cmd-click picks the member"); + click(&mut s); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(b), "the next Cmd-click selects the object behind"); } #[test] @@ -5429,7 +5537,7 @@ fn a_cmd_click_on_a_selected_lines_segment_selects_behind() { 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(); + arm_select_behind(&mut s, v); 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. @@ -5449,7 +5557,7 @@ fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for 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(); + arm_select_behind(&mut s, v); 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(); @@ -5468,7 +5576,7 @@ fn the_marks_follow_this_frames_pointer_with_cmd_held() { 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(); + arm_select_behind(&mut s, v); 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"); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 7a339b6cbd..e2e2d3dae7 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -641,10 +641,11 @@ fn selection_preferences_drive_the_selection_tool() { assert!(click(&mut s, 225.0, plain).is_empty(), "a click inside the fill selects nothing"); assert_eq!(click(&mut s, 250.0, plain), vec![front], "a click on the path selects it"); set(&mut s, "objectSelectionByPathOnly", json!(false)); - // Command Click to Select Objects Behind (on by default): each Cmd/Ctrl-click goes one down, - // then back to the top. + // Command Click to Select Objects Behind (on by default): the first Cmd/Ctrl-click is Direct + // Selection's, then each one goes one down, then back to the top. let cmd = Mods { cmd: true, ..Mods::default() }; assert_eq!(click(&mut s, 175.0, plain), vec![front]); + assert_eq!(click(&mut s, 175.0, cmd), vec![front], "the first Cmd-click arms Select Behind"); assert_eq!(click(&mut s, 175.0, cmd), vec![back], "the object behind"); assert_eq!(click(&mut s, 175.0, cmd), vec![front], "back to the topmost"); set(&mut s, "ctrlClickSelectsBehind", json!(false)); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index be4615bb43..2c4f4419f4 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -27,6 +27,8 @@ pub(crate) struct HoverKey { use_preview_bounds: bool, type_glyph_bounds: bool, show_handles_multiple_anchors: bool, + /// [`Session::behind_armed`]. + behind_armed: bool, } /// The tool whose radius is General › Corner Radius. @@ -203,8 +205,10 @@ impl Session { 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. + // comes back to the tool a Cmd press was lent from. Select Behind is armed again by the + // next Cmd press. self.press_lent = None; + self.behind_armed = 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). @@ -366,6 +370,22 @@ impl Session { use_preview_bounds: p.use_preview_bounds, type_glyph_bounds: p.type_glyph_bounds, show_handles_multiple_anchors: p.show_handles_multiple_anchors, + behind_armed: self.behind_armed(), + } + } + + /// Has a Cmd press with the Selection tool in the active document armed Select Behind, with + /// Cmd held since? Then a Cmd-click over the selection selects the object behind it (Selection + /// & Anchor Display › Command Click to Select Objects Behind); the first Cmd press is lent to + /// Direct Selection or Group Selection. + pub fn behind_armed(&self) -> bool { + self.behind_armed.is_some_and(|doc| doc == self.active().map(|d| d.uid)) + } + + /// Cmd let go ends Select Behind's arming ([`Self::behind_armed`]). + fn note_cmd_held(&mut self, mods: &Mods) { + if !mods.cmd { + self.behind_armed = None; } } @@ -374,6 +394,7 @@ impl Session { /// ([`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 { + self.note_cmd_held(mods); let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; let lent = match p { _ if !lends => None, @@ -387,7 +408,8 @@ impl Session { /// 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). + /// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd + /// press armed ([`Self::behind_armed`]). 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)); @@ -629,6 +651,7 @@ impl Session { double_click_isolate: self.prefs.double_click_to_isolate, double_click_adds_anchor: self.prefs.double_click_adds_anchor_points, select_behind: self.prefs.ctrl_click_selects_behind, + behind_armed: self.behind_armed(), highlight_anchors: self.prefs.highlight_anchors_on_hover, snap_tolerance: self.prefs.snap_to_point_tolerance, handles_multiple: self.prefs.show_handles_multiple_anchors, @@ -921,7 +944,13 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); + self.note_cmd_held(&ev.mods); + // A Cmd press with the Selection tool, lent or not, arms Select Behind for the next one. + let arms = ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.tool.id() == "selection"; let (ev, settled) = self.lend_selection_tool(ev, view)?; + if arms { + self.behind_armed = Some(self.active().map(|d| d.uid)); + } let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -1220,6 +1249,7 @@ impl Session { } fn tool_key_now(&mut self, key: ToolKey, mods: Mods, view: ViewInfo) -> Result> { + self.note_cmd_held(&mods); // 1–4 pick the active perspective plane while the grid is shown. if let Some(plane) = self.plane_key(key) { self.execute("perspective.plane.set", &serde_json::json!({ "plane": plane.id() }))?; @@ -1460,6 +1490,7 @@ impl Session { /// The pointer the active tool shows at `p`. With Cmd held, the pointer of the selection tool a /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { + self.note_cmd_held(&mods); // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. // 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; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index c1a661c4e3..9564e8f67c 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1916,7 +1916,7 @@ fn oversized_screenshot_and_png_export_are_errors() { } /// Preferences reach agents' gestures (#394): `prefs.set` Object Selection by Path Only, then a -/// click inside a filled square selects nothing; Command Click to Select Objects Behind, a +/// click inside a filled square selects nothing; Command Click to Select Objects Behind, a second /// Cmd-click selects the square underneath. #[test] fn selection_preferences_apply_to_pointer_gestures() { @@ -1926,14 +1926,15 @@ fn selection_preferences_apply_to_pointer_gestures() { serde_json::from_str::(&text_of(&r)).unwrap()["id"].as_u64().unwrap() }; let (back, front) = (square(&mut s, 1, 100), square(&mut s, 2, 150)); - let click = |s: &mut Server, id: u64, x: f64, mods: Value| { - let events = json!([{"kind": "down", "x": x, "y": 125}, {"kind": "up", "x": x, "y": 125}]); + let clicks = |s: &mut Server, id: u64, x: f64, mods: Value, n: usize| { + let events: Vec = (0..n).flat_map(|_| [json!({"kind": "down", "x": x, "y": 125}), json!({"kind": "up", "x": x, "y": 125})]).collect(); let r = call(s, id, "pointer_gesture", json!({"tool": "selection", "events": events, "mods": mods})); assert_eq!(r["isError"], false, "{r}"); serde_json::from_str::(&text_of(&r)).unwrap()["selection"].clone() }; + let click = |s: &mut Server, id: u64, x: f64, mods: Value| clicks(s, id, x, mods, 1); assert_eq!(click(&mut s, 3, 175.0, json!({})), json!([front])); - assert_eq!(click(&mut s, 4, 175.0, json!({"cmd": true})), json!([back]), "Cmd-click selects behind"); + assert_eq!(clicks(&mut s, 4, 175.0, json!({"cmd": true}), 2), json!([back]), "the second Cmd-click selects behind"); let r = call(&mut s, 5, "run_command", json!({"command": "prefs.set", "params": {"key": "objectSelectionByPathOnly", "value": true}})); assert_eq!(r["isError"], false, "{r}"); assert_eq!(click(&mut s, 6, 225.0, json!({})), json!([]), "path only: the fill doesn't select"); diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 67658b4ea9..fd9776837d 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -295,10 +295,14 @@ pub struct ToolContext<'a> { /// General → Double-Click Adds Anchor Points: a plain double-click on a path segment with Direct /// Selection adds an anchor there. pub double_click_adds_anchor: bool, - /// Selection & Anchor Display → Command Click to Select Objects Behind: Cmd/Ctrl-click with the - /// Selection tool selects the object under the selected one, the next click the one under - /// that. + /// Selection & Anchor Display → Command Click to Select Objects Behind: once a Cmd/Ctrl press + /// with the Selection tool has armed it ([`Self::behind_armed`]), a Cmd/Ctrl-click selects the + /// object under the selected one, the next click the one under that. pub select_behind: bool, + /// A Cmd/Ctrl press with the Selection tool came before, and Cmd/Ctrl has been held since: the + /// next Cmd/Ctrl-click over the selection selects behind ([`Self::select_behind`]). The first + /// press is lent to Direct Selection or Group Selection. + pub behind_armed: bool, /// Selection & Anchor Display → Highlight anchors on mouse over: Direct Selection marks the /// anchor under the pointer. pub highlight_anchors: bool, diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a39bf3766f..88ee2c4cdf 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2946,7 +2946,7 @@ fn select_behind_is_measured_once_for_a_point() { 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 c = ToolContext { preview_memo: Some(&memo), select_behind: true, behind_armed: 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"); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index ec2b83f1a6..449dad62d8 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -668,6 +668,7 @@ pub(crate) mod testutil { double_click_isolate: true, double_click_adds_anchor: false, select_behind: true, + behind_armed: false, highlight_anchors: true, snap_tolerance: 2.0, handles_multiple: true, diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index cb02554785..14dccdbdad 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -41,7 +41,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, leaves_at, marquee_in_view, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -520,8 +520,6 @@ struct Measured { 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)>, } @@ -598,7 +596,6 @@ impl PreviewMemo { by_object: HashMap::new(), painted: [None, None], part_boxes: None, - holders: None, behind: None, }; if !st.entry.as_ref().is_some_and(|m| m.is_for(cx)) { @@ -1215,9 +1212,11 @@ impl Tool for SelectionTool { self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } - // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). + // 3. Objects: once armed, Cmd/Ctrl-click selects the one under the selected one + // (cycling). if m.cmd && cx.select_behind + && cx.behind_armed && let Some(behind) = object_behind(cx, p) { self.state = @@ -1569,13 +1568,14 @@ impl Tool for SelectionTool { } } -/// 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), +/// Does a Cmd/Ctrl press at `p` with the Selection tool select behind: is Select Behind on and +/// armed by an earlier Cmd/Ctrl press ([`ToolContext::behind_armed`]), and is an object under the +/// pointer ([`leaves_at`]) selected or inside a selected object (a member of a selected group), /// 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 { + if !cx.select_behind || !cx.behind_armed { return false; } let tol = cx.pick_tol(); @@ -1599,8 +1599,8 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { 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() + let stack = under_pointer(cx, p); + stack.len() > 1 && lowest_selected(&stack).is_some() } && !crate::direct::over_selected_part(cx, p); if let Some(memo) = cx.preview_memo @@ -1616,25 +1616,25 @@ pub fn selects_behind_at(cx: &ToolContext, p: Point) -> bool { behind } -/// 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 objects under `p` that Select Behind steps through, topmost first: for each object a Direct +/// Selection click picks there ([`leaves_at`]; in a compound path, the path under the pointer), the +/// object and whether it is selected or inside a selected object. +fn under_pointer(cx: &ToolContext, p: Point) -> Vec<(NodeId, bool)> { + let tol = cx.pick_tol(); + leaves_at(cx.doc, p, cx.selection_hit_options()) + .into_iter() + .map(|h| { + let part = cx.doc.node(h.leaf).and_then(|n| compound_part_at(n, p, tol)); + let picked = h.ancestry.iter().copied().chain(std::iter::once(h.leaf)).chain(part).any(|id| cx.selection.contains(id)); + (part.unwrap_or(h.leaf), picked) + }) + .collect() } -/// 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 index in `stack` ([`under_pointer`]) of the lowest object that is selected or inside a +/// selected object. +fn lowest_selected(stack: &[(NodeId, bool)]) -> Option { + stack.iter().rposition(|(_, picked)| *picked) } /// The selected object `id` and the objects holding it, outermost first, from the object a click @@ -1660,13 +1660,13 @@ 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. +/// Select Behind: of the objects under `p` ([`under_pointer`], topmost first, members of groups +/// one by one), the one below the lowest one that is selected or inside a selected object, 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 = holds_selection(cx, &stack).map_or(0, |i| i + 1); - stack.get(next).or(stack.first()).copied() + let stack = under_pointer(cx, p); + let next = lowest_selected(&stack).map_or(0, |i| i + 1); + stack.get(next).or(stack.first()).map(|(id, _)| *id) } /// The selected object a press on `h` lands on: `top` when it is selected, else the outermost diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index b059903b50..e7d6c5ec04 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -230,9 +230,9 @@ fn a_release_ends_the_image_trace_hold_without_the_panel() { frame(&mut app, &ctx, vec![press(false)]); } -/// The canvas decides which tool's marks and widgets to show for the pointer where it is in the same frame: over the -/// selected blend a Cmd press selects behind, so the Selection tool's stay; moved away in the next frame, where Cmd -/// lends Direct Selection, they are Direct Selection's in that frame. +/// The canvas decides which tool's marks and widgets to show for the pointer where it is in the same frame: once a +/// Cmd-click has armed Select Behind, over the selected blend a Cmd press selects behind, so the Selection tool's +/// stay; moved away in the next frame, where Cmd lends Direct Selection, they are Direct Selection's in that frame. #[test] fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -245,14 +245,22 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() { 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 = crate::testing::ui_context(); frame(&mut app, &ctx, vec![]); let xf = app.canvas_view().unwrap(); + let held = |events: Vec| std::iter::once(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND)).chain(events).collect(); let cmd_frame = |app: &mut VectorcraftApp, at: Point| { - frame(app, &ctx, vec![egui::Event::ModifiersChanged(egui::Modifiers::COMMAND), egui::Event::PointerMoved(xf.to_screen(at))]); + frame(app, &ctx, held(vec![egui::Event::PointerMoved(xf.to_screen(at))])); app.session.hover_tool_id(&Mods { cmd: true, ..Default::default() }) }; + // A Cmd-click on empty canvas arms Select Behind; Cmd stays held. + let empty = xf.to_screen(Point::new(200.0, 380.0)); + let button = + |pressed| egui::Event::PointerButton { pos: empty, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::COMMAND }; + frame(&mut app, &ctx, held(vec![egui::Event::PointerMoved(empty), button(true)])); + frame(&mut app, &ctx, held(vec![button(false)])); + assert!(app.session.behind_armed()); + app.session.execute("select.set", &json!({"ids": [blend]})).unwrap(); // Inside the first key object, away from its anchors and the spine. assert_eq!(cmd_frame(&mut app, Point::new(80.0, 175.0)), "selection", "over the selected blend, the press selects behind"); assert_eq!(cmd_frame(&mut app, Point::new(200.0, 380.0)), "directSelection", "away from it, in the same frame"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4b03fb52f7..42d6829321 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 (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.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, after an earlier press with `mods.cmd` and with `mods.cmd` on every event since, on a selected object (or an object inside one) 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 next object under the pointer (members of groups one by one, back to the topmost after the last); 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 1bbe49574d..c73c31fa49 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7743,10 +7743,11 @@ 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 +with Direct Selection or Group Selection, whichever was chosen last (Direct Selection until one is). That first press +arms Select Behind while `ctrlClickSelectsBehind` is on: until an event comes without `mods.cmd`, a press that lands on +a selected object, or on an object inside one, 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, stays with the Selection tool and +selects the next object under the pointer (members of groups one by one, back to the topmost after the last). 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. @@ -9034,9 +9035,10 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture handle or segment for Direct Selection, the Anchor Point, Add and Delete Anchor Point and Scissors tools, and the Pen with Alt. A handle shorter than that leaves its anchor to be picked when pressed nearer the anchor. - `objectSelectionByPathOnly`: a click inside a filled path or compound path doesn't select it, one on its path does. -- `ctrlClickSelectsBehind` (on by default): a Selection tool click with `mods: {cmd: true}` (Command on macOS, Ctrl - elsewhere) selects the object under the selected one there, the next such click the one under that, then the - topmost again. Cmd held to borrow the selection tool from another tool clicks as usual. +- `ctrlClickSelectsBehind` (on by default): after a first Selection tool click with `mods: {cmd: true}` (Command on + macOS, Ctrl elsewhere), which Direct Selection or Group Selection takes, each further such click with Cmd held + selects the object under the selected one there, members of groups one by one, the next such click the one under + that, then the topmost again. Cmd held to borrow the selection tool from another tool clicks as usual. - `doubleClickToIsolate` (on by default): a `doubleclick` with the Selection tool isolates a group, a compound path or a single path, image, mesh or placed file (not type, blends, envelopes, repeats or symbol instances); off, it no longer does. - `usePreciseCursors`: the Pen, Eyedropper, Slice and Blend tools' pointers are a crosshair. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..4bee0a6ade 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1621,7 +1621,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, 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. + - **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. The first Cmd press arms Select Behind while Command Click to Select Objects Behind is on: until Cmd is let go, a Cmd press on a selected object, or on an object inside one, 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, selects the next object under the pointer, counting the members of groups one by one and coming back to the topmost after the last, as "Select behind an object" (Ctrl+click twice) in [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) and "Select behind objects" in [Select objects](https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe (#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 1c491b9714..d87d119def 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -373,7 +373,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, 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 | +| 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 once a first Cmd press has armed Select Behind (Command Click to Select Objects Behind on), a Cmd press on a selected object, or on an object inside one, 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, selects the next object under the pointer until Cmd is let go, members of groups one by one and back to the topmost after the last, 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) and "Select behind objects" in [Select objects](https://helpx.adobe.com/illustrator/using/selecting-objects.html) describe; 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` |