Canvas tools declare their nudges: a tool that claims them (ToolClaims::nudges) describes what its arrows move, the host declares Increment and Decrement on that node and turns them into nudges. The Ruler (its line), the Artboard tool (the selected boards outside a drag) and the annotation Select tool (its selection) claim them

This commit is contained in:
aiongg
2026-11-12 14:32:42 +00:00
parent 11758c80f0
commit 446ad245aa
9 changed files with 175 additions and 25 deletions
+19 -3
View File
@@ -197,7 +197,12 @@ impl CanvasTool for ArtboardTool {
}
fn claims(&self) -> ToolClaims {
if self.selected.is_empty() { ToolClaims::NONE } else { ToolClaims::NONE.deletes() }
let movable = self.drag.is_none() && self.selected.iter().any(|&index| self.items.get(index).is_some_and(|item| !item.locked));
match (self.selected.is_empty(), movable) {
(true, _) => ToolClaims::NONE,
(false, false) => ToolClaims::NONE.deletes(),
(false, true) => ToolClaims::NONE.deletes().nudges(),
}
}
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
@@ -209,9 +214,10 @@ impl CanvasTool for ArtboardTool {
}
}
/// The board being drawn, or outside a drag the selected boards the arrows move.
fn access(&self, cx: &ToolContext<'_>) -> Option<ToolAccess> {
let drag = self.drag.as_ref().filter(|drag| drag.run.is_some())?;
let rect = drawn_rect(drag.start, drag.at);
let Some(drag) = self.drag.as_ref() else { return self.selection_access() };
let rect = drag.run.as_ref().map(|_| drawn_rect(drag.start, drag.at))?;
let units = cx.units();
let name = cx.words::<ArtboardToolWords>().tool.as_str().to_owned();
Some(ToolAccess::new(name).value(format!("{} x {}", units.pixels(rect.width()), units.pixels(rect.height()))).bounds(rect))
@@ -222,6 +228,16 @@ impl CanvasTool for ArtboardTool {
}
}
impl ArtboardTool {
/// The selected boards as one object: their names and the bounds round them.
fn selection_access(&self) -> Option<ToolAccess> {
let boards: Vec<&ArtboardItem> = self.selected.iter().filter_map(|&index| self.items.get(index)).collect();
let bounds = boards.iter().map(|item| item.rect).reduce(|bounds, rect| bounds.union(rect))?;
let names: Vec<&str> = boards.iter().map(|item| item.name.as_str()).collect();
Some(ToolAccess::new(names.join(", ")).bounds(bounds))
}
}
/// Whether the drag has moved: the preview shows from the first change.
fn pointer_moved(drag: &Drag) -> bool {
drag.start != drag.at
+10 -5
View File
@@ -6,13 +6,13 @@ use super::words::RulerWords;
use craft_behavior::geometry::{Directions, round_to_direction};
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
use craft_behavior::{Granularity, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PartKey, PointerButton, PressPhase, Roving, Sense};
use craft_ui::canvas::{NUDGE, NUDGE_FAR, canvas_space};
use craft_ui::canvas::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_space};
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, PaintUi, PartsCx, Pointer as _, Props as _,
Remember as _, Role, Styled as _, WordSetCx as _,
};
use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::env::Label;
use craft_ui::runtime::env::{Label, Units};
use craft_ui::runtime::focus::KeyUse;
use craft_ui::style::{ComponentStyle, HandleLook, StyleCx};
use egui::{CornerRadius, Rect, Vec2};
@@ -200,9 +200,7 @@ impl Component for RulerOverlay<'_> {
let words = cx.words::<RulerWords>();
let units = cx.env.units();
let rulers = space.rulers();
let length = rulers.x.format_value(&units, line.reading().l1, 0.0);
let angle = units.number(line.reading().angle, 0..=1);
access.value(words.value.fill(&[("length", length.as_str()), ("angle", angle.as_str())]));
access.value(reading_text(&line, &space, &units, &words));
for (part, name) in [(RulerPart::Start, &words.start), (RulerPart::End, &words.end), (RulerPart::Protractor, &words.protractor)] {
let Some(at) = line.point(part) else { continue };
let value = format!("{}, {}", rulers.x.format_value(&units, at.x, 0.0), rulers.y.format_value(&units, at.y, 0.0));
@@ -217,6 +215,13 @@ impl Component for RulerOverlay<'_> {
}
}
/// The line's length and angle as assistive technology reads them, in the canvas's ruler units.
pub(super) fn reading_text(line: &RulerLine, space: &CanvasSpace, units: &Units, words: &RulerWords) -> String {
let length = space.rulers().x.format_value(units, line.reading().l1, 0.0);
let angle = units.number(line.reading().angle, 0..=1);
words.value.fill(&[("length", length.as_str()), ("angle", angle.as_str())])
}
/// The unit vector in document space of an arrow key's direction on screen.
fn nudge_vector(view: &craft_behavior::CanvasView, direction: Vec2) -> DocVec {
let origin = view.rect.center();
+14 -3
View File
@@ -2,11 +2,11 @@
//! line from a press on the background and moves the whole line with the arrow keys.
use super::model::{MIN_LINE, RulerLine, RulerPart};
use super::overlay::{RulerOverlay, moved};
use super::overlay::{RulerOverlay, moved, reading_text};
use super::words::RulerWords;
use craft_behavior::kurbo::Point;
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed};
use craft_ui::canvas::{CanvasTool, NUDGE, NUDGE_FAR, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::canvas::{CanvasTool, NUDGE, NUDGE_FAR, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::canvas_controls::StraightLinePreview;
use craft_ui::contract::{Bind, Show as _};
use craft_ui::primitives::Draw;
@@ -172,7 +172,18 @@ impl CanvasTool for RulerPass<'_> {
}
fn claims(&self) -> ToolClaims {
if self.line.is_some() && self.tool.drag.is_none() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE }
if self.line.is_some() && self.tool.drag.is_none() { ToolClaims::NONE.deletes().nudges() } else { ToolClaims::NONE }
}
/// The line the arrows move, with its length and angle.
fn access(&self, cx: &ToolContext<'_>) -> Option<ToolAccess> {
let (line, space) = (self.line?, cx.space()?);
let words = cx.words::<RulerWords>();
let bounds = [RulerPart::Start, RulerPart::End, RulerPart::Protractor]
.into_iter()
.filter_map(|part| line.point(part))
.fold(craft_behavior::kurbo::Rect::from_points(line.start, line.end), |bounds, at| bounds.union_pt(at));
Some(ToolAccess::new(words.group.as_str()).value(reading_text(&line, &space, &cx.units(), &words)).bounds(bounds))
}
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
+15 -2
View File
@@ -4,7 +4,7 @@ use craft_behavior::geometry::draft::turn_to_45;
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed, PointerButton, SelectionChange};
use craft_keymap::Mods;
use craft_theme::Srgba;
use craft_ui::canvas::{CanvasTool, NUDGE, NUDGE_FAR, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::canvas::{CanvasTool, NUDGE, NUDGE_FAR, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind};
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth};
use craft_ui::runtime::env::Label;
@@ -682,7 +682,20 @@ impl CanvasTool for AnnotateTool {
}
fn claims(&self) -> ToolClaims {
if self.tool == AnnotationTool::Select && !self.editable().is_empty() { ToolClaims::NONE.deletes() } else { ToolClaims::NONE }
if self.tool == AnnotationTool::Select && !self.editable().is_empty() { ToolClaims::NONE.deletes().nudges() } else { ToolClaims::NONE }
}
/// In Select, the annotations the arrows move: their kinds and the bounds round them.
fn access(&self, cx: &ToolContext<'_>) -> Option<ToolAccess> {
if self.tool != AnnotationTool::Select {
return None;
}
let ids = self.editable();
let moved: Vec<&Annotation> = self.annotations.iter().filter(|a| ids.contains(&a.id)).collect();
let bounds = moved.iter().map(|a| a.rect).reduce(|bounds, rect| bounds.union(rect))?;
let words = cx.words::<AnnotateWords>();
let names: Vec<&str> = moved.iter().map(|a| words.kind(a.kind)).collect();
Some(ToolAccess::new(names.join(", ")).bounds(bounds))
}
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
+12 -1
View File
@@ -501,11 +501,15 @@ pub struct ToolClaims {
/// point). With [`keyboard`](Self::keyboard) they are also claimed with Alt held: a polygonal lasso removes its
/// last point while Alt holds the straight-segment switch. Shift, Cmd and Ctrl deletes stay the app's (Fill).
pub deletes: bool,
/// The arrows move something the tool holds (a ruler line, selected boards): the host declares Increment and
/// Decrement on the tool's node and turns them into [`ToolKey::Nudge`], so a tool that claims the nudges
/// describes what they move in [`CanvasTool::access`]. The arrows reach [`CanvasTool::key`] either way.
pub nudges: bool,
}
impl ToolClaims {
/// No keys: every key stays the app's.
pub const NONE: ToolClaims = ToolClaims { keyboard: false, deletes: false };
pub const NONE: ToolClaims = ToolClaims { keyboard: false, deletes: false, nudges: false };
/// The same claims with the canvas's plain keys.
#[must_use]
@@ -520,6 +524,13 @@ impl ToolClaims {
self.deletes = true;
self
}
/// The same claims with the nudges.
#[must_use]
pub const fn nudges(mut self) -> Self {
self.nudges = true;
self
}
}
/// A tool on the canvas. The app owns the value and hands it to [`ToolHost::run`](super::ToolHost::run) each
+28 -8
View File
@@ -17,6 +17,8 @@
//! 5. The deletes and the plain keys are the app's unless the tool claims them ([`CanvasTool::claims`]). The host
//! reads the claims at the end of every pass, after the pointer events and keys, and holds the claimed chords from
//! the app's shortcuts in the next pass: a plain Delete with nothing to delete runs the app's Edit > Clear.
//! A tool that claims the nudges has AccessKit Increment and Decrement on its node, and they reach `key` as the
//! arrows toward and away from the reading end.
//! 6. The tool paints over the canvas and requests its cursor at tool priority.
//!
//! The host keeps its state under the canvas's id (`CanvasOutput::response.id`), so two canvases never share a
@@ -66,8 +68,8 @@ use crate::runtime::{cursor, frame, keys, lock_keys, measure};
use crate::style::StyleCx;
use craft_behavior::kurbo;
use craft_behavior::{
CancelReason, CanvasView, Cursor, CursorPriority, GestureId, GesturePhase, Intent, PartKey, PartRef, PointerButton, PointerSample, PressCancel,
PressPhase, PressStart, PressState,
AccessAction, AccessRequest, CancelReason, CanvasView, Cursor, CursorPriority, GestureId, GesturePhase, Intent, PartKey, PartRef, PointerButton,
PointerSample, PressCancel, PressPhase, PressStart, PressState,
};
use craft_keymap::{Chord, Key, Mods};
use craft_theme::Variant;
@@ -364,8 +366,10 @@ impl<'m> ToolHost<'m> {
};
paint_tool(ui, &env, tool, context());
let cx = context();
// A disabled host delivers no key, so it holds none from the app.
state.claims = if disabled { ToolClaims::NONE } else { tool.claims() };
if let Some(access) = tool.access(&cx) {
report_access(&ctx, canvas, rect, &access);
report_access(&ctx, canvas, rect, &access, state.claims.nudges);
}
if over {
let wanted = tool.cursor(&cx);
@@ -379,8 +383,6 @@ impl<'m> ToolHost<'m> {
if requests.repaint {
frame::request_repaint(&ctx);
}
// A disabled host delivers no key, so it holds none from the app.
state.claims = if disabled { ToolClaims::NONE } else { tool.claims() };
for chord in claimed_chords(state.claims) {
keys::claim(&ctx, canvas.response.id, chord);
}
@@ -444,9 +446,9 @@ const TOOL_ANCHOR: PartKey = PartKey::new("tool anchor");
/// Emits what the tool is to assistive technology through the sub-node path of the canvas's component: a hover-only
/// graphics object over the drawing's bounds (no size at the canvas centre without bounds), and a child object of no
/// size at each anchor, clamped to the canvas. The ids derive from the canvas id, so they stay the same from pass to
/// pass.
fn report_access(ctx: &Context, canvas: &CanvasOutput, rect: Rect, tool: &ToolAccess) {
/// size at each anchor, clamped to the canvas. The object declares Increment and Decrement while the tool claims the
/// nudges. The ids derive from the canvas id, so they stay the same from pass to pass.
fn report_access(ctx: &Context, canvas: &CanvasOutput, rect: Rect, tool: &ToolAccess, nudges: bool) {
let owner = canvas.response.id;
let to_screen = |point: kurbo::Point| canvas.space.map(|space| space.view.to_screen(point));
let bounds = tool.bounds.and_then(|bounds| {
@@ -462,6 +464,9 @@ fn report_access(ctx: &Context, canvas: &CanvasOutput, rect: Rect, tool: &ToolAc
if let Some(value) = &tool.value {
node.value(value.clone());
}
if nudges {
node.steps();
}
access::report_sub(ctx, &sub_decl(owner, &node, bounds.unwrap_or(at_centre), owner));
let parent = access::sub_node_id(owner, tool_part);
for (index, anchor) in (0u64..).zip(&tool.anchors) {
@@ -473,6 +478,11 @@ fn report_access(ctx: &Context, canvas: &CanvasOutput, rect: Rect, tool: &ToolAc
}
}
/// An AccessKit Increment or Decrement on the tool's node.
fn is_tool_step(request: &AccessRequest) -> bool {
matches!(request.action, AccessAction::Increment | AccessAction::Decrement) && request.target == Some(TOOL_NODE.into())
}
/// A sub-node of the canvas that is read only: not focusable, not clickable, never the active part.
fn sub_decl(owner: Id, node: &SubNode, rect: Rect, parent: Id) -> SubDecl<'_> {
SubDecl { owner, component: "", node, rect, enabled: true, focusable: false, clickable: false, active: false, face: None, label: "", parent }
@@ -791,6 +801,16 @@ impl<'a> Run<'a> {
});
let mut intents = keys::intents_of(ctx, Some(canvas), rtl);
let mut taken = self.offer(&mut intents, |intents| intents.take_nudge().map(|(direction, mods)| ToolKey::Nudge { direction, mods }));
if self.state.claims.nudges {
// Increment is the arrow toward the reading end, as for any focused control.
let forward = if rtl { -Vec2::X } else { Vec2::X };
taken |= self.offer(&mut intents, |intents| {
intents.take_access_where(is_tool_step).map(|request| {
let direction = if request.action == AccessAction::Increment { forward } else { -forward };
ToolKey::Nudge { direction, mods: Mods::NONE }
})
});
}
taken |= self.offer(&mut intents, |intents| intents.take(Intent::Submit).then_some(ToolKey::Submit));
if !self.cancelled {
taken |= self.offer(&mut intents, |intents| intents.take(Intent::Cancel).then_some(ToolKey::Cancel));
+64 -3
View File
@@ -5,15 +5,18 @@
//! freehand switch). Unclaimed deletes are the app's (Edit > Clear, Fill). Enter and Escape reach a tool as `Submit`
//! and `Cancel` with Alt carried, and Shift+Delete is no delete (Photoshop opens Fill, which the app binds). A
//! session control in the canvas body (a crop frame) takes the arrows, Enter and Escape before the tool, with the
//! canvas focused or nothing focused; with none shown, the arrows reach the tool with nothing focused.
//! canvas focused or nothing focused; with none shown, the arrows reach the tool with nothing focused. A tool that
//! claims the nudges declares Increment and Decrement on its node, and an AccessKit step moves what it holds as the
//! arrow toward or away from the reading end does.
use craft_behavior::geometry::CropBox;
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{CancelReason, CanvasView};
use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::primitives::Draw;
use craft_ui::testing::focus::key_release;
use craft_ui::testing::access::Declared;
use craft_ui::testing::focus::{AccessActionKind, key_release};
use craft_ui::testing::input::key_press;
use craft_ui::testing::{ToolFixture, pointer, trial};
use egui::{Key, Modifiers};
@@ -166,3 +169,61 @@ fn with_no_session_control_the_arrows_and_enter_reach_the_tool_with_nothing_focu
let seen = &canvas.tool().seen;
assert!(matches!(seen[..], [ToolKey::Nudge { .. }, ToolKey::Submit]), "{seen:?}");
}
/// A marker the arrows move one unit along x while `held`; it describes itself as `Marker` at its place.
struct Marker {
held: bool,
x: f64,
}
impl CanvasTool for Marker {
fn claims(&self) -> ToolClaims {
if self.held { ToolClaims::NONE.nudges() } else { ToolClaims::NONE }
}
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
ToolAction::Ignored
}
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
let ToolKey::Nudge { direction, .. } = key else { return false };
self.x += f64::from(direction.x);
true
}
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
fn access(&self, _: &ToolContext<'_>) -> Option<ToolAccess> {
Some(ToolAccess::new("Marker").bounds(Rect::new(self.x, 0.0, self.x + 10.0, 10.0)))
}
fn command_form(&self) -> ToolPath {
ToolPath::Command("the marker's form")
}
}
#[trial]
fn a_tool_that_claims_the_nudges_takes_increment_and_decrement_on_its_node() {
let mut canvas = ToolFixture::new("Document", Marker { held: false, x: 0.0 });
canvas.fixture().settle();
let node = canvas.fixture().by_label("Marker").expect("the tool's node").node;
let steps = |canvas: &mut ToolFixture<Marker>| {
let tree = canvas.fixture().tree();
(tree.declares_key(node, Declared::Increment), tree.declares_key(node, Declared::Decrement))
};
assert_eq!(steps(&mut canvas), (false, false), "a tool that holds nothing to nudge declares no step");
canvas.tool_mut().held = true;
canvas.fixture().settle();
assert_eq!(steps(&mut canvas), (true, true), "a tool that claims the nudges declares both steps on its node");
let target = canvas.fixture().by_label("Marker").expect("the tool's node");
canvas.fixture().access(AccessActionKind::Increment, &target).settle();
assert_eq!(canvas.tool().x, 1.0, "Increment moves the marker toward the reading end");
canvas.fixture().access(AccessActionKind::Decrement, &target).access(AccessActionKind::Decrement, &target).settle();
assert_eq!(canvas.tool().x, -1.0, "Decrement moves it back");
}
+10
View File
@@ -521,6 +521,7 @@ pub struct SubNode {
#[doc(hidden)]
pub flags: Flags,
pub(crate) custom_actions: Vec<(i32, Label)>,
pub(crate) steps: bool,
pub(crate) bounds: Option<egui::Rect>,
pub(crate) run: Option<RunFacts>,
pub(crate) run_links: Vec<RunLink>,
@@ -551,6 +552,7 @@ impl SubNode {
under: None,
flags: Flags::empty(),
custom_actions: Vec::new(),
steps: false,
bounds: None,
run: None,
run_links: Vec::new(),
@@ -581,6 +583,14 @@ impl SubNode {
self
}
/// Declares Increment and Decrement on a node that steps something with no number (a canvas tool's arrows
/// nudging what it holds); a part with no focus stop gets them as `take_access` requests that name the part.
#[doc(hidden)]
pub fn steps(&mut self) -> &mut Self {
self.steps = true;
self
}
/// The heading level or tree depth.
pub fn level(&mut self, level: usize) -> &mut Self {
self.level = Some(level);
@@ -382,6 +382,9 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) {
spec.sortable = node.sortable;
write_states(&mut spec, flags, decl.enabled, false);
declare_actions(&mut spec, decl.focusable, decl.clickable, numeric);
if node.steps && numeric.is_none() {
spec.actions.extend([NodeAction::Increment, NodeAction::Decrement]);
}
custom_actions(&mut spec, &node.custom_actions);
adapter::register_parent(ctx, id, decl.parent);
write_node(ctx, id, &spec);