#![expect(unsafe_code, reason = "Objective-C messages to AppKit")]
use std::ffi::c_uchar;
use objc2::{AllocAnyThread, rc::Retained};
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
use objc2_foundation::{NSPoint, NSSize, NSUserDefaults, ns_string};
use winit::window::Window;
use super::macos_window::ns_window;
pub(crate) fn pointer_scale() -> f64 {
let defaults = NSUserDefaults::initWithSuiteName(
NSUserDefaults::alloc(),
Some(ns_string!("com.apple.universalaccess")),
);
let scale = defaults.map_or(1.0, |defaults| {
defaults.doubleForKey(ns_string!("mouseDriverCursorSize"))
});
crate::cursor_scale::usable_scale(scale)
}
pub(crate) struct AsDrawnCursor(Retained<NSCursor>);
pub(crate) fn as_drawn(
pixels: &[u8],
width: u32,
height: u32,
hotspot: (u32, u32),
points_per_pixel: f64,
) -> Option<AsDrawnCursor> {
let row = width as usize * 4;
if width == 0 || height == 0 || pixels.len() != row * height as usize {
return None;
}
let bitmap = unsafe {
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
NSBitmapImageRep::alloc(),
std::ptr::null_mut::<*mut c_uchar>(),
width as isize,
height as isize,
8,
4,
true,
false,
NSDeviceRGBColorSpace,
row as isize,
32,
)
}?;
let storage = unsafe { std::slice::from_raw_parts_mut(bitmap.bitmapData(), pixels.len()) };
storage.copy_from_slice(pixels);
let size = NSSize::new(
f64::from(width) * points_per_pixel,
f64::from(height) * points_per_pixel,
);
bitmap.setSize(size);
let image = NSImage::initWithSize(NSImage::alloc(), size);
image.addRepresentation(&bitmap);
let hotspot = NSPoint::new(
f64::from(hotspot.0) * points_per_pixel,
f64::from(hotspot.1) * points_per_pixel,
);
Some(AsDrawnCursor(NSCursor::initWithImage_hotSpot(
NSCursor::alloc(),
&image,
hotspot,
)))
}
pub(crate) fn hold(window: &dyn Window, cursor: &AsDrawnCursor) {
if let Some(window) = ns_window(window) {
window.disableCursorRects();
}
cursor.0.set();
}
pub(crate) fn keep(cursor: &AsDrawnCursor) {
cursor.0.set();
}
pub(crate) fn release(window: &dyn Window) {
if let Some(window) = ns_window(window) {
window.enableCursorRects();
}
}