PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Hand tool: an open hand and a fist as the pointer on Windows, and the fist while panning everywhere (#2196) (#2221)
Sir Starch1f84f19caf30
diff --git a/crates/ui-egui/src/camera_raw_preview_ui.rs b/crates/ui-egui/src/camera_raw_preview_ui.rsindex 80c4b0dd2..a0a1d0cdb 100644--- a/crates/ui-egui/src/camera_raw_preview_ui.rs+++ b/crates/ui-egui/src/camera_raw_preview_ui.rs@@ -119,7 +119,7 @@ pub(crate) fn interact(ui: &mut Ui, state: &mut CameraRawPreviewState, viewport:None => {}}response.clone().on_hover_cursor(if hand {- egui::CursorIcon::Grab+ crate::tool_cursor::hand(ui.ctx(), false)} else if !zoom_tool {egui::CursorIcon::Crosshair} else if modifiers.alt {@@ -139,7 +139,7 @@ pub(crate) fn interact(ui: &mut Ui, state: &mut CameraRawPreviewState, viewport:let mut zoom_box = None;if panning && (response.dragged_by(PointerButton::Primary) || response.dragged_by(PointerButton::Middle)) {state.pan(response.drag_delta(), viewport, size);- ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);+ ui.ctx().set_cursor_icon(crate::tool_cursor::hand(ui.ctx(), true));} else if response.dragged_by(PointerButton::Primary)&& let Some(capture) = capture{diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 52e349b5c..ac29ba8c8 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2513,9 +2513,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:let d = xf.unmap_vec(d) / (view.zoom / ppp);view.center[0] -= d.x;view.center[1] -= d.y;- ctx.set_cursor_icon(egui::CursorIcon::Grabbing);+ ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true));} else if free_hover && (space_pan || hand) {- ctx.set_cursor_icon(egui::CursorIcon::Grab);+ ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, false));} else if picking && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect) {if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise {ctx.set_cursor_icon(egui::CursorIcon::Crosshair);@@ -2545,6 +2545,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:let d = xf.unmap_vec(response.drag_delta()) / (view.zoom / ppp);view.center[0] -= d.x;view.center[1] -= d.y;+ // The tool cursors below are skipped while panning: the fist is set here (#2196).+ ctx.set_cursor_icon(crate::tool_cursor::hand(&ctx, true));} else if primary {let mods = ui.input(|i| i.modifiers);// An ⌥-click the window manager took never arrives; say so (alt_grab.rs).@@ -2955,13 +2957,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:egui::CursorIcon::Crosshair}Tool::Move => egui::CursorIcon::Move,- Tool::Hand => {- if response.dragged() {- egui::CursorIcon::Grabbing- } else {- egui::CursorIcon::Grab- }- }+ // Dragging is handled with the pan itself, above.+ Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false),Tool::RotateView => crate::rotate_view::cursor(response.dragged()),Tool::Zoom => {if zoom_out(alt) {diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rsindex 727d3b2c5..df51d69d5 100644--- a/crates/ui-egui/src/input_tests.rs+++ b/crates/ui-egui/src/input_tests.rs@@ -563,6 +563,77 @@ fn eyedropper_and_alt_sampling_show_a_pipette() {assert_eq!(precise(&mut h), (egui::CursorIcon::Crosshair, windows));}+/// The Hand tool, and Space held over another tool, show an open hand while hovering and a fist+/// while they pan (#2196). The OS draws those everywhere but Windows, where winit maps `Grab` to+/// the four-arrow move cursor, so the app hands it a bitmap there (`Crosshair` is the fallback).+#[test]+fn hand_tool_shows_an_open_hand_and_a_fist_while_panning() {+ let mut h = harness();+ let p = h.state().last_canvas_rect.center();+ let windows = cfg!(target_os = "windows");+ // The icon the OS gets, and the bitmap for it if any.+ let pointer = |h: &Harness<'static, PhotocraftApp>| {+ let out = &h.output().platform_output;+ (out.cursor_icon, out.cursor_image.as_ref().map(|i| i.rgba.clone()))+ };+ let expect = |got: (egui::CursorIcon, Option<std::sync::Arc<[u8]>>), native: egui::CursorIcon, what: &str| {+ if windows {+ assert_eq!(got.0, egui::CursorIcon::Crosshair, "{what}: fallback under the bitmap");+ assert!(got.1.is_some(), "{what}: a bitmap");+ } else {+ assert_eq!(got, (native, None), "{what}");+ }+ got.1+ };++ h.state_mut().ui.tool = crate::state::Tool::Hand;+ h.hover_at(p);+ h.run_steps(2);+ let open = expect(pointer(&h), egui::CursorIcon::Grab, "hovering with the Hand");+ press(&mut h, p, true);+ for i in 1..=3 {+ h.hover_at(p + vec2(10.0 * i as f32, 0.0));+ h.run_steps(1);+ }+ let fist = expect(pointer(&h), egui::CursorIcon::Grabbing, "dragging with the Hand");+ if windows {+ assert_ne!(open, fist, "a fist is not the open hand");+ }+ press(&mut h, p + vec2(30.0, 0.0), false);+ h.run_steps(2);+ expect(pointer(&h), egui::CursorIcon::Grab, "after the drag");++ // Space turns any tool into the Hand while held.+ h.state_mut().ui.tool = crate::state::Tool::Brush;+ h.hover_at(p);+ h.run_steps(2);+ let brush = pointer(&h);+ assert_ne!(brush.0, egui::CursorIcon::Grab, "the Brush is not a hand");+ h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });+ h.run_steps(2);+ expect(pointer(&h), egui::CursorIcon::Grab, "Space over the Brush");+ h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });+ h.run_steps(2);+ assert_eq!(pointer(&h), brush, "released: the Brush's own pointer is back");+}++/// With a dialog open the canvas still pans, and the Hand's pointer follows (#2196).+#[test]+fn hand_pointer_over_the_canvas_under_a_dialog() {+ let mut h = harness();+ open_dialog(&mut h);+ h.state_mut().ui.tool = crate::state::Tool::Hand;+ let p = free_canvas(&h);+ h.hover_at(p);+ h.run_steps(3);+ let out = &h.output().platform_output;+ if cfg!(target_os = "windows") {+ assert!(out.cursor_image.is_some());+ } else {+ assert_eq!(out.cursor_icon, egui::CursorIcon::Grab);+ }+}+/// Esc while drawing with the Pen ends the path where it is, left open, and keeps it as the work/// path, as ↩ does; it used to throw the path away (#1769).#[test]diff --git a/crates/ui-egui/src/tool_cursor.rs b/crates/ui-egui/src/tool_cursor.rsindex b6e57a009..ae29e62e6 100644--- a/crates/ui-egui/src/tool_cursor.rs+++ b/crates/ui-egui/src/tool_cursor.rs@@ -5,13 +5,17 @@ use std::sync::Arc;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;+/// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags.#[derive(Clone, Copy, Debug, PartialEq)]enum Shape {Circle { radius: f32, centre: bool },Crosshair { length: f32, gap: f32 },+ Hand { closed: bool },}#[derive(Clone)]@@ -57,6 +61,21 @@ pub(crate) fn crosshair(painter: &Painter, at: Pos2, length: f32, gap: f32) -> Cshow(painter, at, Shape::Crosshair { length, gap })}+/// 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.+pub(crate) fn hand(ctx: &egui::Context, closed: bool) -> CursorIcon {+ hand_with(ctx, closed, cfg!(target_os = "windows") && ctx.viewport_id() == egui::ViewportId::ROOT)+}++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()) {+ ctx.set_cursor_image(Some(image));+ return CursorIcon::None;+ }+ if closed { CursorIcon::Grabbing } else { CursorIcon::Grab }+}+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@@ -107,6 +126,8 @@ fn paint(painter: &Painter, at: Pos2, shape: Shape) {}}Shape::Crosshair { length, gap } => paint_crosshair(painter, at, length, gap, stroke),+ // Only ever a bitmap: without one the OS draws its own grab cursors.+ Shape::Hand { .. } => {}}}}@@ -138,9 +159,38 @@ fn extent(shape: Shape) -> Option<f32> {}length}+ Shape::Hand { .. } => hand::HALF,})}+/// How much of the pixel at `(dx, dy)` physical pixels from the hotspot the light fill covers and+/// how much the dark outline around it does, each 0 to 1. A dark crease inside the hand takes+/// from the fill, so the fill never covers it.+fn coverage(shape: Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) {+ let (x, y) = (dx.abs(), dy.abs());+ match shape {+ Shape::Circle { radius, centre } => {+ let ring = (x.hypot(y) - radius * scale).abs();+ let distance = if centre { ring.min(cross_distance(x, y, 3.0 * scale, 0.0)) } else { ring };+ stroke_coverage(distance, scale)+ }+ Shape::Crosshair { length, gap } => stroke_coverage(cross_distance(x, y, length * scale, gap * scale), scale),+ Shape::Hand { closed } => {+ let (lx, ly) = (dx / scale, dy / scale);+ let edge = hand::shape(closed, lx, ly) * scale;+ let inside = (0.5 - edge).clamp(0.0, 1.0);+ let outline = (scale + 0.5 - edge).clamp(0.0, 1.0);+ let crease = (0.45 * scale + 0.5 - hand::crease(closed, lx, ly) * scale).clamp(0.0, 1.0);+ (inside * (1.0 - crease), outline.max(inside * crease))+ }+ }+}++/// A 1 px light line with a 1 px dark one on each side, `distance` physical pixels from its centre.+fn stroke_coverage(distance: f32, scale: f32) -> (f32, f32) {+ ((0.5 * scale + 0.5 - distance).clamp(0.0, 1.0), (1.5 * scale + 0.5 - distance).clamp(0.0, 1.0))+}+fn rasterize(shape: Shape, scale: f32) -> Option<CustomCursorImage> {if !scale.is_finite() || scale <= 0.0 {return None;@@ -158,18 +208,12 @@ fn rasterize(shape: Shape, scale: f32) -> Option<CustomCursorImage> {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();+ let dy = f32::from(row) - f32::from(hot);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 dx = f32::from(col) - f32::from(hot);+ let (fill, outline) = coverage(shape, dx, dy, scale);+ let a_dark = outline * f32::from(dark.a()) / 255.0;+ let a_light = fill * 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 };diff --git a/crates/ui-egui/src/tool_cursor/hand.rs b/crates/ui-egui/src/tool_cursor/hand.rsnew file mode 100644index 000000000..2ae3ad0af--- /dev/null+++ b/crates/ui-egui/src/tool_cursor/hand.rs@@ -0,0 +1,72 @@+//! The Hand tool's pointer as signed distance fields (negative inside), in logical pixels from the+//! hotspot with y pointing down. An open hand while the Hand hovers and a fist while it drags, as+//! in Photoshop. Only Windows needs it: winit maps its `Grab` and `Grabbing` to the four-arrow move+//! cursor there, while macOS and the Linux themes already draw hands.++/// Half the side of the square the hand fits in, outline excluded.+pub(super) const HALF: f32 = 12.5;++/// Distance to the segment `a`–`b`, minus `r` (a capsule; a bare line when `r` is 0).+fn capsule(x: f32, y: f32, a: [f32; 2], b: [f32; 2], r: f32) -> f32 {+ let (px, py) = (x - a[0], y - a[1]);+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);+ let len2 = dx * dx + dy * dy;+ let t = if len2 > 0.0 { ((px * dx + py * dy) / len2).clamp(0.0, 1.0) } else { 0.0 };+ (px - dx * t).hypot(py - dy * t) - r+}++/// A box of half-size `half` about `c` with corners rounded by `r`.+fn round_box(x: f32, y: f32, c: [f32; 2], half: [f32; 2], r: f32) -> f32 {+ let qx = (x - c[0]).abs() - (half[0] - r);+ let qy = (y - c[1]).abs() - (half[1] - r);+ qx.max(0.0).hypot(qy.max(0.0)) + qx.max(qy).min(0.0) - r+}++/// Four fingers of this x, reaching up to these tip heights (index to little finger).+const FINGER_X: [f32; 4] = [-5.1, -1.7, 1.7, 5.1];+const FINGER_R: f32 = 1.7;+const TIPS: [f32; 4] = [-7.0, -9.5, -8.5, -5.5];++/// From the hotspot to the shapes' own coordinates: the hotspot is the centre of the hand's box.+fn local(x: f32, y: f32) -> (f32, f32) {+ (x - 2.0, y - 0.5)+}++/// The hand's silhouette: negative inside it.+pub(super) fn shape(closed: bool, x: f32, y: f32) -> f32 {+ let (x, y) = local(x, y);+ if closed {+ let mut d = round_box(x, y, [0.0, 3.0], [7.2, 6.5], 3.6);+ for fx in FINGER_X {+ d = d.min(capsule(x, y, [fx, -1.0], [fx, -2.2], 1.9));+ }+ d.min(capsule(x, y, [-4.5, 7.0], [-9.6, 3.6], 2.0))+ } else {+ let mut d = round_box(x, y, [0.0, 4.5], [6.8, 5.5], 3.0);+ for (fx, tip) in FINGER_X.into_iter().zip(TIPS) {+ d = d.min(capsule(x, y, [fx, 3.0], [fx, tip], FINGER_R));+ }+ d.min(capsule(x, y, [-4.5, 7.0], [-10.5, 1.5], 1.9))+ }+}++/// The creases inside the silhouette (between the fingers, the curl of the fist): distance to the+/// nearest one, so they can be drawn as thin dark lines.+pub(super) fn crease(closed: bool, x: f32, y: f32) -> f32 {+ let (x, y) = local(x, y);+ let line = |a: [f32; 2], b: [f32; 2]| capsule(x, y, a, b, 0.0);+ if closed {+ let mut d = line([-4.0, 4.4], [6.0, 4.4]);+ for fx in [-3.4, 0.0, 3.4] {+ d = d.min(line([fx, -2.6], [fx, 4.4]));+ }+ d+ } else {+ let mut d = f32::MAX;+ // Each crease starts just below the lower of the two fingertips it separates.+ for ((fx, a), b) in [-3.4, 0.0, 3.4].into_iter().zip(TIPS).zip(TIPS.into_iter().skip(1)) {+ d = d.min(line([fx, a.max(b) + 1.0], [fx, 3.5]));+ }+ d+ }+}diff --git a/crates/ui-egui/src/tool_cursor/tests.rs b/crates/ui-egui/src/tool_cursor/tests.rsindex 904bf1729..6a55d3779 100644--- a/crates/ui-egui/src/tool_cursor/tests.rs+++ b/crates/ui-egui/src/tool_cursor/tests.rs@@ -61,6 +61,88 @@ fn hostile_sizes_are_rejected_before_allocating() {}}+#[test]+fn hand_bitmaps_are_outlined_hands_around_a_centred_hotspot_at_each_dpi() {+ for scale in [1.0, 1.25, 1.5, 2.0, 3.0] {+ let open = rasterize(Shape::Hand { closed: false }, scale).unwrap();+ let fist = rasterize(Shape::Hand { closed: true }, scale).unwrap();+ for image in [&open, &fist] {+ 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!(image.size[0] <= (34.0 * scale) as u16, "no bigger than a stock cursor at {scale}: {:?}", image.size);+ assert!(alpha(image, x, y) > 230, "the hotspot is on the hand, not in a hole");+ assert_eq!(alpha(image, 0, 0), 0, "nothing at the corners");+ let pixels = image.rgba.as_chunks::<4>().0;+ assert!(pixels.iter().any(|p| p[3] > 230 && p[0] > 230), "a white hand");+ assert!(pixels.iter().any(|p| p[3] > 100 && p[0] < 25), "with a black outline, readable on white");+ }+ assert_ne!(open.rgba, fist.rgba, "the fist is a different picture");+ }+}++#[test]+fn hand_bitmap_is_a_straight_rgba_silhouette_outlined_outside_the_hand() {+ let image = rasterize(Shape::Hand { closed: false }, 1.0).unwrap();+ let side = usize::from(image.size[0]);+ let px = |x: usize, y: usize| <[u8; 4]>::try_from(&image.rgba[(y * side + x) * 4..][..4]).unwrap();+ let mid = side / 2;+ // Walking left from the hotspot along the middle finger: white fill, then the dark outline,+ // then nothing, never the other way round.+ let mut seen = Vec::new();+ for x in (0..=mid).rev() {+ let [r, _, _, a] = px(x, mid - 4);+ let kind = if a < 20 {+ 'n'+ } else if r > 200 {+ 'w'+ } else {+ 'd'+ };+ if seen.last() != Some(&kind) {+ seen.push(kind);+ }+ }+ assert_eq!(seen.first(), Some(&'w'));+ assert_eq!(seen.last(), Some(&'n'));+ let first_dark = seen.iter().position(|k| *k == 'd').expect("an outline");+ let first_none = seen.iter().position(|k| *k == 'n').unwrap();+ assert!(first_dark < first_none, "outline between fill and background: {seen:?}");+}++#[test]+fn hostile_scales_get_no_hand_bitmap() {+ for scale in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, 500.0] {+ assert!(rasterize(Shape::Hand { closed: false }, scale).is_none(), "{scale}");+ assert!(rasterize(Shape::Hand { closed: true }, scale).is_none(), "{scale}");+ }+}++#[test]+fn the_hand_is_a_bitmap_only_where_the_os_has_none() {+ let ctx = egui::Context::default();+ ctx.add_plugin(CursorLifecycle);+ for closed in [false, true] {+ let native = frame(&ctx, |ui| {+ let icon = hand_with(ui.ctx(), closed, false);+ ui.ctx().set_cursor_icon(icon);+ });+ assert_eq!(native.platform_output.cursor_icon, if closed { CursorIcon::Grabbing } else { CursorIcon::Grab });+ assert!(native.platform_output.cursor_image.is_none(), "macOS and the Linux themes draw their own hands");++ let bitmap = frame(&ctx, |ui| {+ let icon = hand_with(ui.ctx(), closed, true);+ ui.ctx().set_cursor_icon(icon);+ });+ let image = bitmap.platform_output.cursor_image.expect("Windows has no stock hand");+ assert_eq!(image.rgba, rasterize(Shape::Hand { closed }, 1.0).unwrap().rgba);+ assert_eq!(bitmap.platform_output.cursor_icon, CursorIcon::Crosshair, "visible fallback if the OS rejects a bitmap");+ }+ let open = hand_with(&ctx, false, true);+ let fist = hand_with(&ctx, true, true);+ assert_eq!((open, fist), (CursorIcon::None, CursorIcon::None));+}+#[test]fn unchanged_geometry_reuses_the_os_upload_and_dpi_invalidates_it() {let ctx = egui::Context::default();@@ -128,8 +210,12 @@ fn write_cursor_preview() {(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),+ (Shape::Hand { closed: false }, 1.0),+ (Shape::Hand { closed: true }, 1.0),+ (Shape::Hand { closed: false }, 1.5),+ (Shape::Hand { closed: true }, 2.0),];- let (width, height) = (600_usize, 500_usize);+ let (width, height) = (600_usize, cases.len() * 100);let mut rgba = vec![255; width * height * 4];for (col, background) in [0_u8, 128, 255].into_iter().enumerate() {for y in 0..height {@@ -203,10 +289,12 @@ fn brush_hover_uses_an_os_bitmap_that_survives_motion_but_not_tool_or_panel_chanh.run_steps(2);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).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);+ 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);h.state_mut().ui.tool = crate::Tool::Brush;h.state_mut().run("prefs.set", json!({"path": "cursors.painting", "value": "standard"})).unwrap();