diff --git a/crates/draw/src/ui/pen/bezier/hit_test.rs b/crates/draw/src/ui/pen/bezier/hit_test.rs index 5c947df2d..e9a72b255 100644 --- a/crates/draw/src/ui/pen/bezier/hit_test.rs +++ b/crates/draw/src/ui/pen/bezier/hit_test.rs @@ -4,6 +4,7 @@ use craft_behavior::CanvasView; use egui::Pos2; use kurbo::{Affine, CubicBez, ParamCurveNearest as _, Point}; +use super::model::SelectedAnchors; use super::{BezierHit, BezierOverlay, EditPath, HandleSide, HandlesShown, KnotRef, MAX_ANCHORS, PathSelection}; /// A shown direction handle: its path's index, its knot, side and screen end. @@ -46,20 +47,34 @@ impl BezierOverlay<'_> { reach: f32, ) -> Option { // pc: crates/vector/src/edit.rs:337 `hit` (handles, anchors, segments; nearest per kind). - let shown = shown_handles(paths, selection, handles, view); + let shown = shown_handles(paths, selection, &SelectedAnchors::of(selection), handles, view); let anchors = paths.iter().map(EditPath::anchor_count).sum::() <= MAX_ANCHORS; hit_in(paths, &shown, anchors, view, at, reach) } } /// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection -/// does not show. -pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec { - shown_handles_of(paths, sel, sel.selected_len(), handles, view) +/// does not show. `anchors` holds the anchors `sel` selects. +pub(super) fn shown_handles( + paths: &[EditPath], + sel: &PathSelection, + anchors: &SelectedAnchors, + handles: HandlesShown, + view: &CanvasView, +) -> Vec { + shown_handles_of(paths, sel, |path, knot| anchors.has_anchor(path, knot), sel.selected_len(), handles, view) } -/// [`shown_handles`] with `selected` as the number of selected anchors that `OneAnchor` counts. -fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, handles: HandlesShown, view: &CanvasView) -> Vec { +/// [`shown_handles`] with `has_anchor` answering whether a knot of a path is a selected anchor, and `selected` as the +/// number of selected anchors that `OneAnchor` counts. +fn shown_handles_of( + paths: &[EditPath], + sel: &PathSelection, + has_anchor: impl Fn(u64, KnotRef) -> bool, + selected: usize, + handles: HandlesShown, + view: &CanvasView, +) -> Vec { let mut shown = Vec::new(); for (index, path) in paths.iter().enumerate() { let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| { @@ -70,8 +85,8 @@ fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, ha let Some(knot) = path.knot(knot_ref) else { continue }; for side in [HandleSide::In, HandleSide::Out] { let of_selection = || { - sel.has_anchor(path.key, knot_ref) - || next_to_selected_anchor(path, sel, knot_ref, side) + has_anchor(path.key, knot_ref) + || next_to_selected_anchor(path, &has_anchor, knot_ref, side) || segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref)) }; let wanted = match handles { @@ -91,15 +106,22 @@ fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, ha /// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not /// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted. /// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per -/// path, so it reads the other paths' anchor counts from `sel` and copies none of their anchors. -pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec { +/// path, so it reads the listed anchors and their count from `anchors`, the anchors `sel` selects, and copies none. +pub(super) fn other_handles( + paths: &[EditPath], + at: usize, + sel: &PathSelection, + anchors: &SelectedAnchors, + handles: HandlesShown, + view: &CanvasView, +) -> Vec { let Some(path) = paths.get(at) else { return Vec::new() }; - let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key)); - let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() }; - let rest: usize = sel.others.iter().filter(|(key, _)| *key != path.key).map(|(_, rest)| rest.len()).sum(); - let edited = sel.path.filter(|edited| *edited != path.key).map_or(0, |_| sel.anchors.len()); - let own = PathSelection::new(Some(path.key), anchors.clone(), None); - shown_handles_of(std::slice::from_ref(path), &own, anchors.len() + rest + edited, handles, view) + if sel.path == Some(path.key) || handles == HandlesShown::All || !anchors.lists(path.key) { + return Vec::new(); + } + let edited = sel.path.map_or(0, |_| sel.anchors.len()); + let own = PathSelection::new(Some(path.key), Vec::new(), None); + shown_handles_of(std::slice::from_ref(path), &own, |key, knot| anchors.listed_anchor(key, knot), anchors.others_len() + edited, handles, view) .into_iter() .map(|shown| Shown { path: at, ..shown }) .collect() @@ -107,14 +129,14 @@ pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, /// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out /// handle or the next anchor's in handle, across a closed subpath's seam too. -fn next_to_selected_anchor(path: &EditPath, sel: &PathSelection, knot: KnotRef, side: HandleSide) -> bool { +fn next_to_selected_anchor(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool { let Some(sub) = path.subpaths.get(knot.subpath) else { return false }; let count = sub.knots.len(); match side { - HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, next))), + HandleSide::Out => sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next))), HandleSide::In => { let previous = (knot.knot + count.saturating_sub(1)) % count.max(1); - sub.segment_ends(previous).is_some_and(|(previous, _)| sel.has_anchor(path.key, KnotRef::new(knot.subpath, previous))) + sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous))) } } } diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index a480816dc..5c08d39e9 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -37,6 +37,9 @@ use hit_test::{Shown, nearest_on_screen, other_handles, shown_handles}; pub(crate) use mark::paint_mark; pub use mark::{AnchorsShown, HitMark, SegmentMark}; use mark::{Fill, paint_handle, segment_path, stroke}; +use model::SelectedAnchors; +#[cfg(all(test, feature = "screen-testing"))] +pub(crate) use model::reads; pub use model::{AnchorDelete, EditPath, EditSubpath, HandleSide, Knot, KnotRef, PathEdit, PathSelection}; pub use style::BezierStyle; pub use words::BezierWords; @@ -381,6 +384,8 @@ struct Scene { items: Vec, /// Over [`MAX_ANCHORS`] or hidden: outlines only. limited: bool, + /// The anchors the selection selects (none when `limited`). + selected: SelectedAnchors, } /// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's @@ -470,10 +475,12 @@ impl<'a> BezierOverlay<'a> { let limited = self.anchors == AnchorsShown::Hidden || paths.iter().map(EditPath::anchor_count).sum::() > MAX_ANCHORS; let mut items = Vec::new(); if limited { - return Scene { items, limited }; + return Scene { items, limited, selected: SelectedAnchors::default() }; } + let selected = SelectedAnchors::of(self.selection); let near = rect.expand(reach); - let shown = if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, self.handles, view) }; + let shown = + if self.anchors == AnchorsShown::Curvature { Vec::new() } else { shown_handles(paths, self.selection, &selected, self.handles, view) }; let mut handles = shown.iter().peekable(); for (at, path) in paths.iter().enumerate() { let count = path.anchor_count(); @@ -551,7 +558,7 @@ impl<'a> BezierOverlay<'a> { } } } - Scene { items, limited } + Scene { items, limited, selected } } /// Whether the press on `item` is the tool's. @@ -1308,7 +1315,7 @@ impl Component for BezierOverlay<'_> { for item in &scene.items { let press = self.takes(item); let keyboard = item.kind != Kind::Segment && item.shown && focusable; - let selected = item.kind == Kind::Anchor && self.selection.has_anchor(item.key, item.knot); + let selected = item.kind == Kind::Anchor && scene.selected.has_anchor(item.key, item.knot); let part = cx.part(item.part(), item.shape.clone()).priority(item.priority()); let part = if press { part.sense(PRESS) } else { part }; let part = if keyboard { @@ -1416,7 +1423,7 @@ impl Component for BezierOverlay<'_> { draw_end(path, item.knot, item.at, fill); } Kind::Anchor if item.shown => { - let fill = if self.selection.draws_selected(path.key, item.knot) { + let fill = if scene.selected.draws_selected(path.key, item.knot) { Fill::Path(style.line) } else { Fill::Style(if cx.part_if_declared(item.part()).is_some() { @@ -1433,7 +1440,7 @@ impl Component for BezierOverlay<'_> { // The handles of anchors selected in paths the overlay does not edit: drawn, never parts. if !circles { for (at, path) in paths.iter().enumerate() { - for shown in other_handles(paths, at, self.selection, self.handles, &view) { + for shown in other_handles(paths, at, self.selection, &scene.selected, self.handles, &view) { draw_end(path, shown.knot, shown.at, Fill::Style(cx.resolve(handle_fill))); } } diff --git a/crates/draw/src/ui/pen/bezier/model.rs b/crates/draw/src/ui/pen/bezier/model.rs index f8889e462..d95f1d053 100644 --- a/crates/draw/src/ui/pen/bezier/model.rs +++ b/crates/draw/src/ui/pen/bezier/model.rs @@ -2,6 +2,8 @@ //! the overlays report. The host converts its own path type to these each frame and applies the //! edits to its own. +use std::collections::HashSet; + use craft_theme::Srgba; use kurbo::{BezPath, CubicBez, Point, Vec2}; @@ -235,6 +237,8 @@ impl PathSelection { /// Whether `knot` of `path` draws selected: a selected anchor of the path being edited, or one listed in `others`. pub fn draws_selected(&self, path: u64, knot: KnotRef) -> bool { + #[cfg(all(test, feature = "screen-testing"))] + reads::add(self.others.iter().map(|(key, anchors)| if *key == path { 1 + anchors.len() } else { 1 }).sum()); self.has_anchor(path, knot) || self.others.iter().any(|(key, anchors)| *key == path && anchors.contains(&knot)) } @@ -245,6 +249,8 @@ impl PathSelection { /// Whether `knot` of `path` is a selected anchor. pub fn has_anchor(&self, path: u64, knot: KnotRef) -> bool { + #[cfg(all(test, feature = "screen-testing"))] + reads::add(if self.path == Some(path) { self.anchors.len() } else { 0 }); self.path == Some(path) && self.anchors.contains(&knot) } @@ -268,6 +274,79 @@ impl PathSelection { } } +/// The anchors a [`PathSelection`] selects, gathered into sets once so that the overlay asks about each knot it lays +/// out or draws without searching the selection's lists. A path that `others` lists more than once is treated as one +/// path holding every anchor listed for it. +#[derive(Default)] +pub(super) struct SelectedAnchors { + path: Option, + anchors: HashSet, + others: HashSet<(u64, KnotRef)>, + listed: HashSet, + others_len: usize, +} + +impl SelectedAnchors { + /// The anchors `sel` selects. + pub(super) fn of(sel: &PathSelection) -> Self { + let others_len = sel.others.iter().map(|(_, anchors)| anchors.len()).sum(); + #[cfg(all(test, feature = "screen-testing"))] + reads::add(sel.anchors.len() + others_len); + Self { + path: sel.path, + anchors: sel.anchors.iter().copied().collect(), + others: sel.others.iter().flat_map(|(key, anchors)| anchors.iter().map(|knot| (*key, *knot))).collect(), + listed: sel.others.iter().map(|(key, _)| *key).collect(), + others_len, + } + } + + /// Whether `knot` of `path` is a selected anchor of the path being edited ([`PathSelection::has_anchor`]). + pub(super) fn has_anchor(&self, path: u64, knot: KnotRef) -> bool { + self.path == Some(path) && self.anchors.contains(&knot) + } + + /// Whether `knot` of `path` draws selected ([`PathSelection::draws_selected`]). + pub(super) fn draws_selected(&self, path: u64, knot: KnotRef) -> bool { + self.has_anchor(path, knot) || self.others.contains(&(path, knot)) + } + + /// Whether `knot` is one of the anchors `others` lists for `path`. + pub(super) fn listed_anchor(&self, path: u64, knot: KnotRef) -> bool { + self.others.contains(&(path, knot)) + } + + /// Whether `others` lists `path`, with or without anchors. + pub(super) fn lists(&self, path: u64) -> bool { + self.listed.contains(&path) + } + + /// The number of anchors `others` lists over every path. + pub(super) fn others_len(&self) -> usize { + self.others_len + } +} + +/// The number of entries of selection anchor lists read on this thread, for trials that count the overlay's work. +#[cfg(all(test, feature = "screen-testing"))] +pub(crate) mod reads { + use std::cell::Cell; + + thread_local! { + static READS: Cell = const { Cell::new(0) }; + } + + /// Counts `n` entries read. + pub(crate) fn add(n: usize) { + READS.with(|reads| reads.set(reads.get() + n)); + } + + /// The entries read since the last call, and starts the count again. + pub(crate) fn take() -> usize { + READS.with(|reads| reads.replace(0)) + } +} + /// Which of a knot's two direction handles. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 994fdcbea..7db3cbe69 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -489,6 +489,30 @@ fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_a ); } +// A frame reads the selection's anchor lists a number of times that grows with the selection, not with its square: +// doubling the selected anchors of the edited path and the number of other paths listed at most doubles the entries +// read (a search of the lists for each anchor laid out or drawn quadruples them). +#[trial] +fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() { + let reads_for = |n: usize| { + let knot = |i: usize| Knot::smooth(p(20.0 + (i % 40) as f64 * 12.0, 20.0 + (i / 40) as f64 * 12.0), p(26.0 + (i % 40) as f64 * 12.0, 20.0)); + let edited = EditPath::new(1, vec![EditSubpath::new((0..n).map(knot).collect(), false)]); + let others: Vec = + (0..n).map(|i| EditPath::new(2 + i as u64, vec![EditSubpath::new((0..4).map(|k| knot(i * 4 + k)).collect(), true)])).collect(); + let mut selection = PathSelection::new(Some(1), (0..n).map(kr).collect(), None); + for other in &others { + selection = selection.also(other.key, (0..4).map(kr).collect()); + } + let mut h = harness(std::iter::once(edited).chain(others).collect()); + craft_draw::ui::pen::bezier::reads::take(); + h.update(|st| st.selection = selection); + craft_draw::ui::pen::bezier::reads::take() + }; + let (small, large) = (reads_for(60), reads_for(120)); + assert!(small > 0, "the frame reads the selection"); + assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120"); +} + // Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at. // `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object.