From 6e301f04c7cd87a336246924784cb2b51d495b93 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 13 Nov 2026 01:13:02 +0000 Subject: [PATCH] Cursor images: a badged system cursor keeps the system arrow; trials for where, when and how the image goes out --- crates/ui-contract/src/contract/ghost.rs | 6 +- crates/ui-contract/src/contract/ghost/art.rs | 7 +- crates/ui-contract/src/primitives/mod.rs | 2 +- .../ui-contract/src/runtime/egui/fixture.rs | 3 + crates/ui-contract/src/runtime/windows.rs | 2 +- crates/ui-contract/src/testing/frames.rs | 8 + crates/ui-contract/tests/it/runtime/cursor.rs | 170 ++++++++++++++++++ crates/ui-contract/tests/it/runtime/mod.rs | 1 + 8 files changed, 193 insertions(+), 6 deletions(-) create mode 100644 crates/ui-contract/tests/it/runtime/cursor.rs diff --git a/crates/ui-contract/src/contract/ghost.rs b/crates/ui-contract/src/contract/ghost.rs index 5ed90ec486..b88eb84c19 100644 --- a/crates/ui-contract/src/contract/ghost.rs +++ b/crates/ui-contract/src/contract/ghost.rs @@ -38,13 +38,15 @@ pub fn painter(ctx: &Context) -> egui::Painter { /// The painted pointer the cursor service settled on: the window's cursor image where the window takes one at its /// 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. +/// 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. 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); - if let Some(target) = cursor::image_target(ctx) { + 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) { return; } diff --git a/crates/ui-contract/src/contract/ghost/art.rs b/crates/ui-contract/src/contract/ghost/art.rs index 579f361d69..a6c2b05911 100644 --- a/crates/ui-contract/src/contract/ghost/art.rs +++ b/crates/ui-contract/src/contract/ghost/art.rs @@ -36,7 +36,8 @@ pub(crate) enum Mark { impl Mark { /// The rect the mark covers, its line included. fn bounds(&self) -> Rect { - let around = |points: &[Vec2], stroke: &Stroke| Rect::from_points(&points.iter().map(|p| p.to_pos2()).collect::>()).expand(stroke.width / 2.0); + let around = + |points: &[Vec2], stroke: &Stroke| Rect::from_points(&points.iter().map(|p| p.to_pos2()).collect::>()).expand(stroke.width / 2.0); match self { Mark::Line(a, b, stroke) => around(&[*a, *b], stroke), Mark::Ring(centre, radius, stroke) => Rect::from_center_size(centre.to_pos2(), Vec2::splat(2.0 * radius + stroke.width)), @@ -192,7 +193,9 @@ fn rounded_path(rect: Rect, round: f32) -> Option { fn draw(pixmap: &mut tiny_skia::Pixmap, mark: &Mark, transform: tiny_skia::Transform, scale: f32, origin: f32) { match mark { Mark::Line(a, b, stroke) => stroke_path(pixmap, polyline(&[*a, *b], false), *stroke, transform), - Mark::Ring(centre, radius, stroke) => stroke_path(pixmap, tiny_skia::PathBuilder::from_circle(centre.x, centre.y, *radius), *stroke, transform), + Mark::Ring(centre, radius, stroke) => { + stroke_path(pixmap, tiny_skia::PathBuilder::from_circle(centre.x, centre.y, *radius), *stroke, transform) + } Mark::Frame(rect, stroke) => stroke_path(pixmap, rect_path(*rect), *stroke, transform), Mark::Disc(centre, radius, color) => fill_path(pixmap, tiny_skia::PathBuilder::from_circle(centre.x, centre.y, *radius), *color, transform), Mark::Block(rect, round, color) => fill_path(pixmap, rounded_path(*rect, *round), *color, transform), diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index cce42cce32..66807470f1 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -32,8 +32,8 @@ pub use draw::{Dashes, DataStrokeWidth, DataWidth, Draw, PaintShape, StrokeColor pub use faces::FacesCx; pub use focus_ring::{FocusKind, FocusRing}; pub use handle::{Handle, HandleShape}; -pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; pub(crate) use icon::SvgIcon; +pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; pub use ime_surface::ImeSurface; pub use kit::{ Checker, CheckerArea, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, ellipse, diff --git a/crates/ui-contract/src/runtime/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index cabec302e0..0fee004ccc 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -38,6 +38,8 @@ pub(crate) struct FrameResult { pub closed: bool, /// The cursor the frame's output asked for. pub cursor: egui::CursorIcon, + /// The cursor image the frame's output asked for. + pub cursor_image: Option, /// The wait egui asks for before the root viewport's next pass; `Duration::MAX` when it asks for none. pub repaint_delay: std::time::Duration, /// The AccessKit tree update of the frame. @@ -208,6 +210,7 @@ pub(crate) fn run_frame( bounds, overshoot, cursor: output.platform_output.cursor_icon, + cursor_image: output.platform_output.cursor_image.clone(), repaint_delay, tree: crate::runtime::egui::access::tree_of(&mut output), ime: output.platform_output.ime.as_ref().map(|ime| ImeSeen { diff --git a/crates/ui-contract/src/runtime/windows.rs b/crates/ui-contract/src/runtime/windows.rs index a871cd274c..6c43d7cbac 100644 --- a/crates/ui-contract/src/runtime/windows.rs +++ b/crates/ui-contract/src/runtime/windows.rs @@ -40,11 +40,11 @@ pub use native::keeps_app_drag; pub use native::route_root; pub use native::{WindowAction, act, double_click_action}; use placement::record_placement; +pub(crate) use shell::base_shell; #[doc(hidden)] pub use shell::os_of; #[doc(hidden)] pub use shell::shell_of; -pub(crate) use shell::base_shell; use shell::{refresh, window_info}; #[cfg(feature = "testing")] pub(crate) use shell::{set_chrome, set_os}; diff --git a/crates/ui-contract/src/testing/frames.rs b/crates/ui-contract/src/testing/frames.rs index d9e00e6a4a..8c4f71eb49 100644 --- a/crates/ui-contract/src/testing/frames.rs +++ b/crates/ui-contract/src/testing/frames.rs @@ -20,6 +20,7 @@ pub struct Frames { time: f64, root: RootEnv, cursor: egui::CursorIcon, + cursor_image: Option, repaint_delay: Duration, host: Option>, commands: CommandInput, @@ -89,6 +90,7 @@ impl Frames { time: 0.0, root: RootEnv::default(), cursor: egui::CursorIcon::Default, + cursor_image: None, repaint_delay: Duration::MAX, host: None, commands: CommandInput::new(), @@ -229,6 +231,7 @@ impl Frames { None => result.textures.clear(), } self.cursor = result.cursor; + self.cursor_image = result.cursor_image; self.repaint_delay = result.repaint_delay; self.tree = result.tree; self.ime = result.ime; @@ -290,6 +293,11 @@ impl Frames { pub fn cursor_icon(&self) -> egui::CursorIcon { self.cursor } + + /// The cursor image the last frame's output asked for, which the integration shows instead of the system cursor. + pub fn cursor_image(&self) -> Option<&egui::CustomCursorImage> { + self.cursor_image.as_ref() + } } /// Adds `text` to the next frame output's announcements, as the runtime's access service does. diff --git a/crates/ui-contract/tests/it/runtime/cursor.rs b/crates/ui-contract/tests/it/runtime/cursor.rs new file mode 100644 index 0000000000..03a0a3e16f --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/cursor.rs @@ -0,0 +1,170 @@ +//! The cursor service's images (8.5): a painted pointer reaches the window as its cursor image where the window takes +//! one at its size, and is painted at the pointer otherwise. + +use craft_behavior::{Cursor, CursorBadge, CursorIcon, CursorPriority, IconId, PaintedCursor}; +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}; +use std::sync::Arc; + +const AT: Pos2 = Pos2::new(300.0, 300.0); + +/// Frames on `shell` in a window of `scale` device pixels per point, keeping what they paint. +fn frames(shell: ShellInfo, scale: f32) -> Frames { + let mut frames = Frames::uninstalled(); + let mut spec = install_spec(); + spec.shell_info = shell; + craft_ui::install(&frames.ctx, spec).expect("the runtime installs once"); + frames.pixels_per_point(scale); + frames.record_paint(); + frames +} + +/// What one frame with the pointer at `AT` and `requests` sent out: the cursor image, the system cursor and how many +/// shapes it painted (the ghost layer's, as nothing else paints). +struct Seen { + image: Option, + icon: egui::CursorIcon, + shapes: usize, +} + +fn frame(frames: &mut Frames, requests: &[(Cursor, CursorPriority)]) -> Seen { + frames.frame(vec![moved(AT)], |ui| { + for (cursor, priority) in requests { + cursor::request(ui.ctx(), cursor.clone(), *priority); + } + }); + let mut paint = frames.take_paint().expect("the frames record their paint"); + paint.textures_delta.clear(); + let shapes = paint.shapes.iter().filter(|s| !matches!(s.shape, egui::Shape::Noop)).count(); + Seen { image: frames.cursor_image().cloned(), icon: frames.cursor_icon(), shapes } +} + +fn painted(frames: &mut Frames, cursor: PaintedCursor) -> Seen { + frame(frames, &[(Cursor::Painted(cursor), CursorPriority::Tool)]) +} + +fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 { + image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3] +} + +fn linux() -> ShellInfo { + ShellInfo::default().os(Os::Linux).backend(Backend::X11) +} + +/// The window takes the image on a native build, Wayland only at scale 1 (compositors that ignore winit's cursor +/// viewport show it too large and off the pointer); elsewhere the pointer is painted and the system cursor hidden. +/// macOS sizes the image in points, so it does not grow with the display's density. +#[trial] +fn a_painted_pointer_is_the_window_cursor_image_where_the_window_takes_one() { + let wayland = || linux().backend(Backend::Wayland); + let rows: [(&str, ShellInfo, f32, bool); 8] = [ + ("X11 at 1", linux(), 1.0, true), + ("X11 at 1.25", linux(), 1.25, true), + ("Wayland at 1", wayland(), 1.0, true), + ("Wayland at 1.25", wayland(), 1.25, false), + ("Wayland at 2", wayland(), 2.0, false), + ("web", linux().runtime(Runtime::Web), 1.0, false), + ("macOS at 2", linux().os(Os::Mac), 2.0, true), + ("Windows at 1.5", linux().os(Os::Windows), 1.5, true), + ]; + let mut sides = Vec::new(); + for (name, shell, scale, image) in rows { + let mut frames = frames(shell, scale); + let seen = painted(&mut frames, PaintedCursor::circle(20.0)); + assert_eq!(seen.image.is_some(), image, "{name}: image"); + if image { + assert_eq!(seen.shapes, 0, "{name}: an image is not painted as well"); + assert_eq!(seen.icon, egui::CursorIcon::Crosshair, "{name}: a visible system cursor if the integration drops the image"); + } else { + assert!(seen.shapes > 0, "{name}: the pointer is painted"); + assert_eq!(seen.icon, egui::CursorIcon::None, "{name}: the painted pointer is the only pointer"); + } + sides.push((name, seen.image.map(|image| image.size[0]))); + } + let side = |name: &str| sides.iter().find(|(n, _)| *n == name).and_then(|(_, side)| *side).unwrap(); + assert!(side("X11 at 1.25") > side("X11 at 1"), "the image grows with the window's scale"); + assert!(side("macOS at 2") < side("Windows at 1.5"), "macOS takes the image in points"); + + // A tip larger than Linux takes hands its centre cross to the window and paints its ring; macOS takes it whole. + let mut frames_linux = frames(linux(), 1.0); + let big = painted(&mut frames_linux, PaintedCursor::circle(300.0)); + let marks = big.image.expect("the centre cross still moves with the hardware pointer"); + assert!(marks.size[0] < 100 && big.shapes > 0, "the ring is painted, not shrunk into the image"); + let mut frames_mac = frames(linux().os(Os::Mac), 1.0); + let whole = painted(&mut frames_mac, PaintedCursor::circle(300.0)); + assert!(whole.image.expect("macOS takes large images").size[0] > 600 && whole.shapes == 0); + + // Every pointer the overlay host draws has an image, apart from the badged system cursor (the OS draws its arrow) + // and the hidden pointer. + let mut frames = frames(linux(), 1.0); + let ring = vec![Pos2::new(-8.0, -4.0), Pos2::new(8.0, -4.0), Pos2::new(0.0, 9.0)]; + for cursor in [ + PaintedCursor::Crosshair, + PaintedCursor::circle(12.0).marked(true, Some(CursorBadge::Add)), + PaintedCursor::outline(vec![ring]).marked(true, None), + PaintedCursor::Hand, + PaintedCursor::zoom(true), + PaintedCursor::tool(IconId::new("brush"), Vec2::new(4.0, 20.0), Some(CursorBadge::Copy)), + PaintedCursor::turn(Vec2::new(1.0, 1.0)), + PaintedCursor::distort(Vec2::new(-1.0, 0.0)), + PaintedCursor::skew(Vec2::X), + ] { + let seen = painted(&mut frames, cursor.clone()); + assert!(seen.image.is_some() && seen.shapes == 0, "{cursor:?}"); + } + let badged = painted(&mut frames, PaintedCursor::badged(CursorIcon::Default, CursorBadge::Add)); + assert!(badged.image.is_none() && badged.shapes > 0 && badged.icon == egui::CursorIcon::Default, "the arrow stays the system's"); + let hidden = painted(&mut frames, PaintedCursor::Hidden); + assert!(hidden.image.is_none() && hidden.shapes == 0 && hidden.icon == egui::CursorIcon::None); +} + +/// An unchanged pointer hands the window the same image, so the integration uploads it to the OS once; a new size or +/// scale makes a new one; a frame whose winner is a system cursor, or that asks for nothing, clears it (egui keeps an +/// image until it is replaced). +#[trial] +fn the_cursor_image_is_drawn_once_per_look_and_cleared_when_no_painted_pointer_wins() { + let mut frames = frames(linux(), 1.0); + let first = painted(&mut frames, PaintedCursor::circle(20.0)).image.unwrap(); + let moved = painted(&mut frames, PaintedCursor::circle(20.0)).image.unwrap(); + assert!(Arc::ptr_eq(&first.rgba, &moved.rgba), "moving the pointer draws and uploads nothing"); + let larger = painted(&mut frames, PaintedCursor::circle(40.0)).image.unwrap(); + assert!(!Arc::ptr_eq(&first.rgba, &larger.rgba) && larger.size[0] > first.size[0]); + + let hover = frame( + &mut frames, + &[ + (Cursor::Painted(PaintedCursor::circle(40.0)), CursorPriority::Tool), + (Cursor::System(CursorIcon::ResizeHorizontal), CursorPriority::Hover), + ], + ); + assert!(hover.image.is_none() && hover.icon == egui::CursorIcon::ResizeHorizontal, "a hovered control's cursor wins over the image"); + let left = frame(&mut frames, &[]); + assert!(left.image.is_none(), "a pass without a painted pointer keeps no image"); + + frames.pixels_per_point(2.0); + let scaled = painted(&mut frames, PaintedCursor::circle(40.0)).image.unwrap(); + assert!(scaled.size[0] > larger.size[0], "a scale change draws the image again"); +} + +/// The image is the pointer drawn on the device's pixels: an odd square with the hotspot on its centre pixel, the ring +/// opaque at its radius at every scale, clear inside and in the corners. +#[trial] +fn the_cursor_image_draws_the_pointer_around_its_centre_pixel() { + for scale in [1.0, 1.5, 2.0] { + let mut frames = frames(linux(), scale); + let image = painted(&mut frames, PaintedCursor::circle(20.0)).image.unwrap(); + let [w, h] = image.size; + let hot = image.hotspot; + assert!(w == h && w % 2 == 1 && hot == [w / 2, h / 2], "{scale}: {:?} {hot:?}", image.size); + assert_eq!(image.rgba.len(), usize::from(w) * usize::from(h) * 4); + let radius = (20.0 * scale).round() as u16; + for (x, y) in [(hot[0] + radius, hot[1]), (hot[0] - radius, hot[1]), (hot[0], hot[1] + radius)] { + assert!(alpha(&image, x, y) > 200, "{scale}: the ring at ({x}, {y})"); + } + assert_eq!(alpha(&image, hot[0], hot[1]), 0, "{scale}: the hotspot shows what is under it"); + assert_eq!(alpha(&image, 0, 0), 0, "{scale}: the corners are clear"); + } +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 04ee79f82d..79c1408217 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -1,3 +1,4 @@ +mod cursor; mod env; mod frame; mod memory;