cranpose 0.22.4

Build desktop, mobile and web apps with composable Rust functions
Documentation
//! Applying a [`PointerIcon`] to a winit window.
//!
//! Standard shapes go straight through as a winit `CursorIcon`; a custom shape
//! has to be uploaded to the windowing system first, which is what the cache
//! here avoids repeating. A skin whose every control carries its own cursor
//! would otherwise rebuild the same handful of images on each pointer move.

use std::sync::Arc;

use cranpose_core::collections::map::{HashMap, HashSet};
use cranpose_ui::{CursorIcon, CustomPointerIcon, PointerIcon};
use winit::{
    cursor::{Cursor, CustomCursor, CustomCursorSource},
    event_loop::ActiveEventLoop,
    window::{Window, WindowId},
};

use crate::CustomCursorSize;

/// Whether re-offering `icon` would be dropped before it reaches the platform.
///
/// A backend that already holds the cursor being set treats the call as a
/// no-op, and on macOS that skips the cursor-rectangle invalidation with it.
/// That is exactly the case a refresh is made of: the region under the pointer
/// has not changed, so the icon offered is the one the window already has, and
/// the refresh would do nothing. Offering a different cursor first makes the
/// one that matters a change again.
fn offering_the_same_icon_needs_a_nudge(applied: Option<&PointerIcon>, icon: &PointerIcon) -> bool {
    applied.is_some_and(|applied| applied == icon)
}

/// A stock cursor that is never equal to `icon`, for the nudge.
fn a_cursor_that_is_not(icon: &PointerIcon) -> CursorIcon {
    match icon {
        PointerIcon::System(CursorIcon::Default) => CursorIcon::Pointer,
        _ => CursorIcon::Default,
    }
}

/// A custom cursor as the platform takes it: the icon's
/// [`CustomPointerIcon::id`] and the scale its image was handed over at.
type CursorKey = (u64, u64);

fn cursor_key(custom: &CustomPointerIcon, factor: f64) -> CursorKey {
    (custom.id(), factor.to_bits())
}

// Whether an uploaded custom cursor may be handed to a window again.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Reuse {
    Cached,
    // Uploaded for each change and dropped once the window shows another.
    Never,
}

// winit's X11 backend frees a cursor's server image when the window drops its
// own copy at the next change, so a cached copy handed over again names a freed
// cursor and the window keeps the one it had. The X server keeps a cursor a
// window shows until the window stops showing it.
#[cfg(all(target_os = "linux", feature = "desktop-x11"))]
fn reuse_under(window: &dyn Window) -> Reuse {
    use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};

    let x11 = window.window_handle().is_ok_and(|handle| {
        matches!(
            handle.as_raw(),
            RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)
        )
    });
    if x11 { Reuse::Never } else { Reuse::Cached }
}

#[cfg(not(all(target_os = "linux", feature = "desktop-x11")))]
fn reuse_under(_window: &dyn Window) -> Reuse {
    Reuse::Cached
}

/// What the platform under `window` does to a custom cursor image by itself.
fn cursor_surface(window: &dyn Window) -> crate::cursor_scale::CursorSurface {
    #[cfg(target_os = "macos")]
    let (pointer_scale, image_in_points) = (super::macos_cursor::pointer_scale(), true);
    #[cfg(target_os = "windows")]
    let (pointer_scale, image_in_points) = (super::windows_cursor::pointer_scale(), false);
    #[cfg(not(any(target_os = "macos", target_os = "windows")))]
    let (pointer_scale, image_in_points) = (
        crate::cursor_scale::xcursor_scale(std::env::var("XCURSOR_SIZE").ok().as_deref()),
        false,
    );
    crate::cursor_scale::CursorSurface {
        pointer_scale,
        density: window.scale_factor(),
        image_in_points,
        // Only macOS enlarges an app's own cursor images; the others show
        // them pixel for pixel.
        enlarges_custom_images: image_in_points,
    }
}

