Skip to content

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

Windows: brush tips and crosshairs are native bitmap cursors (#1160)

Merle8d95a564e361
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 5100e88c8..4d7c41dda 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -342,20 +342,13 @@ pub(crate) fn stroke_command(tool: Tool) -> &'static str {
}
/// Windows' crosshair cursor inverts the pixels under it, so over mid-grey (the pasteboard, many
-/// photos) it vanishes (#737). There the canvas draws a black-and-white crosshair itself, like
-/// Photoshop's, and hides the system one.
+/// 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.
fn visible_crosshair(icon: egui::CursorIcon, painter: &egui::Painter, p: Pos2, draw: bool) -> egui::CursorIcon {
if !draw || icon != egui::CursorIcon::Crosshair {
return icon;
}
- let p = pos2(p.x.round() + 0.5, p.y.round() + 0.5);
- let (gap, len) = (2.0, 8.0);
- for (w, c) in [(3.0, Color32::from_black_alpha(160)), (1.0, Color32::from_white_alpha(235))] {
- for d in [vec2(1.0, 0.0), vec2(-1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, -1.0)] {
- painter.line_segment([p + d * gap, p + d * len], Stroke::new(w, c));
- }
- }
- egui::CursorIcon::None
+ crate::tool_cursor::crosshair(painter, p, 8.0, 2.0)
}
/// The Pencil's cursor at `doc` (document pixels): the whole-pixel square its dab fills
@@ -2468,22 +2461,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let brush = &app.session.tools.brush;
let full = (brush.size / 2.0 * view.zoom).max(1.0);
let r = if cur.painting == PaintingCursor::NormalTip { (full * (0.5 + 0.5 * brush.hardness.clamp(0.0, 1.0))).max(1.0) } else { full };
- let crosshair = |len: f32| {
- for (w, c) in [(2.5, Color32::from_black_alpha(140)), (1.0, Color32::from_white_alpha(220))] {
- painter.line_segment([p - vec2(len, 0.0), p + vec2(len, 0.0)], Stroke::new(w, c));
- painter.line_segment([p - vec2(0.0, len), p + vec2(0.0, len)], Stroke::new(w, c));
- }
- };
match cur.painting {
PaintingCursor::Standard => egui::CursorIcon::Default,
- PaintingCursor::Precise => {
- crosshair(6.0);
- egui::CursorIcon::None
- }
- _ if painting && cur.show_only_crosshair_while_painting => {
- crosshair(5.0);
- egui::CursorIcon::None
- }
+ PaintingCursor::Precise => crate::tool_cursor::crosshair(&painter, p, 6.0, 0.0),
+ _ if painting && cur.show_only_crosshair_while_painting => crate::tool_cursor::crosshair(&painter, p, 5.0, 0.0),
// The Pencil: the square of whole pixels its dab fills, on the pixel grid.
_ if tool == Tool::Pencil => {
let ppp = painter.ctx().pixels_per_point();
@@ -2493,17 +2474,13 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
painter.rect_stroke(sq, 0.0, Stroke::new(px, Color32::from_white_alpha(230)), egui::StrokeKind::Inside);
// Too small to see where it is: the hotspot as well.
if cur.show_crosshair_in_brush_tip || sq.width() < 6.0 {
- crosshair(4.0);
+ crate::tool_cursor::crosshair(&painter, p, 4.0, 0.0);
}
egui::CursorIcon::None
}
_ => {
- painter.circle_stroke(p, r + 0.5, Stroke::new(1.0, Color32::from_black_alpha(140)));
- painter.circle_stroke(p, r, Stroke::new(1.0, Color32::from_white_alpha(220)));
- if brush_tip_centre(tool, alt || app.ui.shell.sticky_alt, cur.show_crosshair_in_brush_tip, r) {
- crosshair(3.0);
- }
- egui::CursorIcon::None
+ let centre = brush_tip_centre(tool, alt || app.ui.shell.sticky_alt, cur.show_crosshair_in_brush_tip, r);
+ crate::tool_cursor::circle(&painter, p, r, centre)
}
}
}
@@ -3655,8 +3632,8 @@ mod tabs_tests;
#[cfg(test)]
mod tests {
#[test]
- fn windows_draws_its_own_crosshair() {
- // #737: Windows' inverting crosshair vanishes over mid-grey; the canvas draws one instead.
+ fn windows_uses_a_visible_crosshair() {
+ // #737: Windows' inverting crosshair vanishes over mid-grey; use a black/white glyph.
let ctx = egui::Context::default();
let painter = egui::Painter::new(ctx, egui::LayerId::background(), egui::Rect::EVERYTHING);
let p = egui::pos2(10.0, 10.0);
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 88e3dbc6b..9e0ad8018 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -130,6 +130,7 @@ pub mod tiff_options_ui;
mod timeline_ui;
mod titlebar;
pub mod tone;
+mod tool_cursor;
pub mod tool_feedback;
pub mod transform_tex;
pub mod transform_tool;
@@ -1358,6 +1359,7 @@ impl PhotocraftApp {
/// Install fonts, image loaders and the theme. Call from the app creator when possible so the
/// very first frame renders; otherwise `logic` does it and the first frame is skipped.
pub fn setup_context(ctx: &egui::Context, kind: theme::ThemeKind) {
+ ctx.add_plugin(tool_cursor::CursorLifecycle);
theme::install_fonts(ctx);
egui_extras::install_image_loaders(ctx);
theme::apply(ctx, kind);
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index f80ed1416..5d53d96f1 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -120,6 +120,11 @@ pub struct Tokens {
}
impl Tokens {
+ /// Tool outlines need contrast on arbitrary document pixels, independently of UI theme.
+ pub(crate) fn cursor_outline() -> [Color32; 2] {
+ [Color32::from_black_alpha(160), Color32::from_white_alpha(235)]
+ }
+
pub fn for_kind(kind: ThemeKind) -> Self {
match kind {
// Sampled from Photoshop 2026's default brightness (raw display values).
diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/tool_cursor.rs
new file mode 100644
index 000000000..b6e57a009
--- /dev/null
+++ b/crates/ui-egui/src/tool_cursor.rs
@@ -0,0 +1,183 @@
+//! 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.
+
+use std::sync::Arc;
+
+use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, vec2};
+
+/// winit's cursor limit. Keep allocations bounded even for hostile brush sizes or zooms.
+const MAX_SIDE: u16 = 2048;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Shape {
+ Circle { radius: f32, centre: bool },
+ Crosshair { length: f32, gap: f32 },
+}
+
+#[derive(Clone)]
+struct Cached {
+ shape: Shape,
+ scale: f32,
+ image: CustomCursorImage,
+}
+
+/// The image is sticky in egui's platform output. Clear it every pass, including when a
+/// document closes or the pointer leaves the canvas; a later widget's cursor takes precedence.
+pub(crate) struct CursorLifecycle;
+
+impl egui::plugin::Plugin for CursorLifecycle {
+ fn debug_name(&self) -> &'static str {
+ "PhotoCraft tool cursor"
+ }
+
+ fn on_begin_pass(&mut self, ui: &mut egui::Ui) {
+ ui.ctx().set_cursor_image(None);
+ }
+
+ fn on_end_pass(&mut self, ui: &mut egui::Ui) {
+ ui.ctx().output_mut(|o| {
+ if o.cursor_image.is_some() {
+ if o.cursor_icon == CursorIcon::None {
+ // None marks our request until all widgets have had their say. A backend
+ // that cannot upload the bitmap must still leave a visible pointer.
+ o.cursor_icon = CursorIcon::Crosshair;
+ } else {
+ o.cursor_image = None;
+ }
+ }
+ });
+ }
+}
+
+pub(crate) fn circle(painter: &Painter, at: Pos2, radius: f32, centre: bool) -> CursorIcon {
+ show(painter, at, Shape::Circle { radius, centre })
+}
+
+pub(crate) fn crosshair(painter: &Painter, at: Pos2, length: f32, gap: f32) -> CursorIcon {
+ show(painter, at, Shape::Crosshair { length, gap })
+}
+
+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();
+ if let Some(image) = cached_image(ctx, shape, scale) {
+ ctx.set_cursor_image(Some(image));
+ return CursorIcon::None;
+ }
+ // An enormous tip cannot fit an OS cursor. Preserve its full-size outline, with an OS
+ // crosshair at the hotspot so the user still gets immediate position feedback.
+ paint(painter, at, shape);
+ if let Some(image) = cached_image(ctx, Shape::Crosshair { length: 6.0, gap: 2.0 }, scale) {
+ ctx.set_cursor_image(Some(image));
+ }
+ return CursorIcon::None;
+ }
+ paint(painter, at, shape);
+ CursorIcon::None
+}
+
+fn cached_image(ctx: &egui::Context, shape: Shape, scale: f32) -> Option<CustomCursorImage> {
+ let id = egui::Id::new("photocraft-tool-cursor");
+ if let Some(cached) = ctx.data(|d| d.get_temp::<Cached>(id))
+ && cached.shape == shape
+ && cached.scale == scale
+ {
+ return Some(cached.image);
+ }
+ let image = rasterize(shape, scale)?;
+ ctx.data_mut(|d| d.insert_temp(id, Cached { shape, scale, image: image.clone() }));
+ Some(image)
+}
+
+fn paint(painter: &Painter, at: Pos2, shape: Shape) {
+ if extent(shape).is_none() {
+ return;
+ }
+ let [dark, light] = crate::theme::Tokens::cursor_outline();
+ for (width, color) in [(3.0, dark), (1.0, light)] {
+ let stroke = Stroke::new(width, color);
+ match shape {
+ Shape::Circle { radius, centre } => {
+ painter.circle_stroke(at, radius, stroke);
+ if centre {
+ paint_crosshair(painter, at, 3.0, 0.0, stroke);
+ }
+ }
+ Shape::Crosshair { length, gap } => paint_crosshair(painter, at, length, gap, stroke),
+ }
+ }
+}
+
+fn paint_crosshair(painter: &Painter, at: Pos2, length: f32, gap: f32, stroke: Stroke) {
+ for d in [vec2(1.0, 0.0), vec2(-1.0, 0.0), vec2(0.0, 1.0), vec2(0.0, -1.0)] {
+ painter.line_segment([at + d * gap, at + d * length], stroke);
+ }
+}
+
+/// Distance to the nearest arm (round caps), in physical pixels from the hotspot.
+fn cross_distance(x: f32, y: f32, length: f32, gap: f32) -> f32 {
+ let horizontal = (x - x.clamp(gap, length)).hypot(y);
+ let vertical = x.hypot(y - y.clamp(gap, length));
+ horizontal.min(vertical)
+}
+
+fn extent(shape: Shape) -> Option<f32> {
+ Some(match shape {
+ Shape::Circle { radius, centre } => {
+ if !radius.is_finite() || radius <= 0.0 {
+ return None;
+ }
+ if centre { radius.max(3.0) } else { radius }
+ }
+ Shape::Crosshair { length, gap } => {
+ if !length.is_finite() || !gap.is_finite() || gap < 0.0 || length < gap {
+ return None;
+ }
+ length
+ }
+ })
+}
+
+fn rasterize(shape: Shape, scale: f32) -> Option<CustomCursorImage> {
+ if !scale.is_finite() || scale <= 0.0 {
+ return None;
+ }
+ let extent = extent(shape)?;
+ // Odd dimensions put the hotspot on the centre pixel at every DPI. Include the outline
+ // and its antialiasing fringe, then check before converting or allocating.
+ let half = ((extent + 1.5) * scale + 1.0).ceil();
+ if !half.is_finite() || half > f32::from((MAX_SIDE - 1) / 2) {
+ return None;
+ }
+ let hot = half as u16;
+ let side = hot * 2 + 1;
+ let bytes = usize::from(side).checked_mul(usize::from(side))?.checked_mul(4)?;
+ let mut rgba = Vec::with_capacity(bytes);
+ let [dark, light] = crate::theme::Tokens::cursor_outline();
+ for row in 0..side {
+ let y = (f32::from(row) - f32::from(hot)).abs();
+ for col in 0..side {
+ let x = (f32::from(col) - f32::from(hot)).abs();
+ let distance = match shape {
+ Shape::Circle { radius, centre } => {
+ let ring = (x.hypot(y) - radius * scale).abs();
+ if centre { ring.min(cross_distance(x, y, 3.0 * scale, 0.0)) } else { ring }
+ }
+ Shape::Crosshair { length, gap } => cross_distance(x, y, length * scale, gap * scale),
+ };
+ let a_dark = (1.5 * scale + 0.5 - distance).clamp(0.0, 1.0) * f32::from(dark.a()) / 255.0;
+ let a_light = (0.5 * scale + 0.5 - distance).clamp(0.0, 1.0) * f32::from(light.a()) / 255.0;
+ let alpha = a_light + a_dark * (1.0 - a_light);
+ // Straight RGBA, as required by winit, not egui's premultiplied representation.
+ let white = if alpha > 0.0 { (255.0 * a_light / alpha).round() as u8 } else { 0 };
+ rgba.extend_from_slice(&[white, white, white, (255.0 * alpha).round() as u8]);
+ }
+ }
+ Some(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] })
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/tool_cursor/tests.rs
new file mode 100644
index 000000000..904bf1729
--- /dev/null
+++ b/crates/ui-egui/src/tool_cursor/tests.rs
@@ -0,0 +1,238 @@
+use super::*;
+#[cfg(target_os = "windows")]
+use egui::{Event, Modifiers, PointerButton, pos2};
+#[cfg(target_os = "windows")]
+use egui_kittest::Harness;
+#[cfg(target_os = "windows")]
+use serde_json::json;
+
+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 frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
+ let mut output = ctx.run_ui(Default::default(), draw);
+ // These tests inspect cursor output without a renderer.
+ output.textures_delta.clear();
+ output
+}
+
+#[test]
+fn bitmap_has_a_transparent_hotspot_and_the_correct_radius_at_each_dpi() {
+ for scale in [1.0, 1.25, 1.5, 2.0, 3.0] {
+ let radius = 20.0;
+ let image = rasterize(Shape::Circle { radius, centre: false }, scale).unwrap();
+ let [x, y] = image.hotspot;
+ assert_eq!(image.size, [2 * x + 1, 2 * y + 1]);
+ assert_eq!(image.rgba.len(), usize::from(image.size[0]).pow(2) * 4);
+ assert_eq!(alpha(&image, x, y), 0, "the document is visible through the tip");
+ assert_eq!(alpha(&image, 0, 0), 0);
+ let edge = x + (radius * scale) as u16;
+ assert!(alpha(&image, edge, y) > 230);
+ assert_eq!(alpha(&image, x - (radius * scale) as u16, y), alpha(&image, edge, y));
+ let edge_byte = (usize::from(y) * usize::from(image.size[0]) + usize::from(edge)) * 4;
+ assert_eq!(image.rgba[edge_byte], 242, "straight RGBA: 235/255 white over 160/255 black (premultiplied would be 235)");
+ assert!(image.rgba.as_chunks::<4>().0.iter().any(|p| p[3] > 0 && p[0] == 0), "dark outline stays visible on white");
+ }
+}
+
+#[test]
+fn precise_and_tip_centre_crosshairs_have_distinct_hotspots() {
+ let ring = rasterize(Shape::Circle { radius: 20.0, centre: true }, 1.0).unwrap();
+ assert!(alpha(&ring, ring.hotspot[0], ring.hotspot[1]) > 230);
+ let precise = rasterize(Shape::Crosshair { length: 8.0, gap: 2.0 }, 1.0).unwrap();
+ let [x, y] = precise.hotspot;
+ assert_eq!(alpha(&precise, x, y), 0);
+ assert!(alpha(&precise, x + 5, y) > 230);
+ let solid = rasterize(Shape::Crosshair { length: 6.0, gap: 0.0 }, 1.0).unwrap();
+ assert!(alpha(&solid, solid.hotspot[0], solid.hotspot[1]) > 230);
+}
+
+#[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] {
+ assert!(rasterize(Shape::Circle { radius, centre: false }, 1.0).is_none());
+ }
+ for scale in [f32::NAN, f32::INFINITY, -1.0, 0.0, f32::MAX] {
+ assert!(rasterize(Shape::Circle { radius: 20.0, centre: false }, scale).is_none());
+ }
+ for (length, gap) in [(1.0, 2.0), (8.0, -1.0), (f32::NAN, 0.0), (8.0, f32::NAN)] {
+ assert!(rasterize(Shape::Crosshair { length, gap }, 1.0).is_none());
+ }
+}
+
+#[test]
+fn unchanged_geometry_reuses_the_os_upload_and_dpi_invalidates_it() {
+ let ctx = egui::Context::default();
+ let shape = Shape::Circle { radius: 20.0, centre: false };
+ let a = cached_image(&ctx, shape, 1.0).unwrap();
+ let b = cached_image(&ctx, shape, 1.0).unwrap();
+ assert!(Arc::ptr_eq(&a.rgba, &b.rgba));
+ let scaled = cached_image(&ctx, shape, 2.0).unwrap();
+ assert!(!Arc::ptr_eq(&a.rgba, &scaled.rgba));
+ assert!(scaled.size[0] > a.size[0]);
+ let larger = cached_image(&ctx, Shape::Circle { radius: 40.0, centre: false }, 2.0).unwrap();
+ assert!(larger.size[0] > scaled.size[0]);
+}
+
+#[test]
+fn lifecycle_clears_sticky_images_and_respects_later_widgets() {
+ let ctx = egui::Context::default();
+ ctx.add_plugin(CursorLifecycle);
+ let image = rasterize(Shape::Circle { radius: 20.0, centre: false }, 1.0).unwrap();
+ let output = frame(&ctx, |ui| {
+ ui.ctx().set_cursor_image(Some(image.clone()));
+ ui.ctx().set_cursor_icon(CursorIcon::None);
+ });
+ assert!(output.platform_output.cursor_image.is_some());
+ assert_eq!(output.platform_output.cursor_icon, CursorIcon::Crosshair, "visible fallback if the OS rejects a bitmap");
+ let output = frame(&ctx, |_| {});
+ assert!(output.platform_output.cursor_image.is_none(), "leaving the canvas cannot keep its bitmap");
+ let output = frame(&ctx, |ui| {
+ ui.ctx().set_cursor_image(Some(image.clone()));
+ ui.ctx().set_cursor_icon(CursorIcon::None);
+ ui.ctx().set_cursor_icon(CursorIcon::ResizeHorizontal);
+ });
+ assert!(output.platform_output.cursor_image.is_none());
+ assert_eq!(output.platform_output.cursor_icon, CursorIcon::ResizeHorizontal);
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+fn ordinary_brush_cursor_is_not_part_of_the_canvas_draw_list() {
+ let ctx = egui::Context::default();
+ ctx.add_plugin(CursorLifecycle);
+ let output = frame(&ctx, |ui| {
+ let icon = circle(ui.painter(), pos2(100.0, 100.0), 20.0, true);
+ ui.ctx().set_cursor_icon(icon);
+ });
+ assert!(output.platform_output.cursor_image.is_some());
+ assert!(output.shapes.iter().all(|s| matches!(s.shape, egui::Shape::Noop)));
+
+ let output = frame(&ctx, |ui| {
+ let icon = circle(ui.painter(), pos2(100.0, 100.0), 3000.0, false);
+ ui.ctx().set_cursor_icon(icon);
+ });
+ let image = output.platform_output.cursor_image.unwrap();
+ assert!(image.size[0] < 32, "oversized tips retain a small native hotspot");
+ assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Circle(_))), "the full tip is not silently shrunk");
+}
+
+/// Run explicitly for visual QA: native cursors are absent from GPU screenshots.
+#[test]
+#[ignore = "writes target/tool-cursor-preview.png for visual inspection"]
+fn write_cursor_preview() {
+ let cases = [
+ (Shape::Circle { radius: 20.0, centre: false }, 1.0),
+ (Shape::Circle { radius: 20.0, centre: false }, 1.5),
+ (Shape::Circle { radius: 20.0, centre: true }, 2.0),
+ (Shape::Crosshair { length: 8.0, gap: 2.0 }, 2.0),
+ (Shape::Crosshair { length: 6.0, gap: 0.0 }, 2.0),
+ ];
+ let (width, height) = (600_usize, 500_usize);
+ let mut rgba = vec![255; width * height * 4];
+ for (col, background) in [0_u8, 128, 255].into_iter().enumerate() {
+ for y in 0..height {
+ for x in col * 200..(col + 1) * 200 {
+ rgba[(y * width + x) * 4..(y * width + x) * 4 + 3].fill(background);
+ }
+ }
+ for (row, &(shape, scale)) in cases.iter().enumerate() {
+ let image = rasterize(shape, scale).unwrap();
+ let side = usize::from(image.size[0]);
+ let x0 = col * 200 + 100 - usize::from(image.hotspot[0]);
+ let y0 = row * 100 + 50 - usize::from(image.hotspot[1]);
+ for (i, pixel) in image.rgba.as_chunks::<4>().0.iter().enumerate() {
+ let at = ((y0 + i / side) * width + x0 + i % side) * 4;
+ let a = f32::from(pixel[3]) / 255.0;
+ let value = (f32::from(pixel[0]) * a + f32::from(background) * (1.0 - a)).round() as u8;
+ rgba[at..at + 3].fill(value);
+ }
+ }
+ }
+ let image = photocraft_codecs::Image::from_u8(width as u32, height as u32, photocraft_codecs::ChannelLayout::Rgba, rgba).unwrap();
+ let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/tool-cursor-preview.png");
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(path, png).unwrap();
+}
+
+#[cfg(target_os = "windows")]
+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();
+ app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap();
+ app.ui.tool = crate::Tool::Brush;
+ app.sync_views();
+ let mut h = Harness::builder().with_size(vec2(600.0, 500.0)).build_ui_state(
+ |ui, app: &mut crate::PhotocraftApp| {
+ let ctx = ui.ctx().clone();
+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
+ return;
+ }
+ egui::Panel::top("cursor-test-toolbar").show(ui, |ui| {
+ ui.label("Toolbar");
+ });
+ egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
+ crate::dialogs::show(app, &ctx);
+ },
+ app,
+ );
+ crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ h.run_steps(4);
+ h.event(Event::PointerMoved(h.state().last_canvas_rect.center()));
+ h.run_steps(3);
+ h
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+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");
+ let p = h.state().last_canvas_rect.center();
+ h.event(Event::PointerMoved(p + vec2(25.0, 12.0)));
+ h.run_steps(2);
+ let moved = h.output().platform_output.cursor_image.clone().unwrap();
+ assert!(Arc::ptr_eq(&initial.rgba, &moved.rgba), "moving does not rasterize or re-upload the cursor");
+
+ h.event(Event::PointerMoved(pos2(20.0, 12.0)));
+ h.run_steps(2);
+ assert!(h.output().platform_output.cursor_image.is_none(), "toolbar restores the normal pointer");
+ h.event(Event::PointerMoved(p));
+ h.run_steps(2);
+ assert!(h.output().platform_output.cursor_image.is_some());
+
+ h.state_mut().ui.tool = crate::Tool::Hand;
+ h.run_steps(2);
+ assert!(h.output().platform_output.cursor_image.is_none());
+ 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();
+ h.run_steps(2);
+ assert!(h.output().platform_output.cursor_image.is_none());
+ assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::Default);
+}
+
+#[test]
+#[cfg(target_os = "windows")]
+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();
+ h.state_mut().ui.views[0].zoom *= 2.0;
+ h.run_steps(2);
+ assert!(h.output().platform_output.cursor_image.as_ref().unwrap().size[0] > image.size[0]);
+ h.state_mut().run("prefs.set", json!({"path": "cursors.showOnlyCrosshairWhilePainting", "value": true})).unwrap();
+ let pos = h.state().last_canvas_rect.center();
+ h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
+ h.step();
+ h.event(Event::PointerMoved(pos + vec2(20.0, 0.0)));
+ h.run_steps(2);
+ let cross_size = h.output().platform_output.cursor_image.as_ref().unwrap().size[0];
+ assert!(cross_size < image.size[0]);
+ assert_eq!(h.ctx.pointer_latest_pos(), Some(pos + vec2(20.0, 0.0)));
+ h.event(Event::PointerButton { pos: pos + vec2(20.0, 0.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
+ h.run_steps(2);
+ assert!(h.output().platform_output.cursor_image.as_ref().unwrap().size[0] > cross_size);
+}