Merge pull request #2468 from aiongg/tool-overlay-clip

Brush tip outlines show only inside the canvas view (photocraft#15863)
This commit is contained in:
aiongg authored and GitHub committed 2026-11-19 23:15:06 -05:00
commit 3e85f5975a
6 files changed
+178 -15

No files matched your search

+6 -1
View File
@@ -346,5 +346,10 @@ pub enum CursorPriority {
/// The winning request: the highest priority, the later request on a tie.
pub fn pick(requests: &[(Cursor, CursorPriority)]) -> Option<&Cursor> {
requests.iter().enumerate().max_by_key(|(order, (_, priority))| (*priority, *order)).map(|(_, (cursor, _))| cursor)
pick_index(requests).map(|at| &requests[at].0)
}
/// The index of the winning request ([`pick`]).
pub fn pick_index(requests: &[(Cursor, CursorPriority)]) -> Option<usize> {
requests.iter().enumerate().max_by_key(|(order, (_, priority))| (*priority, *order)).map(|(at, _)| at)
}
+4 -2
View File
@@ -22,7 +22,7 @@
//! 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.
//! 6. The tool paints over the canvas and requests its cursor at tool priority, within the view on the canvas's layer.
//! 7. A drag past the canvas edge ([`CanvasTool::autoscrolls`]), and a hover in the band inside it
//! ([`CanvasTool::autoscrolls_on_hover`]), report [`ToolHostResponse::past_edge`] and the pass's
//! [`ToolHostResponse::scroll`]; the app moves its view by it with [`Autoscroll::scroll`].
@@ -624,7 +624,9 @@ impl<'m> ToolHost<'m> {
}
if over {
let wanted = effective.cursor(&cx);
cursor::request(&ctx, wanted.clone(), CursorPriority::Tool);
// A tip outline is a mark on the canvas: it shows inside the view, on the canvas's layer.
let view = space.map_or(rect, |space| space.view.rect).intersect(rect);
cursor::request_within(&ctx, wanted.clone(), CursorPriority::Tool, cursor::CursorRegion::new(ui.layer_id(), view));
response.cursor = Some(wanted);
}
if let Some(at) = current.map(|pointer| pointer.pos) {
+38 -6
View File
@@ -98,24 +98,56 @@ pub fn painter(ctx: &Context) -> egui::Painter {
/// size, else painted at the pointer. A brush tip too large for an image hands its centre cross and badge to the
/// window and paints only its ring, so the pointer itself still moves with the hardware. A badged system cursor keeps
/// the system's arrow and has only its badge painted.
///
/// A tip outline requested within a region (`cursor::request_within`: a canvas's view on the canvas's layer) is a
/// mark on that canvas: the whole outline goes to the window only while it lies inside the region with no layer above
/// the region's over it. Otherwise its ring paints on the region's layer clipped to the region, under the panels,
/// menus and dialogs above it, and the window takes its marks as a too large tip's.
fn paint_pointer(ctx: &Context, env: &Env, painter: &egui::Painter) {
use craft_behavior::{Cursor, PaintedCursor};
let Some(at) = areas::pointer_pos(ctx) else { return };
let Some(Cursor::Painted(cursor)) = cursor::current(ctx) else { return };
let closed = pointer::frame(ctx).buttons.contains(craft_behavior::Buttons::PRIMARY);
let tip = matches!(cursor, PaintedCursor::Circle { .. } | PaintedCursor::Outline { .. });
let whole = pointer_art(env, &cursor, closed, false);
let confined = cursor::current_region(ctx).filter(|region| tip && !shows_whole(ctx, region, &whole, at));
let ring = |painter: &egui::Painter| {
let art = pointer_art(env, &cursor.clone().marked(false, None), closed, false);
match confined {
Some(region) => paint_in_region(ctx, region, &art, at),
None => art.paint(painter, at),
}
};
let target = cursor::image_target(ctx).filter(|_| !matches!(cursor, PaintedCursor::Badged { .. }));
if let Some(target) = target {
if cursor::show_image(ctx, &pointer_art(env, &cursor, closed, false), target) {
if confined.is_none() && cursor::show_image(ctx, &whole, target) {
return;
}
if matches!(cursor, PaintedCursor::Circle { .. } | PaintedCursor::Outline { .. })
&& cursor::show_image(ctx, &pointer_art(env, &cursor, closed, true), target)
{
pointer_art(env, &cursor.marked(false, None), closed, false).paint(painter, at);
if tip && cursor::show_image(ctx, &pointer_art(env, &cursor, closed, true), target) {
ring(painter);
return;
}
}
pointer_art(env, &cursor, closed, false).paint(painter, at);
match confined {
Some(_) => {
ring(painter);
pointer_art(env, &cursor, closed, true).paint(painter, at);
}
None => whole.paint(painter, at),
}
}
/// Whether `art` at the pointer `at` lies inside `region` with no layer above the region's layer over it.
fn shows_whole(ctx: &Context, region: &cursor::CursorRegion, art: &Art, at: Pos2) -> bool {
let Some(bounds) = art.bounds().map(|bounds| bounds.translate(at.to_vec2())) else { return true };
region.clip.contains_rect(bounds) && !areas::rects_over(ctx, region.layer, None).iter().any(|over| over.intersects(bounds))
}
/// Paints `art` at the pointer `at` (screen space) on `region`'s layer, clipped to the region.
fn paint_in_region(ctx: &Context, region: cursor::CursorRegion, art: &Art, at: Pos2) {
let to_layer = areas::layer_to_screen(ctx, region.layer).inverse();
let painter = egui::Painter::new(ctx.clone(), region.layer, to_layer * region.clip);
art.paint(&painter, to_layer * at);
}
/// The art of `cursor`: the hand as a fist while `closed`; with `marks_only`, a brush tip's centre cross and badge
@@ -61,6 +61,11 @@ impl Art {
self.marks.push(mark);
}
/// The rect the marks cover, around the hotspot at the origin; `None` for art with no marks.
pub(crate) fn bounds(&self) -> Option<Rect> {
self.marks.iter().map(Mark::bounds).reduce(|a, b| a.union(b))
}
/// Paints the art with its hotspot at `at`.
pub(crate) fn paint(&self, painter: &Painter, at: Pos2) {
let path = |points: &[Vec2]| points.iter().map(|p| at + *p).collect::<Vec<_>>();
@@ -99,7 +104,7 @@ impl Art {
if !scale.is_finite() || scale <= 0.0 {
return None;
}
let bounds = self.marks.iter().map(Mark::bounds).reduce(|a, b| a.union(b))?;
let bounds = self.bounds()?;
let reach = [bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y].into_iter().map(f32::abs).fold(0.0, f32::max);
let half = (reach * scale + FRINGE_PX).ceil();
if !half.is_finite() || half > f32::from(max_side.saturating_sub(1) / 2) {
+53 -4
View File
@@ -1,13 +1,14 @@
//! The cursor service (8.5): requests of a pass collect here, the end hook picks the winner and records it, and a
//! painted winner reaches the window as its cursor image where the window shows one.
use crate::runtime::egui::areas::LayerKey;
use crate::runtime::egui::{output, pass, viewports};
use crate::runtime::frame::PerViewport;
use crate::runtime::windows;
use craft_behavior::cursor::pick;
use craft_behavior::cursor::pick_index;
use craft_behavior::{Cursor, CursorIcon, CursorPriority, PaintedCursor};
use craft_host::target::Os;
use egui::{Context, ViewportId};
use egui::{Context, Rect, ViewportId};
use std::any::Any;
use std::sync::Arc;
@@ -38,10 +39,32 @@ pub(crate) struct ImageTarget {
pub max_side: u16,
}
/// Where a cursor's footprint may show: a layer and a clip in screen space. A brush tip outline is a mark on its
/// canvas, not a pointer, so it shows only inside the canvas's view and under every layer above the canvas.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct CursorRegion {
/// The layer the requester paints on.
pub layer: LayerKey,
/// The part of the screen the footprint may cover.
pub clip: Rect,
}
impl CursorRegion {
/// The region of `clip` on `layer`.
pub fn new(layer: LayerKey, clip: Rect) -> Self {
CursorRegion { layer, clip }
}
}
#[derive(Default)]
pub(crate) struct State {
requests: Vec<(Cursor, CursorPriority)>,
/// The region of each request, in the order of `requests`.
regions: Vec<Option<CursorRegion>>,
record: Option<Cursor>,
/// The region of the recorded winner.
region: Option<CursorRegion>,
/// The last image handed to the window with the art and scale it was drawn from. egui-winit uploads an image to
/// the OS whenever its `Arc` changes, so an unchanged pointer hands over the same one.
image: Option<(Box<dyn Any + Send + Sync>, f32, CursorBitmap)>,
@@ -50,7 +73,22 @@ pub(crate) struct State {
/// Requests `cursor` for the running pass of this viewport.
#[doc(hidden)]
pub fn request(ctx: &Context, cursor: Cursor, priority: CursorPriority) {
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| state.requests.push((cursor, priority)));
push(ctx, cursor, priority, None);
}
/// Requests `cursor` for the running pass of this viewport, its footprint (a brush tip outline) shown only in
/// `region`: the overlay host paints a tip outline that leaves the region, or that a layer above the region's covers,
/// on the region's layer clipped to it, and gives the window only its marks.
#[doc(hidden)]
pub fn request_within(ctx: &Context, cursor: Cursor, priority: CursorPriority, region: CursorRegion) {
push(ctx, cursor, priority, Some(region));
}
fn push(ctx: &Context, cursor: Cursor, priority: CursorPriority, region: Option<CursorRegion>) {
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| {
state.requests.push((cursor, priority));
state.regions.push(region);
});
}
/// The end hook: records the pass's winner, which in a window an app-modal layer in another window blocks is the
@@ -61,8 +99,14 @@ pub fn request(ctx: &Context, cursor: Cursor, priority: CursorPriority) {
pub(crate) fn end_pass(ctx: &Context) {
let blocked = windows::blocking_modal(ctx).is_some();
let won = PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| {
let won = if blocked { Some(Cursor::System(CursorIcon::NotAllowed)) } else { pick(&state.requests).cloned() };
let (won, region) = match pick_index(&state.requests) {
_ if blocked => (Some(Cursor::System(CursorIcon::NotAllowed)), None),
Some(at) => (Some(state.requests[at].0.clone()), state.regions[at]),
None => (None, None),
};
state.requests.clear();
state.regions.clear();
state.region = region;
if !matches!(won, Some(Cursor::Painted(_))) {
state.image = None;
}
@@ -83,6 +127,11 @@ pub fn current(ctx: &Context) -> Option<Cursor> {
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| state.record.clone())
}
/// The region of the cursor the last pass settled on, when its requester gave one ([`request_within`]).
pub(crate) fn current_region(ctx: &Context) -> Option<CursorRegion> {
PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| state.region)
}
/// How the running viewport's window takes a cursor image, or `None` where it takes none: only the root viewport (the
/// framework's other windows are egui's immediate viewports, which hand no image to the OS), and only where the shell
/// shows images at the window's scale. The image is in points on macOS, where AppKit sizes an `NSCursor` in points,
+71 -1
View File
@@ -6,7 +6,7 @@ use craft_host::target::{Backend, Os, Runtime, ShellInfo};
use craft_ui::runtime::cursor;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Frames, install_spec, trial};
use egui::{CustomCursorImage, Pos2, Vec2, ViewportId};
use egui::{CustomCursorImage, Pos2, Rect, Vec2, ViewportId};
use std::sync::Arc;
const AT: Pos2 = Pos2::new(300.0, 300.0);
@@ -236,3 +236,73 @@ fn the_cursor_image_draws_the_pointer_around_its_centre_pixel() {
assert_eq!(alpha(&image, 0, 0), 0, "{scale}: the corners are clear");
}
}
/// A brush tip outline requested within a region (a canvas's view on the canvas's layer) is a mark on that canvas:
/// the window takes it whole only while it lies inside the region with no layer over it. At the region's edge, or
/// under a layer above the region's, its ring paints on the region's layer clipped to the region, under that layer,
/// and the window takes only its marks.
#[trial]
fn a_tip_outline_shows_only_inside_its_region() {
const RADIUS: f32 = 40.0;
let canvas = egui::LayerId::background();
let cover = egui::Id::unique("cover");
// One frame with the pointer at `AT`, the tip requested within `clip`, and an area over `over` when given: the
// cursor image, and each painted shape's clip with whether it is the ring or the area's fill, in paint order.
let run = |frames: &mut Frames, clip: Rect, over: Option<Rect>| {
frames.frame_in_viewport(ViewportId::ROOT, vec![moved(AT)], |ui| {
let region = cursor::CursorRegion::new(canvas, clip);
cursor::request_within(ui.ctx(), Cursor::Painted(PaintedCursor::circle(RADIUS).marked(true, None)), CursorPriority::Tool, region);
if let Some(over) = over {
egui::Area::new(cover).fixed_pos(over.min).show(ui.ctx(), |ui| {
ui.allocate_space(over.size());
ui.painter().rect_filled(over, 0.0, egui::Color32::RED);
});
}
});
let mut paint = frames.take_paint().expect("the frames record their paint");
paint.textures_delta.clear();
let shapes: Vec<(Rect, Option<bool>)> = paint
.shapes
.iter()
.map(|clipped| {
let kind = match &clipped.shape {
egui::Shape::Circle(circle) if circle.radius > RADIUS / 2.0 => Some(true),
// The area fades in, so its red fill is scaled down.
egui::Shape::Rect(rect) if rect.fill.r() > 0 && rect.fill.g() == 0 && rect.fill.b() == 0 => Some(false),
_ => None,
};
(clipped.clip_rect, kind)
})
.collect();
(frames.cursor_image().cloned(), shapes)
};
let rings = |shapes: &[(Rect, Option<bool>)]| shapes.iter().filter(|(_, kind)| *kind == Some(true)).map(|(clip, _)| *clip).collect::<Vec<_>>();
let mut frames = frames(linux(), 1.0);
// Inside the region with nothing over it: the whole outline moves with the hardware pointer.
let room = Rect::from_center_size(AT, Vec2::splat(400.0));
let (image, shapes) = run(&mut frames, room, None);
let whole = image.expect("the whole outline is the window's image").size[0];
assert!(rings(&shapes).is_empty(), "the image is not painted as well");
// The region's edge runs under the ring: the ring paints clipped to the region; the window takes the marks.
let edge = Rect::from_min_max(Pos2::new(AT.x - RADIUS / 2.0, AT.y - 200.0), Pos2::new(AT.x + 200.0, AT.y + 200.0));
let (image, shapes) = run(&mut frames, edge, None);
assert!(image.expect("the marks still move with the hardware pointer").size[0] < whole, "the image holds only the marks");
let clips = rings(&shapes);
assert!(!clips.is_empty() && clips.iter().all(|clip| edge.contains_rect(*clip)), "the ring is cut off at the region's edge: {clips:?}");
// A layer over part of the ring: the ring paints under it.
let over = Rect::from_min_size(Pos2::new(AT.x + RADIUS / 2.0, AT.y - 100.0), Vec2::new(100.0, 200.0));
// egui shows a new area from its second frame.
run(&mut frames, room, Some(over));
let (image, shapes) = run(&mut frames, room, Some(over));
assert!(image.expect("the marks").size[0] < whole, "a covered outline is not the window's image");
let ring_at = shapes.iter().position(|(_, kind)| *kind == Some(true)).expect("the ring is painted");
let cover_at = shapes.iter().position(|(_, kind)| *kind == Some(false)).expect("the area is painted");
assert!(ring_at < cover_at, "the ring lies under the layer above the canvas");
// A request with no region keeps the pointer's own path at any position.
let seen = painted(&mut frames, PaintedCursor::circle(RADIUS));
assert!(seen.image.is_some() && seen.shapes == 0, "an outline with no region is the window's image");
}