/// Per-window store of the custom cursors the windowing system has accepted,
/// keyed by [`CursorKey`].
#[derive(Default)]
pub(crate) struct DesktopCursors {
    size: CustomCursorSize,
    uploaded: HashMap<CursorKey, CustomCursor>,
    rejected: HashSet<CursorKey>,
    applied: HashMap<WindowId, PointerIcon>,
    shown_once: HashMap<WindowId, CustomCursor>,
    /// Cursors winit cannot build, sized in points rather than one point to a
    /// pixel.
    #[cfg(target_os = "macos")]
    as_drawn: HashMap<CursorKey, super::macos_cursor::AsDrawnCursor>,
    /// The window under the pointer showing one of those, with its cursor
    /// rectangles held off, and which one it shows.
    #[cfg(target_os = "macos")]
    held: HashMap<WindowId, CursorKey>,
    /// The pointer moved over a held window since the cursor was last shown.
    #[cfg(target_os = "macos")]
    moved_over_held: bool,
}

impl DesktopCursors {
    pub(crate) fn new(size: CustomCursorSize) -> Self {
        Self {
            size,
            ..Self::default()
        }
    }

    /// Sets `icon` as `window`'s cursor, uploading a custom image the first
    /// time it appears, scaled so it shows at the size [`CustomCursorSize`]
    /// asks for.
    pub(crate) fn apply(
        &mut self,
        event_loop: &dyn ActiveEventLoop,
        window: &Arc<dyn Window>,
        icon: &PointerIcon,
    ) {
        let id = window.id();
        let factor = match icon {
            PointerIcon::Custom(_) => {
                crate::cursor_scale::image_scale(self.size, cursor_surface(window.as_ref()))
            }
            PointerIcon::System(_) => 1.0,
        };
        #[cfg(target_os = "macos")]
        {
            if self.hold_as_drawn(window, icon, factor) {
                self.applied.insert(id, icon.clone());
                return;
            }
            if self.held.remove(&id).is_some() {
                super::macos_cursor::release(window.as_ref());
                // winit still holds the cursor it last set, which may be the
                // one wanted now; offering another first makes it a change.
                window.set_cursor(Cursor::Icon(a_cursor_that_is_not(icon)));
            }
        }
        if offering_the_same_icon_needs_a_nudge(self.applied.get(&id), icon) {
            window.set_cursor(Cursor::Icon(a_cursor_that_is_not(icon)));
        }
        let reuse = reuse_under(window.as_ref());
        let shown = match icon {
            PointerIcon::System(system) => {
                window.set_cursor(Cursor::Icon(*system));
                None
            }
            PointerIcon::Custom(custom) => self
                .custom_cursor(event_loop, custom, factor, reuse)
                .inspect(|cursor| window.set_cursor(Cursor::Custom(cursor.clone()))),
        };
        if reuse == Reuse::Never {
            // Dropped only now: the window has let go of the one it replaces.
            match shown {
                Some(cursor) => self.shown_once.insert(id, cursor),
                None => self.shown_once.remove(&id),
            };
        }
        self.applied.insert(id, icon.clone());
    }

    /// Shows `icon` sized in points by `factor`, when it is a custom cursor
    /// winit's one point to a pixel would show at the wrong size.
    #[cfg(target_os = "macos")]
    fn hold_as_drawn(&mut self, window: &Arc<dyn Window>, icon: &PointerIcon, factor: f64) -> bool {
        let PointerIcon::Custom(custom) = icon else {
            return false;
        };
        if !crate::cursor_scale::rescales(factor) {
            return false;
        }
        let key = cursor_key(custom, factor);
        let cursor = match self.as_drawn.entry(key) {
            std::collections::hash_map::Entry::Occupied(built) => built.into_mut(),
            std::collections::hash_map::Entry::Vacant(slot) => {
                let image = custom.image();
                let Some(cursor) = super::macos_cursor::as_drawn(
                    &image.rgba8_pixels(),
                    image.width(),
                    image.height(),
                    (custom.hotspot_x(), custom.hotspot_y()),
                    factor,
                ) else {
                    return false;
                };
                slot.insert(cursor)
            }
        };
        super::macos_cursor::hold(window.as_ref(), cursor);
        self.held.insert(window.id(), key);
        true
    }

