diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 93b690ccf8..5885a0ff54 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)) @@ -1048,7 +1207,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// group's original shapes, which the canvas does not draw, and guide paths with /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not -/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`. +/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or +/// no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { struct Find<'a> { art: &'a InstanceArt<'a>, @@ -1057,35 +1218,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> symbols: &'a SymbolBoxes<'a>, } impl Find<'_> { - fn hit(&self, n: &Node, whole: Option) -> bool { - self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some()) + fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> bool { + self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some()) } fn skips_guide(&self, n: &Node) -> bool { self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. }) } - fn find(&self, n: &Node, path: &mut Vec, whole: Option) -> bool { + /// `outline`: the view is in Outline, or a layer around `n` has Preview off. + fn find(&self, n: &Node, path: &mut Vec, whole: Option, outline: bool) -> bool { if !n.visible || n.locked || n.is_template() || self.skips_guide(n) { return false; } - let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) }; + let outline = outline || previews_off(n); + let opt = HitOptions { outline, ..self.opt }; + let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) }; if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH { - return self.hit(n, whole); + return self.hit(n, whole, opt); } let whole = self.art.whole(n, whole); if n.clips() && let Some(first) = children.first() { let Some(clip) = self.art.place_unclipped(first, whole) else { return false }; - if self.opt.clip_outlines - && first.visible - && !first.locked - && !self.skips_guide(first) - && clip_outline(&clip, self.p, self.opt).is_some() + if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some() { path.push(0); return true; } - if !clip_contains(&clip, self.p) { + if !clip_contains(&clip, self.p, outline) { return false; } } @@ -1096,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> } let Ok(i) = u32::try_from(i) else { continue }; path.push(i); - if self.find(c, path, whole) { + if self.find(c, path, whole, outline) { return true; } path.pop(); @@ -1107,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> let art = InstanceArt::of(doc, inst)?; let symbols = doc.symbol_boxes(); let mut path = vec![]; - Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path) + let outline = opt.outline || below_preview_off(doc, inst, opt.scope); + Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path) +} + +/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks +/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it +/// does not count. +fn below_preview_off(doc: &Document, n: &Node, scope: Option) -> bool { + let Some(chain) = doc.ancestry(n.id) else { return false }; + let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1); + chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off)) } /// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]), @@ -1116,11 +1286,23 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> /// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An /// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut /// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`] -/// picks it. +/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it +/// has any. /// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies. pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option { + symbol_part_outline_in_view(doc, inst, path, HitOptions::default()) +} + +/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view +/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the +/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the +/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as +/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around +/// the object leave no region. +pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { let art = InstanceArt::of(doc, inst)?; let part = crate::symbol_overrides::part(&art.art, path)?; + let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; @@ -1128,24 +1310,40 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< for &i in path { let children = n.children()?; whole = art.whole(n, whole); + outline = outline || previews_off(n); if i != 0 && n.clips() && let Some(first) = children.first() - && let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds() { - match meet(Some(clip), limit) { - Some(r) => limit = Some(r), - None => return Some(out), - } + let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) }; + limit = within; } n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, whole)?, limit, &mut out); + outline_within(&art.place(part, whole)?, limit, outline, &mut out); Some(out) } -/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one. -fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { +/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the +/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no +/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art +/// is drawn: the effects leave no region, or the box is outside `limit`. +fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option> { + use vectorcraft_geom::kurbo::Shape; + let region = if outline { None } else { clip_region(clip) }; + let bounds = match region.as_deref() { + Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()), + Some(_) => return None, + None => clip.geometric_bounds(), + }; + match bounds { + Some(b) => meet(Some(b), limit).map(Some), + None => Some(limit), + } +} + +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. +fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; if let Some(pd) = n.path_data() { match limit { @@ -1159,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option, out: &mut BezPath) { out.extend(b.to_path(0.1)); } let Some(children) = n.children() else { return }; + let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { - let inner = match first.geometric_bounds() { - Some(c) => match meet(Some(c), limit) { - Some(r) => Some(r), - None => return, - }, - None => limit, - }; - rest.iter().for_each(|c| outline_within(c, inner, out)); + let Some(inner) = limit_within(first, limit, outline) else { return }; + rest.iter().for_each(|c| outline_within(c, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, out)); + children.iter().for_each(|c| outline_within(c, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. @@ -1248,31 +1441,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 @@ -1281,42 +1491,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| { @@ -1325,18 +1581,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); } } @@ -1344,36 +1612,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 a4d1cbbf10..dde7365424 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -110,6 +110,252 @@ 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; with one named `test.empty`, no region left to clip +/// by; without either, no geometry effect. +fn moved_clip_region(clip: &Node) -> Option> { + let (mut moves, mut empty) = (false, false); + clip.walk(&mut |n| { + moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move"); + empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty"); + }); + if empty { + return Some(None); + } + 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, @@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() { assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}"); } +/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect +/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and +/// when Preview is off for the layer in the art or for the layer the instance is on, the plain +/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline. +#[test] +fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() { + set_clip_region(moved_clip_region); + // The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that + // layer and of the document layer the instance is on. + let instance = |effect: &str, preview: [bool; 2]| { + let mut d = Document::new(300.0, 200.0); + if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind { + *p = preview[1]; + } + let l = d.layers[0].id; + let (mut mask, art) = half_clipped(&mut d); + mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() }); + let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2)); + if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind { + (*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]); + } + layer.set_clips(true); + let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]); + d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) }); + let inst = d.alloc_id(); + d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap(); + (d, inst) + }; + let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| { + let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap(); + vectorcraft_geom::kurbo::Shape::bounding_box(&o) + }; + let opt = HitOptions::default(); + let (d, inst) = instance("test.move", [true, true]); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region"); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was"); + let b = outline_box(&d, inst, opt); + assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}"); + let b = outline_box(&d, inst, HitOptions { outline: true, ..opt }); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}"); + // With Preview off, the art's top edge counts within the plain clipping path. + for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] { + let (d, inst) = instance("test.move", preview); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}"); + assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}"); + let b = outline_box(&d, inst, opt); + assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}"); + } + // An effect that leaves the clipping path no region hides the art: no pick and no outline. + let (d, inst) = instance("test.empty", [true, true]); + let n = d.node(inst).unwrap(); + assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None); + assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index efb006afed..1aad3a27cf 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/effects/src/clip.rs b/crates/effects/src/clip.rs index c5e11c648f..cd9d67fc43 100644 --- a/crates/effects/src/clip.rs +++ b/crates/effects/src/clip.rs @@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData}; /// fills and strokes: the region is then the union of the paths they give, as an export bakes them. /// `None` when there is nothing to clip by (the clipped art is then hidden). pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> { - match clip_effects_applied(clip, true, || true) { - Some(m) => m.clip_outline(Some(&outline_text), &unite), - None => clip.clip_outline(Some(&outline_text), &unite), - } + reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite)) +} + +/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing +/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a +/// group or layer does not clip, so its effects are not counted. +pub fn reshaped_clip_outline(clip: &Node) -> Option> { + clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite)) } /// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9934ea026e..a326c85cf2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -72,7 +72,7 @@ pub use bake::{ StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake, }; -pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent}; +pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index e25cde77cc..1244b77432 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(vectorcraft_render::effects::reshaped_clip_outline); // 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, || { diff --git a/crates/engine/src/tests/clip.rs b/crates/engine/src/tests/clip.rs index cbba2f36cc..87af67d95d 100644 --- a/crates/engine/src/tests/clip.rs +++ b/crates/engine/src/tests/clip.rs @@ -119,12 +119,80 @@ 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 a_hidden_member_of_a_clipping_group_leaves_clicks_on_the_type_frame() { + // The clipping path is a group of an "O" and a hidden rectangle with a Transform effect. The + // hidden rectangle does not clip, so clicks inside the clip group still count the type by its + // frame, the counter of the "O" included. + let mut s = session(); + let art = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()); + let t = id_of(&s.execute("text.create", &json!({"x": 5, "y": 80, "text": "O", "size": 90})).unwrap()); + let b = s.doc().unwrap().doc.node(t).unwrap().geometric_bounds().unwrap(); + let r = id_of(&s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 10, "height": 10})).unwrap()); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 20}, "ids": [r.0], "item": null})).unwrap(); + select(&mut s, &[art, t]); + let g = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + // Make Clipping Mask takes no group on top, so the group goes in place of the type. + let mut d = (*s.doc().unwrap().doc).clone(); + let mut rect = (*d.remove(r).unwrap()).clone(); + rect.visible = false; + let text = d.remove(t).unwrap(); + let group = vectorcraft_doc::Node::group(d.alloc_id(), vec![text, Arc::new(rect)]); + d.insert(Some(g), 0, group).unwrap(); + let leaf = |x: f64, y: f64| vectorcraft_doc::hit::hit_test(&d, vectorcraft_geom::Point::new(x, y), Default::default()).map(|h| h.leaf); + let middle = ((b.x0 + b.x1) / 2.0, (b.y0 + b.y1) / 2.0); + assert_eq!(leaf(middle.0, middle.1), Some(art), "in the counter, inside the frame"); + assert_eq!(leaf(b.x1 + 3.0, middle.1), None, "beside the 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..69230dc050 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -55,7 +55,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline}; +use vectorcraft_doc::hit::{Hit, HitKind, compound_part_at, hit_test, selected_hidden_at, symbol_part_at, symbol_part_outline_in_view}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overrides}; use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; @@ -1029,7 +1029,7 @@ impl Tool for DirectSelectionTool { out.extend(self.mesh.overlays(cx, &|id| cx.selection.contains(id))); if !self.group { if let Some(sp) = &cx.selection.symbol_part - && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline(cx.doc, n, &sp.path)) + && let Some(path) = cx.doc.node(sp.instance).and_then(|n| symbol_part_outline_in_view(cx.doc, n, &sp.path, cx.hit_options())) { out.push(Overlay::Path { path, color: cx.doc.layer_color(sp.instance), width: 1.0, dashed: false }); } @@ -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 29cf0466e1..93f71431c1 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 ef8e3d4817..f63be1193e 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}; @@ -1157,7 +1157,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 b7af316571..3a47a9c85e 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2646,3 +2646,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 d4866e33dd..25339b9c5d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1640,7 +1640,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. - **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. + 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. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects 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. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `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.