Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Native brush outline and crosshair cursors on macOS, X11 and Wayland (#1343) (#3243)

Tanish Mankuda5abd10f937
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 55bbc2e77..e37a258cc 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -509,8 +509,9 @@ pub(crate) fn stroke_command(app: &PhotocraftApp, tool: Tool) -> &'static str {
}
/// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many
-/// photos) it vanishes (#737). Use a black-and-white bitmap, carried by the OS on Windows so
-/// its movement does not wait for the canvas to render.
+/// photos) it vanishes (#737), and the Linux themes' and macOS's differ. Use the same black-and-white
+/// bitmap on every desktop platform, carried by the OS so its movement does not wait for the canvas
+/// to render (#1343).
fn visible_crosshair(icon: egui::CursorIcon, painter: &egui::Painter, p: Pos2, draw: bool) -> egui::CursorIcon {
if !draw || icon != egui::CursorIcon::Crosshair {
return icon;
@@ -3389,7 +3390,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
_ => egui::CursorIcon::Crosshair,
};
- let icon = visible_crosshair(icon, &painter, p, cfg!(target_os = "windows"));
+ let icon = visible_crosshair(icon, &painter, p, cfg!(not(target_arch = "wasm32")));
ui.ctx().set_cursor_icon(icon);
// Selection tools: + / − / × badge for the effective mode (#170). A gesture keeps the
// mode it started with (⇧ then constrains the marquee instead of adding).
diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs
index 71b766a14..d78dbedba 100644
--- a/crates/ui-egui/src/input_tests.rs
+++ b/crates/ui-egui/src/input_tests.rs
@@ -551,17 +551,17 @@ fn eyedropper_and_alt_sampling_show_a_pipette() {
h.event(egui::Event::ModifiersChanged(Modifiers::ALT));
assert_eq!(cursor(&mut h), egui::CursorIcon::None, "⌥ samples with a pipette");
h.state_mut().run("prefs.set", json!({"values": {"cursors.other": "precise"}})).unwrap();
- // Every platform reports the crosshair. Windows also hands the OS a black-and-white bitmap
- // for it (`tool_cursor`, #1160), with `Crosshair` underneath as the fallback.
+ // Every platform reports the crosshair. The desktop builds also hand the OS a black-and-white
+ // bitmap for it (`tool_cursor`, #1160, #1343), with `Crosshair` underneath as the fallback.
let precise = |h: &mut Harness<'static, PhotocraftApp>| {
let icon = cursor(h);
(icon, h.output().platform_output.cursor_image.is_some())
};
- let windows = cfg!(target_os = "windows");
- assert_eq!(precise(&mut h), (egui::CursorIcon::Crosshair, windows), "Precise keeps the crosshair");
+ let desktop = cfg!(not(target_arch = "wasm32"));
+ assert_eq!(precise(&mut h), (egui::CursorIcon::Crosshair, desktop), "Precise keeps the crosshair");
h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
h.state_mut().ui.tool = crate::state::Tool::Eyedropper;
- assert_eq!(precise(&mut h), (egui::CursorIcon::Crosshair, windows));
+ assert_eq!(precise(&mut h), (egui::CursorIcon::Crosshair, desktop));
}
/// The Hand tool, and Space held over another tool, show an open hand while hovering and a fist
diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/tool_cursor.rs
index ae29e62e6..f89e39137 100644
--- a/crates/ui-egui/src/tool_cursor.rs
+++ b/crates/ui-egui/src/tool_cursor.rs
@@ -1,5 +1,9 @@
-//! Canvas cursors must move with the OS pointer, independently of the canvas frame rate.
-//! Windows' stock crosshair inverts grey into grey, so use our black/white bitmap there too.
+//! Canvas cursors must move with the OS pointer, independently of the canvas frame rate: the brush
+//! outline and crosshairs are OS cursor bitmaps on every desktop platform (Windows, macOS, X11 and
+//! Wayland), so they track the hardware pointer instead of trailing it by the app's render,
+//! present and compositor latency. A painted outline lagged the pointer by several refreshes on
+//! Linux and macOS and "jumped to catch up" on slow frames (#1343). Windows' stock crosshair
+//! inverts grey into grey, so the crosshairs are our black/white bitmap there too.
use std::sync::Arc;
@@ -7,8 +11,12 @@ use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, vec2};
mod hand;
-/// winit's cursor limit. Keep allocations bounded even for hostile brush sizes or zooms.
-const MAX_SIDE: u16 = 2048;
+/// The largest cursor bitmap, in physical pixels; a larger tip paints its outline instead (with a
+/// small OS crosshair at the hotspot). Windows takes winit's limit. Elsewhere, X servers and
+/// hardware cursor planes commonly cap cursors at 256 px and fall back to slow software cursors
+/// (or reject them) past that, so stay within it there (#968 used 128). Either way it keeps
+/// allocations bounded for hostile brush sizes or zooms.
+const MAX_SIDE: u16 = if cfg!(target_os = "windows") { 2048 } else { 255 };
/// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -61,6 +69,20 @@ pub(crate) fn crosshair(painter: &Painter, at: Pos2, length: f32, gap: f32) -> C
show(painter, at, Shape::Crosshair { length, gap })
}
+/// Can this pass show an OS cursor bitmap? eframe's immediate viewports and its web integration
+/// don't upload cursor images; every desktop root viewport does (winit custom cursors).
+fn native(ctx: &egui::Context) -> bool {
+ cfg!(not(target_arch = "wasm32")) && ctx.viewport_id() == egui::ViewportId::ROOT
+}
+
+/// Bitmap pixels per egui point. winit takes an `NSCursor` image's dimensions as logical points on
+/// macOS, so there the bitmap scales only with the UI zoom (the monitor's density would enlarge it
+/// a second time on Retina displays); Windows, X11 and Wayland take physical pixels. (The macOS
+/// sizing is from @jerrykimo's #968.)
+pub(crate) fn native_scale(ctx: &egui::Context) -> f32 {
+ if cfg!(target_os = "macos") { ctx.zoom_factor() } else { ctx.pixels_per_point() }
+}
+
/// The Hand tool's pointer: an open hand, a fist while it drags (`closed`). winit maps `Grab` and
/// `Grabbing` to the four-arrow move cursor on Windows, so there it is a bitmap; macOS and the
/// Linux themes already draw hands, and the OS moves those without waiting for a frame.
@@ -69,7 +91,7 @@ pub(crate) fn hand(ctx: &egui::Context, closed: bool) -> CursorIcon {
}
fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon {
- if bitmap && let Some(image) = cached_image(ctx, Shape::Hand { closed }, ctx.pixels_per_point()) {
+ if bitmap && let Some(image) = cached_image(ctx, Shape::Hand { closed }, native_scale(ctx)) {
ctx.set_cursor_image(Some(image));
return CursorIcon::None;
}
@@ -78,10 +100,9 @@ fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon {
fn show(painter: &Painter, at: Pos2, shape: Shape) -> CursorIcon {
let ctx = painter.ctx();
- // eframe's immediate viewports and web integration do not upload cursor images. Keep their
- // existing painter path. Other native platforms retain their existing cursor behaviour.
- if cfg!(target_os = "windows") && ctx.viewport_id() == egui::ViewportId::ROOT {
- let scale = ctx.pixels_per_point();
+ // Where cursor images can't be uploaded (immediate viewports, the web), paint the shape.
+ if native(ctx) {
+ let scale = native_scale(ctx);
if let Some(image) = cached_image(ctx, shape, scale) {
ctx.set_cursor_image(Some(image));
return CursorIcon::None;
diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/tool_cursor/tests.rs
index 6a55d3779..3ce97b79b 100644
--- a/crates/ui-egui/src/tool_cursor/tests.rs
+++ b/crates/ui-egui/src/tool_cursor/tests.rs
@@ -1,9 +1,9 @@
use super::*;
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
use egui::{Event, Modifiers, PointerButton, pos2};
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
use egui_kittest::Harness;
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
use serde_json::json;
fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 {
@@ -48,6 +48,16 @@ fn precise_and_tip_centre_crosshairs_have_distinct_hotspots() {
assert!(alpha(&solid, solid.hotspot[0], solid.hotspot[1]) > 230);
}
+/// Off Windows a tip stays within what X servers and hardware cursor planes take (256 px); a
+/// larger one falls back to the painted outline. Windows takes far larger cursors.
+#[test]
+fn cursor_bitmaps_stay_within_the_platform_limit() {
+ let fits = |radius: f32| rasterize(Shape::Circle { radius, centre: false }, 1.0).map(|i| i.size[0]);
+ assert!(fits(100.0).is_some_and(|side| side <= 255));
+ assert_eq!(fits(200.0).is_some(), cfg!(target_os = "windows"));
+ assert!(fits(200.0).is_none_or(|side| side <= 2048));
+}
+
#[test]
fn hostile_sizes_are_rejected_before_allocating() {
for radius in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, 2048.0] {
@@ -180,7 +190,7 @@ fn lifecycle_clears_sticky_images_and_respects_later_widgets() {
}
#[test]
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
fn ordinary_brush_cursor_is_not_part_of_the_canvas_draw_list() {
let ctx = egui::Context::default();
ctx.add_plugin(CursorLifecycle);
@@ -243,7 +253,7 @@ fn write_cursor_preview() {
std::fs::write(path, png).unwrap();
}
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
fn harness() -> Harness<'static, crate::PhotocraftApp> {
let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
@@ -272,7 +282,7 @@ fn harness() -> Harness<'static, crate::PhotocraftApp> {
}
#[test]
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
fn brush_hover_uses_an_os_bitmap_that_survives_motion_but_not_tool_or_panel_changes() {
let mut h = harness();
let initial = h.output().platform_output.cursor_image.clone().expect("brush hover must reach the OS, not the painter");
@@ -290,11 +300,17 @@ fn brush_hover_uses_an_os_bitmap_that_survives_motion_but_not_tool_or_panel_chan
assert!(h.output().platform_output.cursor_image.is_some());
// Windows has no stock hand (winit maps `Grab` to the move cursor), so the Hand gets the open
- // hand as a bitmap too (#2196).
+ // hand as a bitmap too (#2196); macOS and the Linux themes draw their own.
h.state_mut().ui.tool = crate::Tool::Hand;
h.run_steps(2);
- let hand = h.output().platform_output.cursor_image.clone().expect("the Hand's open hand reaches the OS as a bitmap");
- assert_eq!(hand.rgba, rasterize(Shape::Hand { closed: false }, h.ctx.pixels_per_point()).unwrap().rgba);
+ let hand = h.output().platform_output.cursor_image.clone();
+ if cfg!(target_os = "windows") {
+ let hand = hand.expect("the Hand's open hand reaches the OS as a bitmap");
+ assert_eq!(hand.rgba, rasterize(Shape::Hand { closed: false }, h.ctx.pixels_per_point()).unwrap().rgba);
+ } else {
+ assert!(hand.is_none(), "the OS draws the hand");
+ assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::Grab);
+ }
h.state_mut().ui.tool = crate::Tool::Brush;
h.state_mut().run("prefs.set", json!({"path": "cursors.painting", "value": "standard"})).unwrap();
@@ -304,7 +320,7 @@ fn brush_hover_uses_an_os_bitmap_that_survives_motion_but_not_tool_or_panel_chan
}
#[test]
-#[cfg(target_os = "windows")]
+#[cfg(not(target_arch = "wasm32"))]
fn painting_preference_and_zoom_change_the_native_cursor_without_changing_pointer_input() {
let mut h = harness();
let image = h.output().platform_output.cursor_image.clone().unwrap();