    /// The pointer moved over, or into, the window `id`.
    pub(crate) fn pointer_moved(&mut self, id: WindowId) {
        #[cfg(target_os = "macos")]
        if self.held.contains_key(&id) {
            self.moved_over_held = true;
        }
        #[cfg(not(target_os = "macos"))]
        let _ = id;
    }

    /// Shows the held cursor again after the pointer moved over its window,
    /// when the window server may have put its own arrow over it. Called once
    /// per pass of the event loop.
    pub(crate) fn keep_held(&mut self) {
        #[cfg(target_os = "macos")]
        if std::mem::take(&mut self.moved_over_held) {
            for key in self.held.values() {
                if let Some(cursor) = self.as_drawn.get(key) {
                    super::macos_cursor::keep(cursor);
                }
            }
        }
    }

    /// The pointer left `window`: a cursor it held goes back to the window's
    /// own rectangles, so it is not kept over whatever the pointer is over now.
    pub(crate) fn pointer_left(&mut self, window: &Arc<dyn Window>) {
        #[cfg(target_os = "macos")]
        if self.held.remove(&window.id()).is_some() {
            super::macos_cursor::release(window.as_ref());
        }
        #[cfg(not(target_os = "macos"))]
        let _ = window;
    }

    /// The uploaded cursor for `custom`, uploading it if this is the first time
    /// it is asked for, or every time under [`Reuse::Never`].
    ///
    /// A cursor the windowing system refuses is reported once and remembered as
    /// rejected, so the window keeps the cursor it already has instead of
    /// re-attempting the upload on every pointer move.
    fn custom_cursor(
        &mut self,
        event_loop: &dyn ActiveEventLoop,
        custom: &CustomPointerIcon,
        factor: f64,
        reuse: Reuse,
    ) -> Option<CustomCursor> {
        let id = cursor_key(custom, factor);
        if reuse == Reuse::Cached
            && let Some(cursor) = self.uploaded.get(&id)
        {
            return Some(cursor.clone());
        }
        if self.rejected.contains(&id) {
            return None;
        }

        let image = custom.image();
        let hotspot = (custom.hotspot_x(), custom.hotspot_y());
        let (pixels, width, height, hotspot) = if crate::cursor_scale::rescales(factor) {
            crate::cursor_scale::scaled_image(
                &image.rgba8_pixels(),
                image.width(),
                image.height(),
                hotspot,
                factor,
            )
        } else {
            (
                image.rgba8_pixels().into_owned(),
                image.width(),
                image.height(),
                hotspot,
            )
        };
        let source = CustomCursorSource::from_rgba(
            pixels,
            width as u16,
            height as u16,
            hotspot.0 as u16,
            hotspot.1 as u16,
        );
        let cursor = match source {
            Ok(source) => event_loop.create_custom_cursor(source).map_err(|error| {
                log::warn!("the windowing system refused a custom cursor: {error}");
            }),
            Err(error) => {
                log::warn!("a custom cursor image was rejected: {error}");
                Err(())
            }
        };
        match cursor {
            Ok(cursor) => {
                if reuse == Reuse::Cached {
                    self.uploaded.insert(id, cursor.clone());
                }
                Some(cursor)
            }
            Err(()) => {
                self.rejected.insert(id);
                None
            }
        }
    }
}

#[cfg(test)]
#[path = "tests/cursor_tests.rs"]
mod tests;

#[cfg(all(test, target_os = "linux", feature = "desktop-x11"))]
#[path = "tests/x11_cursor_tests.rs"]
mod x11_tests;