From 8fa551e173e00f7d584913cf6d3e3298f563fe93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 03:55:28 -0800 Subject: [PATCH] Selection: clicks in a clip group follow the region its clipping path's effects give it The canvas clips a clip group by its clipping path with the path's live geometry effects applied, but clicks, hovers and marquees still tested the plain clipping path. A click where a Transform effect had moved the clip selected nothing, and a click on the clipping path's own place selected art that was not drawn there. - The engine registers the effect-shaped region with the doc crate (`hit::set_clip_region`), as it does for image paint and live art. It gives a region only when the clipping path holds a visible geometry effect; otherwise clicks keep the plain shapes, and type keeps counting by its frame. - Clicks, `objects_at`, the hidden art of a selected object, the Unlock submenu's list and marquees inside a clip group or a clipping layer use that region. Outline view and layers with Preview off draw no effects and keep the plain shapes; the Selection, Direct Selection and Enclosing Lasso marquees pass the view's outline state (`hit::marquee_in_view`). Each container around a selected object tests its clipping path in the outline state a click has there. - A marquee touches the clipping path itself by its own geometry, as a click on its outline finds it, and also on the edge of the region, so a marquee around a clipping path that an effect moved into large art still selects it. `hit::marquee_in` keeps the plain shapes for the Color Theme Picker, which clips by them. - The region is kept per thread until the clipping path or the live inputs change. A clip group's reach takes in the region's box, so culling does not skip art the region moved past the plain clipping path. Up to 4096 boxes are kept; when they are full, a new box replaces only as many others as it needs room for. Docs: docs/target-app-parity.md. --- crates/doc/src/hit.rs | 368 +++++++++++++++--- crates/doc/src/hit/tests.rs | 239 ++++++++++++ crates/doc/src/node/ops.rs | 9 +- crates/engine/src/session/documents.rs | 13 + crates/engine/src/tests/clip.rs | 42 ++ crates/tools/src/addons/enclosing_lasso.rs | 2 +- .../tools/src/addons/enclosing_lasso/tests.rs | 22 ++ crates/tools/src/direct.rs | 4 +- crates/tools/src/direct/tests.rs | 23 ++ crates/tools/src/lib.rs | 30 ++ crates/tools/src/select.rs | 4 +- crates/tools/src/select/tests.rs | 19 + docs/target-app-parity.md | 1 + 13 files changed, 713 insertions(+), 63 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fd907a26cc..c0a80a8964 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,7 +1,7 @@ //! Hit testing over the document tree. use std::cell::RefCell; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::{Arc, OnceLock}; @@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: & return false; } // How a click reaches it, if one does. + let start = opt; let Some(opt) = path_options(&nodes, &chain, opt) else { return false }; - // Hidden by a mask: one of the containers around it clips, and not to `p`. - let masked = nodes - .iter() - .rev() - .skip(1) - .any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p))); + // Hidden by a mask: one of the containers around it clips, and not to `p`. A container + // tests its clipping path in outline from the first layer with Preview off down to it, as + // a click going down to it does ([`path_options`]). + let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| { + let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n))); + n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline)) + }); // A click may reach it there ([`may_hit`]: not a guide while guides are locked or // hidden, nor a Shaper group's hidden part), and its own art is what a click would hit // in it: a group's hidden, locked or masked contents don't count. @@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option, seen: &mut HashSet) -> bool { let Some(children) = layer.children() else { return true }; + let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; if layer.clips() && let Some(clip) = children.first() { @@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) { tops.push(clip.id); } - if !clip_contains(clip, p) { + if !clip_contains(clip, p, opt.outline) { return true; } } - let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt }; for (i, c) in children.iter().enumerate().rev() { if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) { continue; @@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec) { let Some(children) = parent.children() else { return }; - if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) { + if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) { return; } for i in hit_order(parent, children, p) { @@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool { matches!(n.kind, NodeKind::Envelope { editing: true, .. }) } -/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame: -/// glyph outlines need the font engine, above this crate. -fn clip_contains(clip: &Node, p: Point) -> bool { - clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) +/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`]) +/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count. +fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool { + let areas = if outline { clip_regions(clip) } else { clip_areas(clip) }; + areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p)) } -/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in -/// [`clip_contains`]. +/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry +/// effects of the clipping path and of what it clips by applied, as one path and fill rule +/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a +/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated +/// above this crate, so the engine registers one with [`set_clip_region`]. +pub type ClipRegion = fn(&Node) -> Option>; + +static CLIP_REGION: OnceLock = OnceLock::new(); + +/// Register how the region of a clipping path with live effects is found (the first registration +/// stays). +pub fn set_clip_region(f: ClipRegion) { + // Already set: the same engine, registered by another session. + let _ = CLIP_REGION.set(f); +} + +/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only +/// then can the registered [`ClipRegion`] find a geometry effect in it. +fn has_effects(clip: &Node) -> bool { + let mut found = false; + clip.walk(&mut |n| { + let visible = |e: &crate::Effect| e.visible; + found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible)); + }); + found +} + +/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the +/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its +/// path elements. +struct EvaluatedClip { + clip: Node, + inputs: u64, + region: Option>>, + size: usize, +} + +/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip +/// group whose clipping path has live effects asks for its region, and clip groups can be nested. +const CLIPS_KEPT: usize = 16; + +thread_local! { + /// The regions [`clip_region`] keeps, the latest first. + static CLIPS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many regions [`clip_region`] evaluated on this thread. + static CLIPS_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The region clipping path `clip` clips to with its live geometry effects applied +/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes +/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the +/// [`LiveInputs`] have changed since. +fn clip_region(clip: &Node) -> Option>> { + let f = CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIPS.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?; + let e = kept.remove(i); + let region = e.region.clone(); + kept.insert(0, e); + Some(region) + }); + if let Some(region) = kept { + return region; + } + #[cfg(test)] + CLIPS_EVALUATED.with(|c| c.set(c.get() + 1)); + let region = f(clip).map(Rc::new); + let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len()); + let size = elements.saturating_add(art_size(std::slice::from_ref(clip))); + if size <= LIVE_KEPT_SIZE { + let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size }; + CLIPS.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(CLIPS_KEPT); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); + } + region +} + +/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the +/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path. +struct ClipBox { + clip: Node, + inputs: u64, + rect: Option, + size: usize, +} + +/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip +/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not +/// only the latest few as with the regions. +const CLIP_BOXES_KEPT: usize = 4096; + +thread_local! { + /// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes. + static CLIP_BOXES: RefCell<(HashMap, usize)> = RefCell::new((HashMap::new(), 0)); +} + +/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]), +/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change. +/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the +/// pointer moving over more clip groups than fit still finds most of their boxes. +pub(crate) fn reshaped_clip_box(clip: &Node) -> Option { + use vectorcraft_geom::kurbo::Shape; + CLIP_REGION.get()?; + if !has_effects(clip) { + return None; + } + let inputs = live_inputs(); + let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect)); + if let Some(rect) = kept { + return rect; + } + let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box())); + let size = art_size(std::slice::from_ref(clip)); + if size <= LIVE_KEPT_SIZE { + CLIP_BOXES.with_borrow_mut(|(boxes, total)| { + if let Some(old) = boxes.remove(&clip.id) { + *total = total.saturating_sub(old.size); + } + while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE { + let Some(other) = boxes.keys().next().copied() else { break }; + if let Some(old) = boxes.remove(&other) { + *total = total.saturating_sub(old.size); + } + } + boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size }); + *total = total.saturating_add(size); + }); + } + rect +} + +/// The regions a click inside a clip group must fall in: those `clip` clips to with its live +/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]). +fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> { + match clip_region(clip) { + Some(region) => region.as_ref().iter().cloned().collect(), + None => clip_regions(clip), + } +} + +/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live +/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate. pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> { let frame = |n: &Node| { let b = n.geometric_bounds()?; @@ -698,7 +857,7 @@ fn hit_children( // Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for // the selection tools in isolation mode within it. let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope); - if !edited && !clip_contains(clip, p) { + if !edited && !clip_contains(clip, p, opt.outline) { return None; } } @@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option match &n.kind { // A clip group only hits inside its clipping path. NodeKind::Group { children, clip } => { - if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) { + if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) { return None; } children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols)) @@ -1081,7 +1240,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> path.push(0); return true; } - if !clip_contains(&clip, self.p) { + if !clip_contains(&clip, self.p, self.opt.outline) { return false; } } @@ -1244,31 +1403,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit /// the selection tools' clicks. pub fn marquee(doc: &Document, r: Rect, scope: Option, leaves: bool) -> Vec { - marquee_with(doc, r, scope, leaves, false) + marquee_with(doc, r, scope, leaves, false, false) +} + +/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer +/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as +/// the clicks of [`HitOptions::outline`] do. +pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option, leaves: bool, outline: bool) -> Vec { + marquee_with(doc, r, scope, leaves, false, outline) } /// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group -/// traversal follow [`marquee`]; compounds contribute the complete path they paint. -pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option) -> Vec { - marquee_with(doc, r, scope, true, true) +/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint. +pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option, outline: bool) -> Vec { + marquee_with(doc, r, scope, true, true, outline) } -fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool) -> Vec { +/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)? +fn previews_off(n: &Node) -> bool { + matches!(n.kind, NodeKind::Layer { preview: false, .. }) +} + +fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, whole_compounds: bool, outline: bool) -> Vec { let mut out = Vec::new(); - // `tops` pairs each object with the part of `r` in which the marquee can touch it. - let tops: Vec<(&std::sync::Arc, Rect)> = match scope.and_then(|s| doc.node(s)) { + // The objects the marquee may touch ([`Top`]). + let tops: Vec = match scope.and_then(|s| doc.node(s)) { // Isolated art whose layer, or a group around it, was locked or hidden afterwards: the // marquee touches none of it, as clicks don't (#5309). Some(s) if !doc.is_editable(s.id) => vec![], Some(s) => match s.children() { - Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(), + Some(c) => c + .iter() + .enumerate() + .filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)) + .map(|(_, c)| (c, Some(r), outline, None)) + .collect(), // A single object isolated: only it. None => doc .parent_of(s.id) .and_then(|p| doc.node(p)) .and_then(|p| p.children()) .into_iter() - .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r))) + .flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None))) .collect(), }, // The objects of the layers, looking through sublayers (hidden, locked and template ones @@ -1277,42 +1453,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh .layers .iter() .filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id)) - .flat_map(|l| layer_objects(l, r)) + .flat_map(|l| layer_objects(l, r, outline)) .collect(), }; /// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of - /// the sublayers it is in leave. - fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc, Rect)> { + /// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`, + /// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain + /// shapes ([`mask_marquee`]). + fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec> { let mut out = vec![]; - let Some(r) = marquee_in(l, r) else { return out }; - for c in l.children().into_iter().flatten() { + let outline = outline || previews_off(l); + let inner = marquee_in_parent(l, r, outline); + for (i, c) in l.children().into_iter().flatten().enumerate() { if c.is_layer() { - if c.visible && !c.locked && !c.is_template() { - out.extend(layer_objects(c, r)); + if let Some(inner) = inner + && c.visible + && !c.locked + && !c.is_template() + { + out.extend(layer_objects(c, inner, outline)); } } else if !c.is_ruler_guide() { - out.push((c, r)); + if i == 0 && l.clips() { + out.push((c, mask_marquee(l, r), outline, Some(r))); + } else if inner.is_some() { + out.push((c, inner, outline, None)); + } } } out } + /// The part of `r` in which the marquee can touch the clipping path of `parent` by its own + /// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its + /// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to. + fn mask_marquee(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) + } + /// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a + /// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where + /// the clip shows? Never in outline, nor without live effects: its own geometry counts then. + fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool { + if outline { + return false; + } + clip_region(clip).is_some_and(|region| { + region.as_ref().as_ref().is_some_and(|(bp, _)| { + // The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it. + let mut edge = PathData::from_bezpath(bp); + edge.subpaths.iter_mut().for_each(|sp| sp.closed = true); + vectorcraft_geom::hit::intersects_rect(&edge, r) + }) + }) + } + /// Is `n` collected whole by [`collect_leaves`], not by its members? + fn is_leaf(n: &Node) -> bool { + !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. }) + } /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. - fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool) -> bool { + /// compound paths, layers and groups are touched by their box. A clipping path is touched by + /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { match &n.kind { NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r), NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - marquee_in(n, r).is_some_and(|r| { - children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds)) + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); + children.iter().enumerate().any(|(i, c)| { + c.visible + && !shaper_hides(n, i, scope) + && if i == 0 && n.clips() { + mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline) + } else { + inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) + } }) } NodeKind::Compound { children, .. } if whole_compounds => { children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r)) } - NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)), - NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)), + NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), + NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A box with no width or no height (an instance of a symbol that draws a straight // line) is touched where the marquee crosses it. _ => n.geometric_bounds_with(s).is_some_and(|b| { @@ -1321,18 +1543,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh }), } } - fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, out: &mut Vec) { + fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool, out: &mut Vec) { match &n.kind { NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => { - let Some(r) = marquee_in(n, r) else { return }; + let outline = outline || previews_off(n); + let inner = marquee_in_parent(n, r, outline); for (i, c) in children.iter().enumerate() { - if c.visible && !c.locked && !shaper_hides(n, i, scope) { - collect_leaves(c, s, r, scope, whole_compounds, out); + if !c.visible || c.locked || shaper_hides(n, i, scope) { + continue; + } + if i == 0 && n.clips() { + let before = out.len(); + if let Some(r) = mask_marquee(n, r) { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); + } + if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) { + out.push(c.id); + } + } else if let Some(r) = inner { + collect_leaves(c, s, r, scope, whole_compounds, outline, out); } } } _ => { - if touches(n, s, r, scope, whole_compounds) { + if touches(n, s, r, scope, whole_compounds, outline) { out.push(n.id); } } @@ -1340,36 +1574,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh } let symbols = doc.symbol_boxes(); let locks = doc.locked_artboards(); - for (t, r) in tops { + for (t, r, outline, edge) in tops { if !t.visible || t.locked || locks.holds_id(t.id) { continue; } if leaves { - collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out); - } else if touches(t, &symbols, r, scope, whole_compounds) { + let before = out.len(); + if let Some(r) = r { + collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out); + } + if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) { + out.push(t.id); + } + } else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline)) + || edge.is_some_and(|e| clip_edge_touches(t, e, outline)) + { out.push(t.id); } } out } +/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which +/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a +/// layer, the marquee whose edge test it also takes (`clip_edge_touches`). +type Top<'a> = (&'a std::sync::Arc, Option, bool, Option); + /// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a -/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None -/// when the marquee misses it); otherwise it is all of `r`. +/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its +/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`. pub fn marquee_in(parent: &Node, r: Rect) -> Option { + marquee_in_parent(parent, r, true) +} + +/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its +/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline` +/// ([`marquee_in_view`]). +fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option { match parent.children().and_then(|c| c.first()) { - Some(clip) if parent.clips() => marquee_in_clip(clip, r), + Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline), _ => Some(r), } } /// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of /// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip` -/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those -/// bounds, art outside a region that is not a rectangle still counts. -fn marquee_in_clip(clip: &Node, r: Rect) -> Option { +/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of +/// those regions. Within those bounds, art outside a region that is not a rectangle still counts. +fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option { use vectorcraft_geom::kurbo::Shape; - let regions = clip_regions(clip); + let regions = if outline { clip_regions(clip) } else { clip_areas(clip) }; // The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it. let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| { let mut edge = vectorcraft_geom::PathData::from_bezpath(bp); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 3eac4202b6..4584421200 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -110,6 +110,245 @@ fn half_clipped(d: &mut Document) -> (Node, Node) { (mask, art) } +/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping +/// path, its first shape moved 100 pt right; without one, no geometry effect. +fn moved_clip_region(clip: &Node) -> Option> { + let mut moves = false; + clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + if !moves { + return None; + } + Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) +} + +/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region. +fn test_move() -> crate::Effect { + crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true } +} + +/// Clicks inside a clip group whose clipping path has a live effect fall in the region the +/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and +/// again after the clipping path changes; a clipping path without effects is not evaluated. +#[test] +fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let before = evaluated(); + let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf); + for x in [148.0, 150.0, 152.0] { + assert_eq!(leaf(&d, x), Some(art_id), "in the moved region"); + } + assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place"); + assert_eq!(evaluated(), before + 1); + // Outline mode draws no effects: the art's edge shows within the clipping path's own shape. + let outline = HitOptions { outline: true, ..HitOptions::default() }; + assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode"); + // So with a marquee across the art's left edge: in the view, only in Outline view. The + // clipping path's own left edge lies there too, and counts in both. + let edge = Rect::new(-5.0, 40.0, 5.0, 60.0); + assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]); + assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]); + // `marquee_in` measures by the plain shapes, as its callers clip by them. + assert!(marquee_in(d.node(g).unwrap(), edge).is_some()); + // Hidden, the effect no longer moves the region. + d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false; + assert_eq!(leaf(&d, 50.0), Some(art_id)); + assert_eq!(leaf(&d, 150.0), None); + assert_eq!(evaluated(), before + 1); + // Shown again and widened, the region is evaluated again. + let mask = d.node_mut(mask_id).unwrap(); + mask.appearance.effects[0].visible = true; + if let NodeKind::Path { path, .. } = &mut mask.kind { + *path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0)); + } + assert_eq!(leaf(&d, 180.0), Some(art_id)); + assert_eq!(leaf(&d, 195.0), None); + assert_eq!(evaluated(), before + 2); +} + +/// A marquee around a clipping path that an effect moved into the middle of large art touches the +/// clipping path on the edge of its moved region, in a clip group and in a clipping layer. +#[test] +fn a_marquee_touches_a_moved_clipping_path_on_its_region() { + set_clip_region(moved_clip_region); + let parts = |d: &mut Document| { + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art()); + (mask, art) + }; + // Around the moved region (120..160) and the clipping path's own place, inside the art. + let around = Rect::new(10.0, 10.0, 170.0, 70.0); + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + let (mask, art) = parts(&mut d); + let (g, mask_id) = (d.alloc_id(), mask.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + assert_eq!(marquee(&d, around, None, false), [g]); + assert_eq!(marquee(&d, around, None, true), [mask_id]); + // Only over the clipping path's own place, the marquee misses the region but touches the + // clipping path's anchors, which a click on its outline also finds. + let own = Rect::new(10.0, 10.0, 70.0, 70.0); + assert_eq!(marquee(&d, own, None, false), [g]); + assert_eq!(marquee(&d, own, None, true), [mask_id]); + // Away from both, nothing. + assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty()); + + let mut d = Document::new(400.0, 400.0); + let top = d.layers[0].id; + let (mask, art) = parts(&mut d); + let mask_id = mask.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + assert_eq!(marquee(&d, around, None, false), [mask_id]); +} + +/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point +/// and marquees count its clipping path by its plain shape, without the effect that moves it. +#[test] +fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() { + set_clip_region(moved_clip_region); + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind { + (*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + // The art's top edge, within the clipping path's own shape. + let p = Point::new(50.0, 0.5); + assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id)); + assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id)); + assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id)); +} + +/// The pointer moving over empty canvas past more clip groups with live effects than the regions +/// kept measures each group's box once: the boxes are kept for every clip group. +#[test] +fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + for i in 0..(2 * CLIPS_KEPT) { + let x = 20.0 * i as f64; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()); + mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + d.insert(Some(l), 0, clip).unwrap(); + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(500.0, 500.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + for _ in 0..3 { + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + } + assert_eq!(evaluated(), first); +} + +/// With more clip groups with live effects than the boxes kept, a new box replaces only as many +/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions. +#[test] +fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() { + set_clip_region(moved_clip_region); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let groups = CLIP_BOXES_KEPT + 64; + let mut members = Vec::with_capacity(groups); + for i in 0..groups { + let x = (i % 100) as f64 * 5.0; + let y = (i / 100) as f64 * 5.0; + let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default()); + mask.appearance.effects.push(test_move()); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art()); + let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + members.push(Arc::new(clip)); + } + if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) { + *children = members; + } + let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get); + let empty = Point::new(900.0, 900.0); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let first = evaluated(); + assert!(hit_test(&d, empty, HitOptions::default()).is_none()); + let again = evaluated() - first; + assert!(again < groups / 8, "{again} of {groups} regions evaluated again"); +} + +/// Every test of a clip group by its clipping path follows the region a live effect moved it to: +/// the selected art hidden by the mask, a click into a group holding the clip group, the locked +/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer +/// whose Preview is off, which is clicked in outline while the layer above clips by its region. +#[test] +fn every_clip_test_follows_the_moved_region() { + set_clip_region(moved_clip_region); + let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0)); + let mut d = Document::new(300.0, 200.0); + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let (g, art_id) = (d.alloc_id(), art.id); + let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]); + clip.set_clips(true); + let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + d.insert(Some(l), 0, outer.clone()).unwrap(); + let opt = HitOptions::default(); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place"); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region"); + let symbols = d.symbol_boxes(); + assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill)); + assert_eq!(hit_any(&outer, own, opt, &symbols), None); + d.node_mut(art_id).unwrap().locked = true; + assert_eq!(locked_objects_at(&d, moved, opt), [art_id]); + assert!(locked_objects_at(&d, own, opt).is_empty()); + + // A clipping layer holding the mask and a sublayer whose Preview is off, with the art. + let mut d = Document::new(300.0, 200.0); + let top = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(test_move()); + let art_id = art.id; + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind { + (*children, *preview) = (vec![Arc::new(art)], false); + } + d.insert(Some(top), 0, sublayer).unwrap(); + d.insert(Some(top), 0, mask).unwrap(); + d.node_mut(top).unwrap().set_clips(true); + // The art's top edge, at the clipping path's own place and in the moved region. + let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5)); + assert!(hit_test(&d, own, opt).is_none()); + assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id)); + assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id)); + assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None); +} + /// The art a mask hides counts only for a selected object: there a click hits nothing, and the /// selection tools grab the selection by that art. Not where the art shows (the click hits it), /// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index fb6e8de8d9..9d34150a88 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -211,7 +211,9 @@ impl Node { /// A quick box round everything the object can paint, for culling clicks: paths and compound /// paths grow their geometric bounds by the farthest their strokes can reach from any path - /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in + /// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a + /// clipping layer's box takes in the region that the live geometry effects of its clipping + /// path give it ([`crate::hit::set_clip_region`]). An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box @@ -261,6 +263,11 @@ impl Node { NodeKind::Blend { children, spec } => { vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols)) } + // The live geometry effects of a clipping path can move or grow the region it clips to + // past its plain shape ([`crate::hit::set_clip_region`]). + NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { + vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) + } _ => self.visual(symbols), } } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index a87b47be0e..a1a3fe5293 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,8 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Clicks inside a clip group fall in the region its clipping path's effects give it. + vectorcraft_doc::hit::set_clip_region(reshaped_clip_region); // Clicks find a blend's steps and an envelope's distorted art where the canvas draws them, // evaluated again when the fonts, the hyphenation exceptions or the plug-ins change. vectorcraft_doc::hit::set_live_art(vectorcraft_render::effects::expand_live, || { @@ -491,6 +493,17 @@ impl Session { } } +/// The region clipping path `clip` clips to with its live geometry effects applied +/// ([`vectorcraft_render::effects::clip_outline`]), for clicks inside its clip group; `None` when +/// nothing in it has a visible geometry effect of its own or on a fill or stroke, so that clicks +/// count its plain shapes, type by its frame. +fn reshaped_clip_region(clip: &Node) -> Option> { + use vectorcraft_render::effects::has_geometry; + let mut reshaped = false; + clip.walk(&mut |n| reshaped |= has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(i.effects()))); + reshaped.then(|| vectorcraft_render::effects::clip_outline(clip)) +} + /// Whether some of type `t` is set in a font named (in any case) one of `names`, lowercased. fn sets_in_any(t: &TextObject, names: &HashSet) -> bool { !names.is_empty() && t.runs.iter().any(|r| names.contains(&r.style.font_family.to_lowercase())) diff --git a/crates/engine/src/tests/clip.rs b/crates/engine/src/tests/clip.rs index cbba2f36cc..7d500f6835 100644 --- a/crates/engine/src/tests/clip.rs +++ b/crates/engine/src/tests/clip.rs @@ -119,12 +119,54 @@ fn text_on_top_clips_by_its_glyphs() { assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art)); assert!(b.x1 < 95.0, "{b:?}"); assert_eq!(hit(&s, b.x1 + 3.0, (b.y0 + b.y1) / 2.0), None, "beside the text"); + // An effect that does not reshape it, such as a drop shadow, leaves clicks on its frame. + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "params": {}, "ids": [t.0], "item": null})).unwrap(); + assert_eq!(hit(&s, (b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0), Some(art), "in the counter, with a drop shadow"); // Release gives the text back. select(&mut s, &[g]); s.execute("object.clippingMask.release", &json!({})).unwrap(); assert!(matches!(s.doc().unwrap().doc.node(t).unwrap().kind, NodeKind::Text(_))); } +#[test] +fn clicks_follow_the_region_a_clipping_paths_effects_give_it() { + // Art from 10 to 90 pt, clipped by the artboard's left half, which a Transform effect moves + // 50 pt right: the art shows on the right half, as clicks find it. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap()); + let clip = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 100})).unwrap()); + select(&mut s, &[art, clip]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 50}, "ids": [clip.0], "item": null})).unwrap(); + let r = render(&s); + assert!(opaque(&r, 75, 50) && !opaque(&r, 25, 50), "the canvas clips by the moved region"); + assert_eq!(hit(&s, 75.0, 50.0), Some(art), "where the effect moved the clipping path"); + assert_eq!(hit(&s, 25.0, 50.0), None, "the clipping path's own place"); + let d = &s.doc().unwrap().doc; + let at = |x: f64| vectorcraft_doc::hit::objects_at(d, vectorcraft_geom::Point::new(x, 50.0), Default::default(), None); + assert_eq!(at(75.0), [g]); + assert!(at(25.0).is_empty()); + // A marquee across the art's edge reaches it within the moved region only. + let marquee = |x0: f64, x1: f64| vectorcraft_doc::hit::marquee(d, vectorcraft_geom::Rect::new(x0, 40.0, x1, 60.0), None, true); + assert_eq!(marquee(85.0, 95.0), [art], "the right edge, in the moved region"); + assert!(marquee(5.0, 15.0).is_empty(), "the left edge, in the clipping path's own place"); + + // The same with a sublayer that clips by its first object. + let mut d = (**d).clone(); + let members: Vec<_> = d.node(g).unwrap().children().unwrap().to_vec(); + let top = d.layers[0].id; + d.remove(g).unwrap(); + let mut sublayer = (*d.layers[0]).clone(); + sublayer.id = d.alloc_id(); + if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind { + (*children, *clip) = (members, true); + } + d.insert(Some(top), 0, sublayer).unwrap(); + let leaf = |x: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, 50.0), Default::default()).map(|h| h.leaf); + assert_eq!(leaf(75.0), Some(art)); + assert_eq!(leaf(25.0), None); +} + #[test] fn make_refuses_a_top_object_that_cannot_clip() { let mut s = session(); diff --git a/crates/tools/src/addons/enclosing_lasso.rs b/crates/tools/src/addons/enclosing_lasso.rs index 9b92f0833d..0f674aead9 100644 --- a/crates/tools/src/addons/enclosing_lasso.rs +++ b/crates/tools/src/addons/enclosing_lasso.rs @@ -134,7 +134,7 @@ impl Tool for EnclosingLassoTool { let symbols = cx.doc.symbol_boxes(); let region = (points.len() >= 3).then(|| Region::new(polygon(&points, true))).flatten(); let mut ids = if let Some(region) = region { - enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation) + enclosure_candidates(cx.doc, region.path.bounding_box(), cx.isolation, cx.outline) .into_iter() .filter(|id| cx.doc.node(*id).is_some_and(|n| node_inside(n, &symbols, ®ion))) .collect() diff --git a/crates/tools/src/addons/enclosing_lasso/tests.rs b/crates/tools/src/addons/enclosing_lasso/tests.rs index 836e640306..a8ba79aac7 100644 --- a/crates/tools/src/addons/enclosing_lasso/tests.rs +++ b/crates/tools/src/addons/enclosing_lasso/tests.rs @@ -367,3 +367,25 @@ fn enclosing_lasso_considers_the_geometry_a_visible_compound_paints() { ); } } + +/// A loop around clipped art that the clipping path's own shape holds, but not the region a live +/// effect moved it to, selects the art in Outline view only, which draws the clipping path without +/// its effects. +#[test] +fn outline_view_loops_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let around = [(410.0, 410.0), (490.0, 410.0), (490.0, 490.0), (410.0, 490.0)]; + let gesture = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut tool = crate::create(ID); + tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 410.0, 410.0)); + for &(x, y) in &around[1..] { + tool.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)); + } + tool.pointer(&cx, &PointerEvent::new(PointerKind::Up, 410.0, 490.0)) + }; + assert_eq!(gesture(true), vec![Action::Exec("select.set".into(), json!({"ids": [art.0]}))]); + assert_eq!(gesture(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 3030414b38..cee2c7dfa1 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1608,7 +1608,7 @@ impl DirectSelectionTool { // (members of groups too), each whole, as a click selects one; with an Alt-marquee, every // object it touches, each whole. if enclosed || whole { - let mut touched = vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true); + let mut touched = vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline); let editable = cx.doc.editable(); touched.retain(|id| editable(*id)); let picked = if enclosed { crate::select::inside(cx, r, touched) } else { touched }; @@ -1680,7 +1680,7 @@ impl DirectSelectionTool { } // Objects without anchors to pick (type, images, symbols…) are selected whole when // the marquee touches them, as with the Selection tool (#927). - for id in vectorcraft_doc::hit::marquee(cx.doc, r, cx.isolation, true) { + for id in vectorcraft_doc::hit::marquee_in_view(cx.doc, r, cx.isolation, true, cx.outline) { let whole = cx.doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. })); if whole && !sel.iter().any(|(s, _)| *s == id) && !framed.iter().any(|(f, _)| *f == id) && !meshed.contains(&id) { sel.push((id, vec![])); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index 7ce48bdc1e..32229158af 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2396,3 +2396,26 @@ fn type_on_a_path_shows_and_drags_its_paths_handles() { assert!((v["x"].as_f64().unwrap() - 400.0).abs() < 1e-9, "Shift keeps it straight above its anchor: {v}"); assert!(handles(&ToolContext { handles_multiple: false, ..cx(&d, &s, &p) }).is_empty()); } + +/// An Alt-marquee across clipped art where the clipping path's own shape, but not the region a +/// live effect moved it to, lets it show selects the art in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_clipped_art_by_the_plain_clipping_path() { + let (d, _, art) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let alt = Mods { alt: true, ..Mods::default() }; + let marquee = |outline: bool| { + let c = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = DirectSelectionTool::new(false); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 440.0, 410.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 460.0, 430.0).with_mods(alt)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 460.0, 430.0).with_mods(alt)) + }; + let selects = |a: &[Action]| a.iter().any(|a| matches!(a, Action::Exec(c, v) if c == "select.set" && v["ids"] == json!([art.0]))); + let a = marquee(true); + assert!(selects(&a), "outline: {a:?}"); + let a = marquee(false); + assert!(!selects(&a), "preview: {a:?}"); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 1119bb0764..74e11e4760 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -450,6 +450,36 @@ pub(crate) mod testutil { (d, g, clip, art) } + /// A document with the rectangle of [`doc_with_rect`] and a clip group whose clipping path, + /// (400, 400)–(500, 500), has a live effect that moves the region it clips to 100 pt right + /// (registered with [`vectorcraft_doc::hit::set_clip_region`]), over art at (420, 420)–(480, 480), + /// inside the clipping path's own shape and outside the moved region: the document, the clip + /// group and the art. + pub fn doc_with_moved_clip_region() -> (Document, NodeId, NodeId) { + fn moved(clip: &Node) -> Option> { + let mut moves = false; + clip.walk(&mut |n| moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move")); + if !moves { + return None; + } + Some(vectorcraft_doc::hit::clip_regions(clip).into_iter().next().map(|(mut bp, rule)| { + bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0))); + (bp, rule) + })) + } + vectorcraft_doc::hit::set_clip_region(moved); + let (mut d, _) = doc_with_rect(); + let l = d.layers[0].id; + let (g, clip, art) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut path = Node::path(clip, shapes::rectangle(Rect::new(400.0, 400.0, 500.0, 500.0)), Default::default()); + path.appearance.effects.push(vectorcraft_doc::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }); + let picture = Node::path(art, shapes::rectangle(Rect::new(420.0, 420.0, 480.0, 480.0)), Appearance::default_art()); + let group = + Node::new(g, vectorcraft_doc::NodeKind::Group { children: vec![std::sync::Arc::new(path), std::sync::Arc::new(picture)], clip: true }); + d.insert(Some(l), 1, group).unwrap(); + (d, g, art) + } + /// A new layer of `d`, above the others, with the unpainted rectangle `mask` as its clipping /// mask and `art` clipped by it: the layer and the clipping mask. pub fn add_masked_layer(d: &mut Document, mask: Rect, art: Node) -> (NodeId, NodeId) { diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 70060ebc2b..be767f60c3 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -40,7 +40,7 @@ use std::cell::RefCell; use std::collections::HashMap; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee, objects_at, selected_hidden_at}; +use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, selected_hidden_at}; use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -1125,7 +1125,7 @@ impl Tool for SelectionTool { if r.width() < Self::drag_threshold(cx) && r.height() < Self::drag_threshold(cx) { return if toggle { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] }; } - let touched = marquee(cx.doc, r, cx.isolation, false); + let touched = marquee_in_view(cx.doc, r, cx.isolation, false, cx.outline); let enclosed = marquee_enclosed(cx, enclosed, marquee_direction(cx, start, p, directional_inside)); let ids = if enclosed { inside(cx, r, touched) } else { touched }; let art = Action::Exec(if toggle { "select.toggle" } else { "select.set" }.into(), json!({ "ids": json_ids(&ids) })); diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 63ca697c7d..a04741498d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2558,3 +2558,22 @@ fn outline_view_click_through_an_image_selects_the_path_behind() { assert!(!selects(&a, back), "preview, {picked:?} selected: {a:?}"); } } + +/// A marquee across clipped art where the clipping path's own shape, but not the region a live +/// effect moved it to, lets it show reaches the clip group in Outline view only, which draws the +/// clipping path without its effects. +#[test] +fn outline_view_marquees_measure_a_clip_group_by_its_plain_clipping_path() { + let (d, g, _) = doc_with_moved_clip_region(); + let s = Selection::default(); + let p = paint(); + let marquee = |outline: bool| { + let cx = ToolContext { outline, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 440.0, 410.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 460.0, 430.0)); + t.pointer(&cx, &ev(PointerKind::Up, 460.0, 430.0)) + }; + assert_eq!(marquee(true), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]); + assert_eq!(marquee(false), vec![Action::Exec("select.set".into(), json!({"ids": []}))]); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4c07d6e597..2dcb038f04 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1582,6 +1582,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export, and type used as a clipping path keeps them when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. `doc::hit::tests` and the engine's `tests::clip` cover it. - **Transparency:** three-state Knockout Group (on, neutral, off), Opacity & Mask Define Knockout Shape, Page Isolated Blending and Page Knockout Group, on screen and in SVG/PDF. SVG export writes a knockout group of opaque art plainly, without masks, so shapes meeting edge to edge leave no seam; translucent, blended, masked or brushed art knocks out through masks. Blend modes match the standard formulas on screen, in SVG and in PDF, and non-isolated groups blend with the art below. Flatten Transparency with presets, a dialog and a Flattener Preview panel. Flattening for files without transparency (PDF/X-1a, PDF/X-3) in a CMYK document keeps the inks where it rasterizes, as under an image with see-through pixels: the images it makes hold ink amounts, not screen colours the file would separate again, so a C100 M6 Y41 K3 panel stays C100 M6 Y41 K3 there (#2160, `engine/src/cmd/fileio/tests_pdfx.rs`). On the canvas, the renderer no longer draws the picture of the art below back as an image each time it copies the backdrop of a non-isolated group that blends: it keeps that picture and draws the art that follows over it. At 2880 × 1800, 50 translucent groups with Multiply members take 65 ms a frame instead of 299 ms on 8 threads (`vectorcraft-cli bench`), and the frames have the same pixels. Type inside a group, layer, symbol instance, blend or repeat keeps its opacity, blend mode, opacity mask, Opacity & Mask Define Knockout Shape, own effects, perspective and visibility when the effects on the container outline it. Hidden type with a geometry effect of its own is left out of exports.