Merge pull request #4306 from dotCooCoo/fix/anchor-overlay-one-mesh

BezierOverlay: Anchors declares no part per anchor and a pass lays out its scene once
This commit is contained in:
BFlat authored and GitHub committed 2026-11-30 02:53:13 +07:00
commit 17af07fdf3
2 files changed
+138 -13

No files matched your search

+87 -12
View File
@@ -11,6 +11,8 @@ mod style;
mod tools;
mod words;
use std::rc::Rc;
use craft_behavior::geometry::{SelectionOperation, axis_or_diagonal};
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2};
use craft_behavior::{
@@ -72,7 +74,8 @@ pub enum BezierTool {
/// handles; a handle drag moves that handle alone; a drag on a straight segment bends it, or moves the whole path
/// when every anchor is selected.
Convert,
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools).
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). The overlay declares no part and no
/// AccessKit object for its anchors and handles.
Anchors,
/// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
/// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does
@@ -394,6 +397,44 @@ struct Scene {
selected: SelectedAnchors,
}
/// A scene and what it was laid out from, kept on the overlay so that the later steps of the same pass reuse it.
struct Laid {
scene: Rc<Scene>,
paths: Vec<EditPath>,
view: CanvasView,
rect: Rect,
reach: f32,
tool: BezierTool,
}
impl Laid {
/// Whether the scene is the one of `paths` with these view, rect, reach and tool: a step that sees other paths (an
/// edit, a reset or the end of a press changed them) lays out its own.
fn matches(&self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32, tool: BezierTool) -> bool {
self.view == *view && self.rect == rect && self.reach.to_bits() == reach.to_bits() && self.tool == tool && self.paths == paths
}
}
/// The number of scenes the overlay laid out on this thread, for trials that count the overlay's work.
#[cfg(all(test, feature = "screen-testing"))]
pub(crate) mod laid {
use std::cell::Cell;
thread_local! {
static LAID: Cell<usize> = const { Cell::new(0) };
}
/// Counts one scene laid out.
pub(crate) fn add() {
LAID.with(|laid| laid.set(laid.get() + 1));
}
/// The scenes laid out since the last call, and starts the count again.
pub(crate) fn take() -> usize {
LAID.with(|laid| laid.replace(0))
}
}
/// Paths with anchors and direction handles over a canvas, edited by the pointer and the keyboard as PhotoCraft's
/// Direct Selection and Convert Point tools edit them. The value is the paths: a drag proposes them with the gesture's
/// edit applied and Escape restores the start; [`BezierOutput::change`] carries the gesture's [`PathEdit`] from its
@@ -420,7 +461,10 @@ struct Scene {
/// [`path_options`](Self::path_options) change the look; [`hit_test`](Self::hit_test) answers the press priority
/// without a pass.
/// - The units and the zero point of the AccessKit values come from the canvas, and snapping of a dragged point is
/// the canvas's [`Snap`].
/// the canvas's [`Snap`]. Under [`BezierTool::Anchors`] the anchors and handles have no parts and no AccessKit
/// objects.
/// - A pass lays out its anchors, handles and segments once and its steps share them; a step that sees other paths
/// (after an edit or a reset) lays them out again.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
#[component(canvas_control, content_painter)]
pub struct BezierOverlay<'a> {
@@ -447,6 +491,8 @@ pub struct BezierOverlay<'a> {
report: Report,
marquee: Option<DocRect>,
hover_mark: Option<BezierHit>,
/// The scene the latest step of this pass laid out.
laid: Option<Laid>,
}
impl<'a> BezierOverlay<'a> {
@@ -464,6 +510,7 @@ impl<'a> BezierOverlay<'a> {
report: Report::default(),
marquee: None,
hover_mark: None,
laid: None,
}
.label(label)
}
@@ -483,6 +530,8 @@ impl<'a> BezierOverlay<'a> {
if limited {
return Scene { items, limited, selected: SelectedAnchors::default() };
}
#[cfg(all(test, feature = "screen-testing"))]
laid::add();
let selected = SelectedAnchors::of(self.selection);
let near = rect.expand(reach);
let shown =
@@ -567,6 +616,17 @@ impl<'a> BezierOverlay<'a> {
Scene { items, limited, selected }
}
/// The scene of `paths`: the one an earlier step of this pass laid out from equal paths with the same view, rect,
/// reach and tool, else a new one, kept for the later steps.
fn scene_of(&mut self, paths: &[EditPath], view: &CanvasView, rect: Rect, reach: f32) -> Rc<Scene> {
if let Some(laid) = self.laid.as_ref().filter(|laid| laid.matches(paths, view, rect, reach, self.tool)) {
return Rc::clone(&laid.scene);
}
let scene = Rc::new(self.scene(paths, view, rect, reach));
self.laid = Some(Laid { scene: Rc::clone(&scene), paths: paths.to_vec(), view: *view, rect, reach, tool: self.tool });
scene
}
/// Whether the press on `item` is the tool's.
fn takes(&self, item: &Item) -> bool {
self.tool.takes(&item.proxy(), item.interior, item.straight)
@@ -1304,20 +1364,24 @@ impl Component for BezierOverlay<'_> {
/// The anchors and shown handles in view, then the segments the tool takes, and under Direct Selection one part
/// below them all for the marquee. The anchors and handles are one roving group in keyboard order: one Tab stop,
/// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves.
/// arriving at the first selected anchor. The Page keys, Home and End are the overlay's own moves. Anchors declares
/// none.
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
let held = cx.press_slot::<Held>();
self.press_tool(held.as_ref());
let Some(space) = canvas_space(&cx.env) else { return };
let reach = cx.style.reach;
let scene = match &held {
Some(held) => self.scene(&held.start, &space.view, rect, reach),
Some(held) => self.scene_of(&held.start, &space.view, rect, reach),
None => {
let Some(paths) = cx.value() else { return };
self.scene(paths, &space.view, rect, reach)
self.scene_of(paths, &space.view, rect, reach)
}
};
let focusable = self.tool != BezierTool::Anchors;
// Anchors draws the anchors and handles without parts: nothing of them takes a press or the keyboard.
if self.tool == BezierTool::Anchors {
return;
}
if self.tool == BezierTool::Direct && !scene.limited {
cx.part(MARQUEE, HitShape::Rect(rect))
.sense(Sense::DRAG.union(Sense::CLICK).union(Sense::TAKE_FOCUS))
@@ -1333,7 +1397,7 @@ impl Component for BezierOverlay<'_> {
let arrival = self.selection.path.zip(self.selection.anchors.first().copied());
for item in &scene.items {
let press = self.takes(item);
let keyboard = item.kind != Kind::Segment && item.shown && focusable;
let keyboard = item.kind != Kind::Segment && item.shown;
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 };
@@ -1349,7 +1413,7 @@ impl Component for BezierOverlay<'_> {
part.selected();
}
}
if focusable && scene.items.iter().any(|item| item.kind != Kind::Segment && item.shown) {
if scene.items.iter().any(|item| item.kind != Kind::Segment && item.shown) {
cx.roving(Roving::new(NavShape::Flat).home_end(false));
}
}
@@ -1360,7 +1424,7 @@ impl Component for BezierOverlay<'_> {
let held = cx.press_slot::<Held>().clone();
let Some(paths) = held.as_ref().map(|held| held.start.clone()).or_else(|| cx.value().cloned()) else { return };
self.press_tool(held.as_ref());
let scene = self.scene(&paths, &space.view, cx.rect, cx.style.reach);
let scene = self.scene_of(&paths, &space.view, cx.rect, cx.style.reach);
self.run_pointer(cx, &space, &scene, &paths);
self.run_keys(cx, &space, &scene, &paths);
}
@@ -1368,7 +1432,7 @@ impl Component for BezierOverlay<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let (Some(space), Some(paths)) = (canvas_space(&cx.env), cx.value()) else { return };
let (view, style) = (space.view, &cx.style);
let scene = self.scene(paths, &view, cx.rect, style.reach);
let scene = self.scene_of(paths, &view, cx.rect, style.reach);
let options = self.path_options;
let thickness = options.and_then(|options| options.thickness);
let option_color =
@@ -1484,10 +1548,21 @@ impl Component for BezierOverlay<'_> {
}
/// A graphics object per anchor and shown handle, named "Anchor 3 of 12", "In handle" and "Out handle" and valued
/// in the canvas's units. None above [`MAX_ANCHORS`].
/// in the canvas's units. None above [`MAX_ANCHORS`] or under [`BezierTool::Anchors`].
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
if self.tool == BezierTool::Anchors {
return;
}
let (Some(space), Some(paths)) = (canvas_space(&cx.env), cx.value()) else { return };
let scene = self.scene(paths, &space.view, cx.rect, cx.style.reach);
let (rect, reach) = (cx.rect, cx.style.reach);
let built;
let scene = match self.laid.as_ref().filter(|laid| laid.matches(paths, &space.view, rect, reach, self.tool)) {
Some(laid) => &*laid.scene,
None => {
built = self.scene(paths, &space.view, rect, reach);
&built
}
};
let (words, units, rulers) = (cx.words::<BezierWords>(), cx.env.units(), space.rulers());
for item in scene.items.iter().filter(|item| item.kind != Kind::Segment && item.shown) {
let Some(knot) = paths[item.path].knot(item.knot) else { continue };
+51 -1
View File
@@ -2,7 +2,7 @@
use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets};
use craft_behavior::kurbo::{ParamCurve as _, Point, Size, Vec2};
use craft_behavior::{CanvasView, EditEvent};
use craft_behavior::{CanvasView, EditEvent, PartKey};
use craft_draw::ui::{
AnchorDelete, AnchorTool, AnchorsShown, BezierHit, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleSide, HandlesShown, Knot, KnotRef,
PathEdit, PathSelection, PathTool, SegmentMark,
@@ -11,6 +11,7 @@ use craft_ui::canvas::{Canvas, Guide, Momentary, NavigationOptions, Snap, ToolHo
use craft_ui::canvas_controls::Guides;
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft_ui::primitives::cancel_press_of;
use craft_ui::runtime::access::Role;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Id, Pos2, Vec2 as ScreenVec, vec2};
use std::cell::RefCell;
@@ -530,6 +531,55 @@ fn a_frame_reads_the_selections_anchor_lists_in_proportion_to_the_selection() {
assert!(large < small * 3, "{small} entries read for 60 selected paths, {large} for 120");
}
// A pass lays out the anchors, handles and segments once for all of its steps (parts, update, paint, access): a frame
// at rest lays out one scene per pass.
#[trial]
fn a_pass_lays_out_the_overlays_scene_once() {
for tool in [BezierTool::Direct, BezierTool::Anchors] {
let mut h = two_paths();
h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)])));
craft_draw::ui::pen::bezier::laid::take();
h.fixture.frame(Vec::new());
let (laid, passes) = (craft_draw::ui::pen::bezier::laid::take(), h.fixture.passes());
assert!(passes > 0, "{tool:?}: the frame ran");
assert_eq!(laid, passes, "{tool:?}: {laid} scenes laid out in {passes} passes");
}
}
// A step that sees other paths than the one before it lays out its own scene: the pass of an arrow nudge paints the
// moved anchor where the next frame, at rest, paints it.
#[trial]
fn the_pass_of_an_edit_paints_the_edited_anchors() {
let mut h = two_paths();
h.update(|st| st.selection = sel(1, &[(0, 1)]));
h.fixture.key(egui::Key::Tab, egui::Modifiers::NONE).key(egui::Key::Tab, egui::Modifiers::NONE).settle();
let arrow = egui::Event::Key { key: egui::Key::ArrowRight, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let nudged = format!("{:?}", h.fixture.frame_shapes_with(vec![arrow]));
assert!(matches!(h.last_change(), Some(PathEdit::MoveAnchors { path: 1, .. })), "{:?}", h.last_change());
let rest = format!("{:?}", h.fixture.frame_shapes());
assert_eq!(nudged, rest, "the nudge's pass paints the anchors of the nudged paths");
}
// Under Anchors the overlay draws the anchors without declaring them: no part of an anchor and no AccessKit object,
// where Direct Selection declares both. The anchors still draw.
#[trial]
fn anchors_draws_its_anchors_with_no_part_and_no_accesskit_object() {
for (tool, declared) in [(BezierTool::Direct, true), (BezierTool::Anchors, false)] {
let mut h = two_paths();
h.update(|st| (st.tool, st.selection) = (tool, sel(1, &[(0, 1)])));
let id = h.state.borrow().id;
assert_eq!(h.fixture.part_rect(id, PartKey::new("anchor").at(0)).is_some(), declared, "{tool:?}: the first anchor's part");
let objects = h.fixture.by_role(Role::GRAPHICS_OBJECT).len();
assert_eq!(objects > 0, declared, "{tool:?}: {objects} AccessKit objects");
}
let shapes = |anchors: AnchorsShown| {
let mut h = two_paths();
h.update(|st| (st.tool, st.anchors, st.selection) = (BezierTool::Anchors, anchors, sel(1, &[(0, 1)])));
h.fixture.frame_shapes().len()
};
assert!(shapes(AnchorsShown::All) > shapes(AnchorsShown::Hidden), "Anchors draws the anchors that outlines only leave out");
}
// 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.