diff --git a/src/platform.rs b/src/platform.rs index 8984b85..523dfd0 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -1,25 +1,29 @@ +// File: C:\Users\j\Documents\augment-projects\Cursor Rush\src\platform.rs // Platform-specific cursor handling // Windows implementation #[cfg(windows)] mod windows { use std::path::Path; - use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; + // Make Mutex and AtomicBool readily available + use std::sync::{Mutex, atomic::{AtomicBool, Ordering}}; use std::thread; use std::time::Duration; - use std::sync::Once; + // Remove Once - Lazy handles initialization + // use std::sync::Once; use winapi::{ um::winuser::{ GetDC, ReleaseDC, GetCursorPos, LoadCursorW, - SetSystemCursor, CopyIcon, IDC_ARROW, + SetSystemCursor, CopyIcon, IDC_ARROW, // Keep IDC_ARROW CreateCursor, SystemParametersInfoW, SPI_SETCURSORS, CreateWindowExW, DestroyWindow, UpdateLayeredWindow, ShowWindow, SetWindowPos, RegisterClassExW, DefWindowProcW, - WS_EX_LAYERED, WS_EX_TRANSPARENT, WS_EX_TOPMOST, WS_EX_TOOLWINDOW, + WS_EX_LAYERED, WS_EX_TRANSPARENT, WS_EX_TOPMOST, WS_EX_TOOLWINDOW, WS_EX_NOACTIVATE, // Added NOACTIVATE WS_POPUP, SW_SHOW, HWND_TOPMOST, SWP_NOSIZE, SWP_NOMOVE, - WM_DESTROY, WM_CLOSE, WM_MOUSEMOVE, - CS_HREDRAW, CS_VREDRAW, ULW_ALPHA, + WM_DESTROY, WM_CLOSE, /* WM_MOUSEMOVE, */ // Remove WM_MOUSEMOVE handling from window proc + CS_HREDRAW, CS_VREDRAW, ULW_ALPHA, WNDCLASSEXW, // Import WNDCLASSEXW + MAKEINTRESOURCEW, // Add this for converting cursor IDs to resource pointers }, um::wingdi::{ CreateCompatibleDC, DeleteDC, SelectObject, DeleteObject, @@ -30,28 +34,76 @@ mod windows { shared::windef::{HWND, POINT, HCURSOR, SIZE, HBITMAP, HDC}, shared::minwindef::{DWORD, BOOL, TRUE, FALSE, UINT, WPARAM, LPARAM, LRESULT}, }; + use std::{ptr::null_mut, ffi::OsStr}; + use std::os::windows::ffi::OsStrExt; // For OsStr::encode_wide + use ::image::{RgbaImage, open as image_open}; + // Replace lazy_static with once_cell for consistency + // use lazy_static::lazy_static; + use once_cell::sync::Lazy; // Use once_cell::sync::Lazy - // Import the Windows API function to reset system cursors + // Import the Windows API function to reset system cursors (keep this) #[link(name = "user32")] extern "system" { fn SystemParametersInfoA(uiAction: u32, uiParam: u32, pvParam: *mut std::ffi::c_void, fWinIni: u32) -> BOOL; } - // Constants for SystemParametersInfo + // Constants for SystemParametersInfo (keep these) const SPI_SETCURSORS_A: u32 = 0x0057; const SPIF_UPDATEINIFILE: u32 = 0x01; const SPIF_SENDCHANGE: u32 = 0x02; - use std::ptr::null_mut; - use ::image::{RgbaImage, open as image_open}; - use lazy_static::lazy_static; - // Static variables for cursor state - static mut CURSOR_HIDDEN: bool = false; - // Flag to control the rendering thread + // --- Thread-Safe Handle Wrappers --- + // These wrappers make raw Windows handles safe to share between threads + + // Wrapper for HWND (window handle) + #[derive(Copy, Clone, Debug)] + struct SyncHWND(HWND); + unsafe impl Send for SyncHWND {} + unsafe impl Sync for SyncHWND {} + + // Wrapper for HCURSOR (cursor handle) + #[derive(Copy, Clone, Debug)] + struct SyncHCURSOR(HCURSOR); + unsafe impl Send for SyncHCURSOR {} + unsafe impl Sync for SyncHCURSOR {} + + // Wrapper for HBITMAP (bitmap handle) + #[derive(Copy, Clone, Debug)] + struct SyncHBITMAP(HBITMAP); + unsafe impl Send for SyncHBITMAP {} + unsafe impl Sync for SyncHBITMAP {} + + // Wrapper for HDC (device context handle) + #[derive(Copy, Clone, Debug)] + struct SyncHDC(HDC); + unsafe impl Send for SyncHDC {} + unsafe impl Sync for SyncHDC {} + + // --- Thread-Safe Static Variables --- + + // Use AtomicBool for simple flags + static CURSOR_HIDDEN: AtomicBool = AtomicBool::new(false); + static CTRL_HANDLER_REGISTERED: AtomicBool = AtomicBool::new(false); + + // Flag to control the rendering thread (already AtomicBool, keep it) static RENDERING_ACTIVE: AtomicBool = AtomicBool::new(false); - // Define all system cursor IDs we'll replace + // Use Lazy> for complex Option types + static ORIGINAL_CURSORS: Lazy>>> = Lazy::new(|| Mutex::new(None)); + static CURRENT_CURSOR_IMAGE: Lazy>> = Lazy::new(|| Mutex::new(None)); + static RENDER_THREAD: Lazy>>> = Lazy::new(|| Mutex::new(None)); + static LAST_CURSOR_POS: Lazy>> = Lazy::new(|| Mutex::new(None)); + + // Use Lazy>> for WinAPI handles with our thread-safe wrappers + static CURSOR_WINDOW: Lazy>> = Lazy::new(|| Mutex::new(None)); + static CURSOR_BITMAP: Lazy>> = Lazy::new(|| Mutex::new(None)); + static CURSOR_DC: Lazy>> = Lazy::new(|| Mutex::new(None)); + + // --- End Thread-Safe Static Variables --- + + + // Define all system cursor IDs we'll replace (keep this) static SYSTEM_CURSORS: [DWORD; 11] = [ 32512, // IDC_ARROW 32513, // IDC_IBEAM @@ -66,333 +118,347 @@ mod windows { 32642, // IDC_SIZENWSE ]; - // Use lazy_static for thread-safe access to the cursor image - lazy_static! { - static ref CURRENT_CURSOR_IMAGE: Arc>> = Arc::new(Mutex::new(None)); - static ref RENDER_THREAD: Mutex>> = Mutex::new(None); - // Track the last cursor position to avoid unnecessary updates - static ref LAST_CURSOR_POS: Arc>> = Arc::new(Mutex::new(None)); - } - - // We need to use static variables since they aren't Send - static mut CURSOR_WINDOW: Option = None; - static mut CURSOR_BITMAP: Option = None; - static mut CURSOR_DC: Option = None; - - // Window class name for our cursor window + // Window class name for our cursor window (keep this) const CURSOR_WINDOW_CLASS: &str = "CursorRushOverlay"; - // Window procedure for our cursor window + // Window procedure for our cursor window (Simplified - no longer needs WM_MOUSEMOVE) unsafe extern "system" fn window_proc(hwnd: HWND, msg: UINT, wparam: WPARAM, lparam: LPARAM) -> LRESULT { match msg { WM_CLOSE | WM_DESTROY => { - DestroyWindow(hwnd); - 0 - }, - WM_MOUSEMOVE => { - // Extract cursor position from lparam - let x = (lparam & 0xFFFF) as i16 as i32; - let y = ((lparam >> 16) & 0xFFFF) as i16 as i32; - - // Update cursor position - let point = POINT { x, y }; - - // Update the cursor window position - update_cursor_position(&point); + // Clean up resources associated with the window if necessary + // We handle destruction in the main cleanup logic mostly + DestroyWindow(hwnd); // Ensure window is destroyed on close message + // Remove window handle from our static variable upon destruction + *CURSOR_WINDOW.lock().unwrap() = None; 0 }, + // WM_MOUSEMOVE is handled by the render thread polling GetCursorPos _ => DefWindowProcW(hwnd, msg, wparam, lparam), } } - // Function to update the cursor position + // Function to update the cursor position (Render thread responsibility) fn update_cursor_position(point: &POINT) { + // Lock the statics needed + let mut last_pos_guard = LAST_CURSOR_POS.lock().unwrap(); + let cursor_image_guard = CURRENT_CURSOR_IMAGE.lock().unwrap(); + + // Get Option then map to Option + let maybe_hwnd_wrapper = *CURSOR_WINDOW.lock().unwrap(); + let maybe_bitmap_wrapper = *CURSOR_BITMAP.lock().unwrap(); + let maybe_dc_wrapper = *CURSOR_DC.lock().unwrap(); + // Check if we need to update (if position changed) - let mut last_pos = LAST_CURSOR_POS.lock().unwrap(); + let position_changed = last_pos_guard.map_or(true, |last| last.x != point.x || last.y != point.y); - // Only update if position changed or first time - if last_pos.is_none() || last_pos.as_ref().unwrap().x != point.x || last_pos.as_ref().unwrap().y != point.y { - // Update last position - *last_pos = Some(POINT { x: point.x, y: point.y }); + if position_changed { + // Update last position *within the lock* + *last_pos_guard = Some(*point); - // Update the cursor window position - unsafe { - if let Some(hwnd) = CURSOR_WINDOW { - // Get cursor image dimensions - if let Some(ref cursor_image) = *CURRENT_CURSOR_IMAGE.lock().unwrap() { - let (width, height) = cursor_image.dimensions(); + // Update the cursor window position if all resources exist + if let (Some(hwnd_wrapper), Some(ref cursor_image), Some(_bitmap_wrapper), Some(dc_wrapper)) = + (maybe_hwnd_wrapper, cursor_image_guard.as_ref(), maybe_bitmap_wrapper, maybe_dc_wrapper) + { + // Extract the raw handles using .0 + let hwnd = hwnd_wrapper.0; + let dc = dc_wrapper.0; - // Update the layered window with the bitmap - if let (Some(_bitmap), Some(dc)) = (CURSOR_BITMAP, CURSOR_DC) { - let screen_dc = GetDC(std::ptr::null_mut()); - if !screen_dc.is_null() { - // Set up source and destination points and size - let src_point = POINT { x: 0, y: 0 }; - let dst_point = POINT { - x: point.x - (width as i32 / 2), - y: point.y - (height as i32 / 2) - }; - let size = SIZE { - cx: width as i32, - cy: height as i32 - }; + // Get cursor image dimensions + let (width, height) = cursor_image.dimensions(); - // Set up blend function for alpha blending - let blend = BLENDFUNCTION { - BlendOp: AC_SRC_OVER, - BlendFlags: 0, - SourceConstantAlpha: 255, // Fully opaque - AlphaFormat: AC_SRC_ALPHA, // Use per-pixel alpha - }; + unsafe { + let screen_dc = GetDC(null_mut()); + if !screen_dc.is_null() { + // Set up source and destination points and size + let src_point = POINT { x: 0, y: 0 }; + // Adjust position based on image dimensions (center hotspot) + let dst_point = POINT { + x: point.x - (width as i32 / 2), + y: point.y - (height as i32 / 2) + }; + let size = SIZE { + cx: width as i32, + cy: height as i32 + }; - // Make sure the window is visible - ShowWindow(hwnd, SW_SHOW); + // Set up blend function for alpha blending + let blend = BLENDFUNCTION { + BlendOp: AC_SRC_OVER, + BlendFlags: 0, + SourceConstantAlpha: 255, // Fully opaque + AlphaFormat: AC_SRC_ALPHA, // Use per-pixel alpha + }; - // Always ensure the window is topmost before updating - // This ensures our cursor stays above all other windows including system menus - SetWindowPos( - hwnd, - HWND_TOPMOST, - 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE - ); + // Ensure the window is visible and topmost *before* updating + // This helps prevent flicker and ensures it stays on top + ShowWindow(hwnd, SW_SHOW); + SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - // Update the layered window atomically - // Convert references to raw pointers for UpdateLayeredWindow - let result = UpdateLayeredWindow( - hwnd, - screen_dc, - &dst_point as *const POINT as *mut POINT, - &size as *const SIZE as *mut SIZE, - dc, - &src_point as *const POINT as *mut POINT, - 0, // No color key - &blend as *const BLENDFUNCTION as *mut BLENDFUNCTION, - ULW_ALPHA, - ); + // Update the layered window atomically + let result = UpdateLayeredWindow( + hwnd, + screen_dc, + &dst_point as *const POINT as *mut POINT, // Use address-of + &size as *const SIZE as *mut SIZE, // Use address-of + dc, // Use the DC handle directly + &src_point as *const POINT as *mut POINT, // Use address-of + 0, // No color key + &blend as *const BLENDFUNCTION as *mut BLENDFUNCTION, // Use address-of + ULW_ALPHA, + ); - if result == 0 { - // If UpdateLayeredWindow fails, log the error - use std::io::Error; - let error = Error::last_os_error(); - eprintln!("UpdateLayeredWindow failed: {}", error); - } - - ReleaseDC(std::ptr::null_mut(), screen_dc); - } + if result == 0 { + use std::io::Error; + let error = Error::last_os_error(); + eprintln!("UpdateLayeredWindow failed: {}", error); + // Consider logging the point, size, handles for debugging } + + ReleaseDC(null_mut(), screen_dc); + } else { + eprintln!("Failed to get screen DC for UpdateLayeredWindow"); } - } + } // end unsafe + } else { + // Log if resources are missing for update (optional) + // eprintln!("Skipping update: HWND: {:?}, Image: {}, Bitmap: {:?}, DC: {:?}", + // maybe_hwnd_wrapper, cursor_image_guard.is_some(), maybe_bitmap_wrapper, maybe_dc_wrapper); } - } + } // end if position_changed + // else: Position didn't change, no update needed } // Create a layered, topmost window for our cursor - unsafe fn create_cursor_window() -> Option { - use std::ffi::OsStr; - use std::os::windows::ffi::OsStrExt; - + unsafe fn create_cursor_window() -> Option { // Convert class name to wide string - let class_name: Vec = OsStr::new(CURSOR_WINDOW_CLASS) + let class_name_wide: Vec = OsStr::new(CURSOR_WINDOW_CLASS) .encode_wide() .chain(std::iter::once(0)) .collect(); - // Register window class - let mut wc = std::mem::zeroed::(); - wc.cbSize = std::mem::size_of::() as u32; + // Register window class if not already registered (check atom?) + // For simplicity, we register it each time, Windows handles duplicates. + let mut wc = std::mem::zeroed::(); + wc.cbSize = std::mem::size_of::() as u32; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = Some(window_proc); - wc.hInstance = std::ptr::null_mut(); - wc.lpszClassName = class_name.as_ptr(); - wc.hCursor = LoadCursorW(std::ptr::null_mut(), IDC_ARROW as _); + wc.hInstance = null_mut(); // GetModuleHandleW(null_mut()); might be better if needed + wc.lpszClassName = class_name_wide.as_ptr(); + // Use MAKEINTRESOURCEW to convert IDC_ARROW to a resource pointer + wc.hCursor = LoadCursorW(null_mut(), MAKEINTRESOURCEW(IDC_ARROW as u16)); let atom = RegisterClassExW(&wc); if atom == 0 { - eprintln!("Failed to register window class"); - return None; + // Check GetLastError() if registration fails + if winapi::um::errhandlingapi::GetLastError() != 1410 { // ERROR_CLASS_ALREADY_EXISTS + eprintln!("Failed to register window class, error: {}", winapi::um::errhandlingapi::GetLastError()); + return None; + } } // Create window with layered, transparent, and topmost attributes - // WS_EX_TRANSPARENT: Makes the window transparent to mouse clicks - // WS_EX_LAYERED: Required for transparency and UpdateLayeredWindow - // WS_EX_TOPMOST: Keeps the window above all other windows - // WS_EX_TOOLWINDOW: Prevents the window from showing in the taskbar - // WS_EX_NOACTIVATE: Prevents the window from becoming active when clicked let hwnd = CreateWindowExW( - WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | 0x08000000, // WS_EX_NOACTIVATE - class_name.as_ptr(), - std::ptr::null(), // Window title (none) + WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE, // Added NOACTIVATE + class_name_wide.as_ptr(), + null_mut(), // Window title (none) WS_POPUP, // Popup window with no border - 0, 0, // Position (will be updated based on cursor position) - 128, 128, // Size (will be updated based on cursor image) - std::ptr::null_mut(), // Parent window - std::ptr::null_mut(), // Menu - std::ptr::null_mut(), // Instance - std::ptr::null_mut(), // Additional data + 0, 0, // Initial Position (irrelevant, updated immediately) + 1, 1, // Initial Size (irrelevant, determined by bitmap) + null_mut(), // Parent window + null_mut(), // Menu + null_mut(), // Instance + null_mut(), // Additional data ); if hwnd.is_null() { - eprintln!("Failed to create cursor window"); + eprintln!("Failed to create cursor window, error: {}", winapi::um::errhandlingapi::GetLastError()); return None; } - // Don't use SetLayeredWindowAttributes since we're using UpdateLayeredWindow - // Just show the window + // Show the window and ensure it's topmost ShowWindow(hwnd, SW_SHOW); + SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); - // Ensure it stays on top - SetWindowPos( - hwnd, - HWND_TOPMOST, - 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE - ); - - Some(hwnd) + // Return the wrapped handle + Some(SyncHWND(hwnd)) } - // We'll use a static variable for original cursors since they're not thread-safe - static mut ORIGINAL_CURSORS: Option> = None; - - // Flag to track if we've registered the control handler - static mut CTRL_HANDLER_REGISTERED: bool = false; - - // Use Once to ensure initialization happens only once - static INIT: Once = Once::new(); + // Use OnceCell for INIT to avoid `static mut` + static INIT: once_cell::sync::OnceCell<()> = once_cell::sync::OnceCell::new(); // Control handler function for console events (Ctrl+C, close, etc.) extern "system" fn ctrl_handler(_ctrl_type: DWORD) -> BOOL { - println!("Control event received, restoring cursors..."); - // Call our cleanup function to restore cursors - cleanup(); - // Return FALSE to allow other handlers to process the event - FALSE + // Check if cleanup is already running to prevent recursion + // (Though cleanup() itself has internal guards) + println!("Control event received, attempting cleanup..."); + cleanup(); // Call cleanup logic + FALSE // Allow other handlers (like default exit) to run } // Cleanup function to restore cursors and clean up resources fn cleanup() { - unsafe { - // Only restore if we've hidden the cursor - if CURSOR_HIDDEN { - println!("Restoring system cursors..."); + // Stop the rendering thread FIRST + if RENDERING_ACTIVE.swap(false, Ordering::SeqCst) { // Use swap to ensure it's only attempted once + println!("Stopping render thread..."); + // Join the thread handle + if let Some(handle) = RENDER_THREAD.lock().unwrap().take() { + match handle.join() { + Ok(_) => println!("Render thread joined successfully."), + Err(e) => eprintln!("Error joining render thread: {:?}", e), + } + } + } else { + // Render thread was already stopped or never started + // println!("Render thread already stopped."); + } - // First, force Windows to reload the cursors + + // Restore system cursors if they were hidden + if CURSOR_HIDDEN.swap(false, Ordering::SeqCst) { // Use swap to ensure it runs only once + println!("Restoring system cursors..."); + unsafe { + // Force Windows to reload default cursor settings SystemParametersInfoW(SPI_SETCURSORS, 0, null_mut(), 0); + // Also try the A version just in case + SystemParametersInfoA(SPI_SETCURSORS_A, 0, null_mut(), SPIF_SENDCHANGE); + } - // Try multiple restoration methods and track success - let mut restoration_success = false; + let mut restoration_success = false; - // Method 1: Try to restore the original system cursors if we have them - if let Some(ref original_cursors) = ORIGINAL_CURSORS { - if !original_cursors.is_empty() { - let mut method1_success = true; - println!("Attempting to restore {} saved original cursors", original_cursors.len()); - - for &(cursor_id, cursor) in original_cursors.iter() { - // Make a copy of the original cursor - let cursor_copy = CopyIcon(cursor as _) as HCURSOR; + // Lock ORIGINAL_CURSORS once + let original_cursors_guard = ORIGINAL_CURSORS.lock().unwrap(); + if let Some(ref original_cursors) = *original_cursors_guard { + if !original_cursors.is_empty() { + println!("Attempting to restore {} saved original cursors", original_cursors.len()); + let mut method1_success = true; + unsafe { + for &(cursor_id, sync_hcursor) in original_cursors.iter() { + // Extract the raw handle using .0 + let original_hcursor = sync_hcursor.0; + // Make a fresh copy *each time* we set it + let cursor_copy = CopyIcon(original_hcursor); if !cursor_copy.is_null() { - // Restore the system cursor if SetSystemCursor(cursor_copy, cursor_id) == 0 { eprintln!("Failed to restore system cursor {}", cursor_id); + // Don't destroy the copy on failure, let Windows manage SetSystemCursor's handle method1_success = false; } + // SetSystemCursor takes ownership if successful, CopyIcon needs no manual destroy } else { + eprintln!("Failed to copy original cursor for ID {}", cursor_id); method1_success = false; } } - - if method1_success { - println!("Successfully restored original cursors"); - restoration_success = true; - } } - } - - // Method 2: If method 1 failed, try with the default arrow cursor - if !restoration_success { - println!("Using arrow cursor restoration method"); - let mut method2_success = true; - - // Load the default arrow cursor - let arrow_cursor = LoadCursorW(null_mut(), 32512 as _); // IDC_ARROW = 32512 - if !arrow_cursor.is_null() { - // Make a copy for each system cursor - for &cursor_id in SYSTEM_CURSORS.iter() { - let cursor_copy = CopyIcon(arrow_cursor as _) as HCURSOR; - if !cursor_copy.is_null() { - if SetSystemCursor(cursor_copy, cursor_id) == 0 { - eprintln!("Failed to set system cursor {} to arrow", cursor_id); - method2_success = false; - } - } else { - method2_success = false; - } - } - } else { - method2_success = false; - } - - if method2_success { - println!("Successfully restored cursors using arrow cursor"); + if method1_success { + println!("Successfully restored original cursors from saved state."); restoration_success = true; } } + } + // Drop the guard + drop(original_cursors_guard); - // Method 3: Reset all system cursors to their defaults using Windows API - if !restoration_success { - println!("Using system reset method"); - // Call our reset function which uses SystemParametersInfo - reset_system_cursors(); + // Method 2: Fallback using standard arrow (less critical now with API reset) + if !restoration_success { + println!("Falling back to setting all cursors to standard arrow (IDC_ARROW)"); + unsafe { + // Use MAKEINTRESOURCEW to convert IDC_ARROW to a resource pointer + let arrow_cursor = LoadCursorW(null_mut(), MAKEINTRESOURCEW(IDC_ARROW as u16)); + if !arrow_cursor.is_null() { + for &cursor_id in SYSTEM_CURSORS.iter() { + // Make a copy for each system cursor ID + let arrow_copy = CopyIcon(arrow_cursor); + if !arrow_copy.is_null() { + if SetSystemCursor(arrow_copy, cursor_id) == 0 { + eprintln!("Failed to set system cursor {} to arrow", cursor_id); + // System takes ownership if successful + } + } else { + eprintln!("Failed to copy arrow cursor for ID {}", cursor_id); + } + } + println!("Finished setting cursors to standard arrow."); + restoration_success = true; // Consider this a success even if some minor fails occurred + } else { + eprintln!("Failed to load standard arrow cursor (IDC_ARROW)."); + } } - - CURSOR_HIDDEN = false; - println!("System cursors restoration complete"); } + + // Method 3: Reset via API (already called, but can call again for good measure) + if !restoration_success { + println!("Using system API reset method as final fallback."); + reset_system_cursors(); // Explicitly call the reset function + } + + println!("System cursors restoration attempt complete."); + } else { + // println!("Cursors were not marked as hidden, skipping restoration."); } - // Stop the rendering thread - RENDERING_ACTIVE.store(false, Ordering::SeqCst); - // Clean up bitmap and DC + // Clean up GDI resources (Bitmap and DC) + // Take ownership from the Mutex> + let bitmap_wrapper_to_delete = CURSOR_BITMAP.lock().unwrap().take(); + let dc_wrapper_to_delete = CURSOR_DC.lock().unwrap().take(); + unsafe { - // Clean up the bitmap if it exists - if let Some(bitmap) = CURSOR_BITMAP.take() { - DeleteObject(bitmap as _); - println!("Cursor bitmap deleted during cleanup"); + if let Some(bitmap_wrapper) = bitmap_wrapper_to_delete { + if DeleteObject(bitmap_wrapper.0 as _) != 0 { + println!("Cursor bitmap deleted during cleanup."); + } else { + eprintln!("Failed to delete cursor bitmap during cleanup."); + } } - - // Clean up the DC if it exists - if let Some(dc) = CURSOR_DC.take() { - DeleteDC(dc); - println!("Cursor DC deleted during cleanup"); + if let Some(dc_wrapper) = dc_wrapper_to_delete { + if DeleteDC(dc_wrapper.0) != 0 { + println!("Cursor DC deleted during cleanup."); + } else { + eprintln!("Failed to delete cursor DC during cleanup."); + } } } - // Destroy the cursor window if it exists - unsafe { - if let Some(hwnd) = CURSOR_WINDOW.take() { - DestroyWindow(hwnd); - println!("Cursor window destroyed during cleanup"); + // Destroy the cursor window + let window_wrapper_to_destroy = CURSOR_WINDOW.lock().unwrap().take(); + if let Some(hwnd_wrapper) = window_wrapper_to_destroy { + unsafe { + if DestroyWindow(hwnd_wrapper.0) != 0 { + println!("Cursor window destroyed during cleanup."); + } else { + // GetLastError might provide info, e.g., if already destroyed + eprintln!("Failed to destroy cursor window during cleanup (Error {}).", winapi::um::errhandlingapi::GetLastError()); + } } } - // Reset the last cursor position + // Reset the last known cursor position *LAST_CURSOR_POS.lock().unwrap() = None; + + // Unregister control handler (less critical now, but good practice) + if CTRL_HANDLER_REGISTERED.load(Ordering::SeqCst) { + unsafe { + if SetConsoleCtrlHandler(Some(ctrl_handler), FALSE) != 0 { + CTRL_HANDLER_REGISTERED.store(false, Ordering::SeqCst); + println!("Control handler unregistered."); + } else { + eprintln!("Failed to unregister control handler."); + } + } + } } // Register the cleanup function with control handler fn register_cleanup() { - // Use Once to ensure this only happens once - INIT.call_once(|| { + // Use OnceCell::get_or_init for thread-safe single initialization + INIT.get_or_init(|| { unsafe { - // Register our control handler if SetConsoleCtrlHandler(Some(ctrl_handler), TRUE) == 0 { eprintln!("Failed to register control handler"); } else { println!("Control handler registered for cursor restoration"); - CTRL_HANDLER_REGISTERED = true; + CTRL_HANDLER_REGISTERED.store(true, Ordering::SeqCst); } } }); @@ -402,23 +468,21 @@ mod windows { fn initialize() { // Register cleanup handler on module load register_cleanup(); - // Reset system cursors on startup in case they were left in a bad state reset_system_cursors(); - } - - // Call initialize when module is loaded - #[ctor::ctor] - fn module_init() { - initialize(); println!("Windows cursor module initialized with cleanup handlers"); } - // Call cleanup when module is unloaded + // Call initialize when module is loaded (keep ctor) + #[ctor::ctor] + fn module_init() { + initialize(); + } + + // Call cleanup when module is unloaded (keep dtor) #[ctor::dtor] fn module_cleanup() { - println!("Module unloading, restoring cursors..."); - // Call cleanup which handles all cursor restoration + println!("Module unloading, performing final cleanup..."); cleanup(); } @@ -426,22 +490,13 @@ mod windows { fn reset_system_cursors() { unsafe { // Use the Windows API to reset system cursors - let result = SystemParametersInfoW(SPI_SETCURSORS, 0, null_mut(), 0); - - if result == 0 { - // If the W version failed, try with the A version with flags to update the system settings - let result = SystemParametersInfoA( - SPI_SETCURSORS_A, - 0, - null_mut(), - SPIF_UPDATEINIFILE | SPIF_SENDCHANGE - ); - - if result == 0 { - eprintln!("Failed to reset system cursors via API"); - } else { + if SystemParametersInfoW(SPI_SETCURSORS, 0, null_mut(), 0) == 0 { + // If the W version failed, try with the A version with flags + if SystemParametersInfoA(SPI_SETCURSORS_A, 0, null_mut(), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE) == 0 { + eprintln!("Failed to reset system cursors via API (W and A versions)"); + } else { println!("Reset system cursors to defaults via API (A version)"); - } + } } else { println!("Reset system cursors to defaults via API (W version)"); } @@ -450,52 +505,78 @@ mod windows { // Function to save the original system cursors fn save_original_cursors() { - unsafe { - // Only save if we haven't already - if ORIGINAL_CURSORS.is_none() { - let mut cursors = Vec::new(); + // Lock the Mutex + let mut original_cursors_guard = ORIGINAL_CURSORS.lock().unwrap(); + // Only save if the Option inside the Mutex is None + if original_cursors_guard.is_none() { + let mut saved_cursors = Vec::new(); + unsafe { for &cursor_id in SYSTEM_CURSORS.iter() { - let cursor = LoadCursorW(null_mut(), cursor_id as _); - if !cursor.is_null() { - // Make a copy of the cursor - let cursor_copy = CopyIcon(cursor as _) as HCURSOR; + // Load the *current* system cursor for this ID + // Use MAKEINTRESOURCEW to convert cursor_id to a resource pointer + let hcursor = LoadCursorW(null_mut(), MAKEINTRESOURCEW(cursor_id as u16)); + if !hcursor.is_null() { + // Make a copy of the loaded cursor to store + let cursor_copy = CopyIcon(hcursor); if !cursor_copy.is_null() { - cursors.push((cursor_id, cursor_copy)); + // Store the wrapped handle + saved_cursors.push((cursor_id, SyncHCURSOR(cursor_copy))); + // CopyIcon creates a new handle, no need to destroy original loaded one. + } else { + eprintln!("Failed to copy system cursor for ID {}", cursor_id); } + } else { + eprintln!("Failed to load system cursor for ID {}", cursor_id); } } + } - ORIGINAL_CURSORS = Some(cursors); - println!("Saved {} original system cursors", ORIGINAL_CURSORS.as_ref().unwrap().len()); + if !saved_cursors.is_empty() { + println!("Saved {} original system cursors", saved_cursors.len()); + *original_cursors_guard = Some(saved_cursors); + } else { + eprintln!("Warning: Failed to save any original system cursors."); + // Keep the Option as None } } + // else: Already saved, do nothing. + // MutexGuard is dropped here, unlocking the Mutex. } // Function to create a bitmap from an RGBA image with alpha channel - unsafe fn create_alpha_bitmap(image: &RgbaImage) -> Option<(HBITMAP, HDC)> { - // Clean up any existing bitmap and DC - if let Some(bitmap) = CURSOR_BITMAP.take() { - DeleteObject(bitmap as _); - } + unsafe fn create_alpha_bitmap(image: &RgbaImage) -> Option<(SyncHBITMAP, SyncHDC)> { + // Clean up existing resources first by taking them from the Mutex + let old_bitmap_wrapper = CURSOR_BITMAP.lock().unwrap().take(); + let old_dc_wrapper = CURSOR_DC.lock().unwrap().take(); - if let Some(dc) = CURSOR_DC.take() { - DeleteDC(dc); + if let Some(bitmap_wrapper) = old_bitmap_wrapper { + DeleteObject(bitmap_wrapper.0 as _); + } + if let Some(dc_wrapper) = old_dc_wrapper { + DeleteDC(dc_wrapper.0); } // Get image dimensions let (width, height) = image.dimensions(); + if width == 0 || height == 0 { + eprintln!("Cannot create bitmap for zero-sized image."); + return None; + } + // Create a device context compatible with the screen - let screen_dc = GetDC(std::ptr::null_mut()); + let screen_dc = GetDC(null_mut()); if screen_dc.is_null() { + eprintln!("Failed to get screen DC"); return None; } // Create a compatible memory DC let mem_dc = CreateCompatibleDC(screen_dc); if mem_dc.is_null() { - ReleaseDC(std::ptr::null_mut(), screen_dc); + eprintln!("Failed to create compatible DC"); + ReleaseDC(null_mut(), screen_dc); return None; } @@ -507,36 +588,47 @@ mod windows { bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; - bmi.bmiHeader.biSizeImage = (width * height * 4) as u32; // Size in bytes + // biSizeImage can often be 0 for BI_RGB bitmaps + // bmi.bmiHeader.biSizeImage = (width * height * 4) as u32; // Create a DIB section that we can write to - let mut bits: *mut std::ffi::c_void = std::ptr::null_mut(); + let mut bits: *mut std::ffi::c_void = null_mut(); let bitmap = CreateDIBSection( - mem_dc, - &bmi, + mem_dc, // Use the mem_dc here + &bmi as *const _ as *mut _, // Pass pointer to BITMAPINFO DIB_RGB_COLORS, &mut bits, - std::ptr::null_mut(), - 0 + null_mut(), // No file mapping object + 0 // Offset (must be 0) ); - if bitmap.is_null() || bits.is_null() { + if bitmap.is_null() { + eprintln!("CreateDIBSection failed (Error {})", winapi::um::errhandlingapi::GetLastError()); DeleteDC(mem_dc); - ReleaseDC(std::ptr::null_mut(), screen_dc); + ReleaseDC(null_mut(), screen_dc); return None; } + if bits.is_null() { + eprintln!("CreateDIBSection succeeded but returned null bits pointer."); + DeleteObject(bitmap as _); // Clean up the created bitmap + DeleteDC(mem_dc); + ReleaseDC(null_mut(), screen_dc); + return None; + } // Select the bitmap into the memory DC - let _old_bitmap = SelectObject(mem_dc, bitmap as _); + let _old_bitmap = SelectObject(mem_dc, bitmap as _); // Cast HBITMAP to HGDIOBJ - // Copy the image data to the DIB section with premultiplied alpha + // Copy the image data to the DIB section with premultiplied alpha (BGRA format) let pixels = image.as_raw(); let dest = bits as *mut u8; + let stride = (width * 4) as usize; // Bytes per row for y in 0..height { for x in 0..width { let src_idx = ((y * width + x) * 4) as usize; - let dest_idx = ((y * width + x) * 4) as isize; + // Calculate destination index carefully, respecting stride + let dest_idx = (y as usize * stride) + (x as usize * 4); // Get RGBA components let r = pixels[src_idx]; @@ -544,40 +636,47 @@ mod windows { let b = pixels[src_idx + 2]; let a = pixels[src_idx + 3]; - // Write to DIB with premultiplied alpha (BGRA format) + // Write BGRA with premultiplied alpha to DIB section // Premultiply: (color * alpha) / 255 - *dest.offset(dest_idx) = (b as u16 * a as u16 / 255) as u8; // B - *dest.offset(dest_idx + 1) = (g as u16 * a as u16 / 255) as u8; // G - *dest.offset(dest_idx + 2) = (r as u16 * a as u16 / 255) as u8; // R - *dest.offset(dest_idx + 3) = a; // A + // Ensure intermediate calculations use u16 to avoid overflow + let alpha_factor = a as u16; + // Using ptr::add for potentially better optimization/safety + dest.add(dest_idx).write((b as u16 * alpha_factor / 255) as u8); // B + dest.add(dest_idx + 1).write((g as u16 * alpha_factor / 255) as u8); // G + dest.add(dest_idx + 2).write((r as u16 * alpha_factor / 255) as u8); // R + dest.add(dest_idx + 3).write(a); // A } } - // Clean up - ReleaseDC(std::ptr::null_mut(), screen_dc); + // Clean up screen DC (keep mem_dc and bitmap) + ReleaseDC(null_mut(), screen_dc); - // Store the bitmap and DC for later use - CURSOR_BITMAP = Some(bitmap); - CURSOR_DC = Some(mem_dc); + // Create wrapped handles + let sync_bitmap = SyncHBITMAP(bitmap); + let sync_dc = SyncHDC(mem_dc); - Some((bitmap, mem_dc)) + // Store the new bitmap and DC in the Mutex> + *CURSOR_BITMAP.lock().unwrap() = Some(sync_bitmap); + *CURSOR_DC.lock().unwrap() = Some(sync_dc); + + // Return the wrapped handles + Some((sync_bitmap, sync_dc)) } // Function to hide the system cursor - called once at startup pub fn hide_system_cursor() -> bool { - // Save the original system cursors before hiding them + // Save original cursors *before* hiding save_original_cursors(); - // Register cleanup handler to ensure cursor is restored on exit + // Register cleanup handler (idempotent call) register_cleanup(); - // Hide the system cursor - unsafe { - if !CURSOR_HIDDEN { - // Create an invisible cursor (1x1 transparent cursor) - // Create bitmap data for a 1x1 cursor - let and_plane: [u8; 1] = [0xFF]; // All bits 1 = transparent - let xor_plane: [u8; 1] = [0x00]; // All bits 0 = black + // Check if already hidden using AtomicBool load + if !CURSOR_HIDDEN.load(Ordering::SeqCst) { + unsafe { + // Create a 1x1 transparent cursor + let and_plane: [u8; 1] = [0xFF]; // Transparent mask + let xor_plane: [u8; 1] = [0x00]; // Black color (doesn't matter with transparent mask) let empty_cursor = CreateCursor( null_mut(), // hInst @@ -585,74 +684,104 @@ mod windows { 0, // yHotSpot 1, // nWidth 1, // nHeight - and_plane.as_ptr() as *const _, // pvANDPlane - xor_plane.as_ptr() as *const _, // pvXORPlane + and_plane.as_ptr() as *const _, + xor_plane.as_ptr() as *const _, ); if empty_cursor.is_null() { - eprintln!("Failed to create empty cursor"); + eprintln!("Failed to create empty cursor for hiding."); return false; } - // Replace all system cursors with our empty cursor + let mut all_set = true; + // Replace all tracked system cursors with the empty one for &cursor_id in SYSTEM_CURSORS.iter() { - // Make a copy of our empty cursor for each system cursor - let cursor_copy = CopyIcon(empty_cursor as _) as HCURSOR; + // Need a fresh copy for each call to SetSystemCursor + let cursor_copy = CopyIcon(empty_cursor); if !cursor_copy.is_null() { - // Set the system cursor if SetSystemCursor(cursor_copy, cursor_id) == 0 { - eprintln!("Failed to set system cursor {}", cursor_id); + eprintln!("Failed to set system cursor {} to empty.", cursor_id); + // Destroy the copy if SetSystemCursor failed + winapi::um::winuser::DestroyCursor(cursor_copy); + all_set = false; } + // If successful, SetSystemCursor takes ownership, no need to destroy copy. + } else { + eprintln!("Failed to copy empty cursor for ID {}", cursor_id); + all_set = false; } } - CURSOR_HIDDEN = true; - println!("System cursors hidden once at startup"); - } + // Destroy the original empty cursor template + winapi::um::winuser::DestroyCursor(empty_cursor); + + if all_set { + // Mark as hidden *only if* successful + CURSOR_HIDDEN.store(true, Ordering::SeqCst); + println!("System cursors hidden successfully."); + true + } else { + eprintln!("Failed to hide all system cursors. Attempting to restore..."); + // Attempt to restore immediately if hiding failed partially + reset_system_cursors(); // Use the API reset + // Don't set CURSOR_HIDDEN to true + false + } + } // end unsafe + } else { + println!("System cursors already hidden."); + true // Already hidden is considered success } - true } // Function to update the cursor image without changing system cursors pub fn update_cursor_image(path: &Path) -> bool { - // Load the cursor image match image_open(path) { Ok(img) => { let rgba_img = img.to_rgba8(); + println!("Loaded PNG cursor: {:?} ({}x{})", path, rgba_img.width(), rgba_img.height()); - // Store the image for reference + // Store the image clone in the static mutex *CURRENT_CURSOR_IMAGE.lock().unwrap() = Some(rgba_img.clone()); - println!("Using PNG cursor: {:?}", path); // Create the alpha bitmap for the cursor - unsafe { - if let Some((_bitmap, _dc)) = create_alpha_bitmap(&rgba_img) { - println!("Created alpha bitmap for cursor"); - } else { - eprintln!("Failed to create alpha bitmap for cursor"); - return false; - } - } + let bitmap_created = unsafe { create_alpha_bitmap(&rgba_img).is_some() }; - // Create or get the cursor window - unsafe { - if CURSOR_WINDOW.is_none() { - if let Some(window) = create_cursor_window() { - CURSOR_WINDOW = Some(window); + if !bitmap_created { + eprintln!("Failed to create alpha bitmap for cursor"); + // Clear the stored image if bitmap creation failed + *CURRENT_CURSOR_IMAGE.lock().unwrap() = None; + return false; + } + println!("Created alpha bitmap for cursor"); + + // Create or get the cursor window handle + // Lock the window Mutex + let mut window_guard = CURSOR_WINDOW.lock().unwrap(); + if window_guard.is_none() { + match unsafe { create_cursor_window() } { + Some(sync_hwnd) => { + *window_guard = Some(sync_hwnd); println!("Created cursor window"); - } else { + } + None => { eprintln!("Failed to create cursor window"); + // Clean up bitmap/DC if window fails + cleanup_gdi_resources(); + *CURRENT_CURSOR_IMAGE.lock().unwrap() = None; return false; } } } + // Drop the guard explicitly after check/creation + drop(window_guard); - // Initialize cursor position - let mut point = POINT { x: 0, y: 0 }; + + // Initialize cursor position immediately after update unsafe { + let mut point = POINT { x: 0, y: 0 }; if GetCursorPos(&mut point) != 0 { - // Update cursor position - update_cursor_position(&point); + update_cursor_position(&point); // Force initial update } } @@ -662,147 +791,96 @@ mod windows { true }, Err(e) => { - eprintln!("Failed to load cursor image: {}", e); + eprintln!("Failed to load cursor image '{}': {}", path.display(), e); false } } } - // Function to restore the cursor when the program exits + // Helper to clean up just GDI resources + fn cleanup_gdi_resources() { + let bitmap_wrapper_to_delete = CURSOR_BITMAP.lock().unwrap().take(); + let dc_wrapper_to_delete = CURSOR_DC.lock().unwrap().take(); + unsafe { + if let Some(bitmap_wrapper) = bitmap_wrapper_to_delete { DeleteObject(bitmap_wrapper.0 as _); } + if let Some(dc_wrapper) = dc_wrapper_to_delete { DeleteDC(dc_wrapper.0); } + } + } + + + // Function to restore the cursor when the program exits (called explicitly) pub fn restore_cursor() { - println!("Explicit restore_cursor called"); - - // Call our cleanup function which handles cursor restoration - cleanup(); - - // Join the thread if it exists - if let Some(handle) = RENDER_THREAD.lock().unwrap().take() { - // Use a timeout to avoid hanging if the thread is stuck - let thread_handle = handle; - match thread_handle.join() { - Ok(_) => println!("Render thread joined successfully"), - Err(_) => eprintln!("Error joining render thread"), - } - } - - // Clean up bitmap and DC - unsafe { - // Clean up the bitmap if it exists - if let Some(bitmap) = CURSOR_BITMAP.take() { - DeleteObject(bitmap as _); - println!("Cursor bitmap deleted during restore"); - } - - // Clean up the DC if it exists - if let Some(dc) = CURSOR_DC.take() { - DeleteDC(dc); - println!("Cursor DC deleted during restore"); - } - } - - // Destroy the cursor window if it exists - unsafe { - if let Some(hwnd) = CURSOR_WINDOW.take() { - if DestroyWindow(hwnd) == 0 { - eprintln!("Failed to destroy cursor window"); - } else { - println!("Cursor window destroyed"); - } - } - } - - // Clear the cursor image - *CURRENT_CURSOR_IMAGE.lock().unwrap() = None; - - // Reset the last cursor position - *LAST_CURSOR_POS.lock().unwrap() = None; - - // Unregister our control handler to avoid double cleanup - unsafe { - if CTRL_HANDLER_REGISTERED { - if SetConsoleCtrlHandler(Some(ctrl_handler), FALSE) == 0 { - eprintln!("Failed to unregister control handler"); - } else { - CTRL_HANDLER_REGISTERED = false; - println!("Control handler unregistered"); - } - } - } - - // Final verification that cursors are restored - unsafe { - if CURSOR_HIDDEN { - println!("Cursor still marked as hidden after cleanup, forcing reset"); - reset_system_cursors(); - CURSOR_HIDDEN = false; - } - } + println!("Explicit restore_cursor called, performing cleanup..."); + cleanup(); // Call the main cleanup function + // No need to duplicate cleanup logic here } // Function to start the rendering thread if it's not already running fn start_render_thread_if_needed() { - let mut render_thread_guard = RENDER_THREAD.lock().unwrap(); + // Check if active *before* locking the thread handle mutex for performance + if !RENDERING_ACTIVE.load(Ordering::SeqCst) { + let mut render_thread_guard = RENDER_THREAD.lock().unwrap(); + // Double check inside the lock + if render_thread_guard.is_none() { + // Set the flag *before* spawning the thread + RENDERING_ACTIVE.store(true, Ordering::SeqCst); - // Only start a new thread if one isn't already running - if render_thread_guard.is_none() { - // Set the rendering active flag - RENDERING_ACTIVE.store(true, Ordering::SeqCst); + // Spawn the thread + let handle = thread::spawn(|| { + println!("Starting cursor render thread..."); + // Render loop + while RENDERING_ACTIVE.load(Ordering::Relaxed) { // Relaxed is fine for loop check + render_cursor_internal(); // Call internal render function + // Use a variable sleep time, e.g., target 120Hz (approx 8ms) + thread::sleep(Duration::from_millis(8)); + } + println!("Cursor render thread stopped."); + }); - // Clone the Arc for the thread - let cursor_image_arc = CURRENT_CURSOR_IMAGE.clone(); - - // Create a new thread for continuous rendering - let handle = thread::spawn(move || { - println!("Starting cursor render thread"); - - // Render loop - while RENDERING_ACTIVE.load(Ordering::SeqCst) { - render_cursor_internal(&cursor_image_arc); - - // Sleep to control frame rate (120 FPS for smoother cursor movement) - thread::sleep(Duration::from_millis(8)); - } - - println!("Cursor render thread stopped"); - }); - - // Store the thread handle - *render_thread_guard = Some(handle); + // Store the thread handle + *render_thread_guard = Some(handle); + println!("Render thread started and handle stored."); + } + // else: Another thread started it between the outer check and acquiring the lock } + // else: Already running } // Internal function to render the cursor (called from the render thread) - fn render_cursor_internal(_cursor_image_arc: &Arc>>) { - // Get the current mouse position + fn render_cursor_internal() { unsafe { let mut point = POINT { x: 0, y: 0 }; if GetCursorPos(&mut point) == 0 { + // Failed to get cursor position, maybe log error? + // eprintln!("GetCursorPos failed in render loop"); return; } - // Ensure the cursor window is always topmost, even if no movement occurred - if let Some(hwnd) = CURSOR_WINDOW { - // Always ensure the window is topmost, even if the cursor hasn't moved - // This helps ensure our cursor stays above system menus and other topmost windows - SetWindowPos( - hwnd, - HWND_TOPMOST, - 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE - ); + // --- Check if window needs to be topmost --- + // It's generally better to ensure topmost status less frequently, + // perhaps only when the window is created or maybe periodically, + // as calling SetWindowPos constantly can have overhead. + // However, keeping it here ensures responsiveness if other apps fight for topmost. + // Let's keep it for now. + if let Some(hwnd_wrapper) = *CURSOR_WINDOW.lock().unwrap() { // Get handle copy + SetWindowPos(hwnd_wrapper.0, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } + // --- End Topmost Check --- - // Update the cursor position using our new function + // Update the cursor graphic position update_cursor_position(&point); } } - // Function to render the custom cursor (called from the application) + // Public function to ensure the custom cursor is rendering (main purpose now is to start thread) pub fn render_cursor() { - // This is now just a trigger to ensure the render thread is running start_render_thread_if_needed(); } -} +} // end mod windows + + +// --- Non-Windows Stubs --- +// (Keep these as they are, they don't use static mut) // macOS implementation #[cfg(target_os = "macos")] @@ -810,28 +888,15 @@ mod macos { use std::path::Path; pub fn hide_system_cursor() -> bool { - // macOS cursor hiding implementation would go here - // This is a placeholder - actual implementation would require - // Objective-C/Cocoa bindings to NSCursor - println!("macOS system cursor hiding not yet implemented"); - false + println!("macOS system cursor hiding not yet implemented"); false } - pub fn update_cursor_image(_path: &Path) -> bool { - // macOS cursor image update implementation would go here - println!("macOS cursor image update not yet implemented"); - false + println!("macOS cursor image update not yet implemented"); false } - pub fn restore_cursor() { - // Placeholder for restoring cursor on macOS println!("macOS cursor restoration not yet implemented"); } - - pub fn render_cursor() { - // On macOS, we would update the cursor on mouse movement - // This is a placeholder - } + pub fn render_cursor() { } } // Linux implementation @@ -840,31 +905,20 @@ mod linux { use std::path::Path; pub fn hide_system_cursor() -> bool { - // Linux cursor hiding implementation would go here - // This is a placeholder - actual implementation would require - // X11 or Wayland bindings - println!("Linux system cursor hiding not yet implemented"); - false + println!("Linux system cursor hiding not yet implemented"); false } - pub fn update_cursor_image(_path: &Path) -> bool { - // Linux cursor image update implementation would go here - println!("Linux cursor image update not yet implemented"); - false + println!("Linux cursor image update not yet implemented"); false } - pub fn restore_cursor() { - // Placeholder for restoring cursor on Linux println!("Linux cursor restoration not yet implemented"); } - - pub fn render_cursor() { - // On Linux, we would update the cursor on mouse movement - // This is a placeholder - } + pub fn render_cursor() { } } -// Export the appropriate implementation based on platform +// --- Public Exports --- +// (Keep these as they are) + #[cfg(windows)] pub use windows::{restore_cursor, render_cursor, hide_system_cursor, update_cursor_image}; @@ -876,23 +930,13 @@ pub use linux::{restore_cursor, render_cursor, hide_system_cursor, update_cursor // Default implementation for other platforms #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] -pub fn hide_system_cursor() -> bool { - println!("System cursor hiding not supported on this platform"); - false +pub mod unsupported { + use std::path::Path; + pub fn hide_system_cursor() -> bool { println!("System cursor hiding not supported"); false } + pub fn update_cursor_image(_path: &Path) -> bool { println!("Cursor image update not supported"); false } + pub fn restore_cursor() { println!("Cursor restoration not supported"); } + pub fn render_cursor() { } } #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] -pub fn update_cursor_image(_path: &Path) -> bool { - println!("Cursor image update not supported on this platform"); - false -} - -#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] -pub fn restore_cursor() { - println!("Cursor restoration not supported on this platform"); -} - -#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] -pub fn render_cursor() { - // No-op for unsupported platforms -} +pub use unsupported::{restore_cursor, render_cursor, hide_system_cursor, update_cursor_image}; \ No newline at end of file