// 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; // Make Mutex and AtomicBool readily available use std::sync::{Mutex, atomic::{AtomicBool, Ordering}}; use std::time::Duration; // Remove Once - Lazy handles initialization // use std::sync::Once; use winapi::{ um::winuser::{ GetDC, ReleaseDC, GetCursorPos, LoadCursorW, 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_NOACTIVATE, // Added NOACTIVATE WS_POPUP, SW_SHOW, HWND_TOPMOST, SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, // Added SWP_NOACTIVATE WM_DESTROY, WM_CLOSE, WM_MOUSEMOVE, WM_RBUTTONDOWN, WM_RBUTTONUP, // Added right mouse button events CS_HREDRAW, CS_VREDRAW, ULW_ALPHA, WNDCLASSEXW, // Import WNDCLASSEXW MAKEINTRESOURCEW, // Add this for converting cursor IDs to resource pointers // Add mouse hook related imports SetWindowsHookExW, UnhookWindowsHookEx, CallNextHookEx, WH_MOUSE_LL, HC_ACTION, MSLLHOOKSTRUCT, }, um::libloaderapi::GetModuleHandleW, shared::windef::HHOOK, um::wingdi::{ CreateCompatibleDC, DeleteDC, SelectObject, DeleteObject, BLENDFUNCTION, AC_SRC_OVER, AC_SRC_ALPHA, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS, BI_RGB, CreateDIBSection, }, um::consoleapi::SetConsoleCtrlHandler, 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 (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 (keep these) const SPI_SETCURSORS_A: u32 = 0x0057; const SPIF_UPDATEINIFILE: u32 = 0x01; const SPIF_SENDCHANGE: u32 = 0x02; // --- 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 {} // Wrapper for HHOOK (hook handle) #[derive(Copy, Clone, Debug)] struct SyncHHOOK(HHOOK); unsafe impl Send for SyncHHOOK {} unsafe impl Sync for SyncHHOOK {} // --- Thread-Safe Static Variables --- // Use AtomicBool for simple flags static CURSOR_HIDDEN: AtomicBool = AtomicBool::new(false); static CTRL_HANDLER_REGISTERED: AtomicBool = AtomicBool::new(false); // 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 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)); // Mouse hook related variables static MOUSE_HOOK_HANDLE: Lazy>> = Lazy::new(|| Mutex::new(None)); // This one is for CallNextHookEx to avoid locking inside the hook callback static CURRENT_HOOK_FOR_CALLBACK: std::sync::atomic::AtomicPtr = std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()); static LAST_MOUSE_MOVE_TIME: Lazy>> = Lazy::new(|| Mutex::new(None)); const MOUSE_UPDATE_INTERVAL: Duration = Duration::from_millis(8); // Throttle to ~120Hz // --- 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 32515, // IDC_CROSS 32514, // IDC_WAIT 32649, // IDC_HAND 32650, // IDC_APPSTARTING 32648, // IDC_NO 32646, // IDC_SIZEALL 32645, // IDC_SIZENS 32644, // IDC_SIZEWE 32642, // IDC_SIZENWSE ]; // Window class name for our cursor window (keep this) const CURSOR_WINDOW_CLASS: &str = "CursorRushOverlay"; // 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 => { // 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 low-level mouse hook _ => DefWindowProcW(hwnd, msg, wparam, lparam), } } // Low-level mouse hook procedure unsafe extern "system" fn low_level_mouse_proc(n_code: i32, w_param: WPARAM, l_param: LPARAM) -> LRESULT { if n_code == HC_ACTION { // Extract mouse position from the hook struct for any mouse event let p_msll_hook_struct = l_param as *const MSLLHOOKSTRUCT; if !p_msll_hook_struct.is_null() { let msll_hook_struct = *p_msll_hook_struct; let current_pos = msll_hook_struct.pt; match w_param as UINT { WM_MOUSEMOVE => { let mut last_update_time_guard = LAST_MOUSE_MOVE_TIME.lock().unwrap(); let now = std::time::Instant::now(); if last_update_time_guard.map_or(true, |last_time| now.duration_since(last_time) >= MOUSE_UPDATE_INTERVAL) { // update_cursor_position already contains logic to only update if position actually changed via LAST_CURSOR_POS update_cursor_position(¤t_pos); *last_update_time_guard = Some(now); } }, // Handle right mouse button down - immediately update cursor position and force topmost WM_RBUTTONDOWN => { // Force an immediate update of the cursor position when right-clicking // This ensures the overlay is visible before the menu appears update_cursor_position(¤t_pos); // Force the cursor window to be topmost if let Some(hwnd_wrapper) = *CURSOR_WINDOW.lock().unwrap() { SetWindowPos( hwnd_wrapper.0, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, // SWP_NOACTIVATE is critical ); } }, // Handle other mouse events if needed _ => { /* Other mouse messages can be handled here if needed */ } } } } // Call the next hook in the chain. // Pass the HHOOK of our own hook, loaded from CURRENT_HOOK_FOR_CALLBACK. CallNextHookEx( CURRENT_HOOK_FOR_CALLBACK.load(std::sync::atomic::Ordering::Relaxed) as HHOOK, n_code, w_param, l_param, ) } // Install mouse hook function fn install_mouse_hook_if_needed() -> bool { let mut hook_guard = MOUSE_HOOK_HANDLE.lock().unwrap(); if hook_guard.is_none() { unsafe { // GetModuleHandleW(null_mut()) gets the HMODULE for the current process (EXE) // which is correct for a hook procedure within the same process. let h_instance = GetModuleHandleW(null_mut()); if h_instance.is_null() { eprintln!("Failed to get module handle for setting mouse hook: {}", std::io::Error::last_os_error()); return false; } let hook = SetWindowsHookExW( WH_MOUSE_LL, // Hook type: Low-level mouse Some(low_level_mouse_proc), // Pointer to hook procedure h_instance, // HMODULE of the DLL containing the hook proc (or current process) 0 // Thread ID (0 for all threads on current desktop) ); if !hook.is_null() { // Create wrapped handle let sync_hook = SyncHHOOK(hook); *hook_guard = Some(sync_hook); CURRENT_HOOK_FOR_CALLBACK.store(hook as *mut _, std::sync::atomic::Ordering::SeqCst); println!("Low-level mouse hook installed successfully."); return true; } else { eprintln!("Failed to install low-level mouse hook: {}", std::io::Error::last_os_error()); return false; } } } true // Already installed } // Uninstall mouse hook function fn uninstall_mouse_hook() { let mut hook_guard = MOUSE_HOOK_HANDLE.lock().unwrap(); if let Some(hook_wrapper) = hook_guard.take() { // .take() removes it from Option and returns it unsafe { // Extract the raw handle using .0 let hook = hook_wrapper.0; if UnhookWindowsHookEx(hook) != 0 { CURRENT_HOOK_FOR_CALLBACK.store(std::ptr::null_mut(), std::sync::atomic::Ordering::SeqCst); println!("Low-level mouse hook uninstalled successfully."); } else { eprintln!("Failed to uninstall low-level mouse hook: {}", std::io::Error::last_os_error()); // Put it back if unhooking failed, though this is unlikely. *hook_guard = Some(hook_wrapper); } } } } // 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 position_changed = last_pos_guard.map_or(true, |last| last.x != point.x || last.y != point.y); if position_changed { // Update last position *within the lock* *last_pos_guard = Some(*point); // 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; // Get cursor image dimensions let (width, height) = cursor_image.dimensions(); 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 }; // 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 }; // The window is already set to visible and topmost when created in create_cursor_window() // But we need to re-assert TOPMOST after UpdateLayeredWindow to ensure it stays above system tray menus // The key is to use SWP_NOACTIVATE to prevent stealing focus from the menu // 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, ); // Re-assert TOPMOST after successful update, with SWP_NOACTIVATE to prevent stealing focus if result != 0 { SetWindowPos( hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, // Added SWP_NOACTIVATE to prevent stealing focus ); } 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 { // Convert class name to wide string let class_name_wide: Vec = OsStr::new(CURSOR_WINDOW_CLASS) .encode_wide() .chain(std::iter::once(0)) .collect(); // 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 = 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 { // 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 let hwnd = CreateWindowExW( 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, // 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, error: {}", winapi::um::errhandlingapi::GetLastError()); return None; } // Show the window and ensure it's topmost ShowWindow(hwnd, SW_SHOW); SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); // Return the wrapped handle Some(SyncHWND(hwnd)) } // 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 { // 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() { // Uninstall the mouse hook FIRST uninstall_mouse_hook(); // 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); } let mut restoration_success = false; // 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() { 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 from saved state."); restoration_success = true; } } } // Drop the guard drop(original_cursors_guard); // 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)."); } } } // 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."); } // 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 { 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."); } } 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 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 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 OnceCell::get_or_init for thread-safe single initialization INIT.get_or_init(|| { unsafe { if SetConsoleCtrlHandler(Some(ctrl_handler), TRUE) == 0 { eprintln!("Failed to register control handler"); } else { println!("Control handler registered for cursor restoration"); CTRL_HANDLER_REGISTERED.store(true, Ordering::SeqCst); } } }); } // Initialize module 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(); println!("Windows cursor module initialized with cleanup handlers"); } // 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, performing final cleanup..."); cleanup(); } // Function to reset all system cursors to their defaults fn reset_system_cursors() { unsafe { // Use the Windows API to reset system cursors 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)"); } } } // Function to save the original system cursors fn save_original_cursors() { // 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() { // 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() { // 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); } } } 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<(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(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(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() { eprintln!("Failed to create compatible DC"); ReleaseDC(null_mut(), screen_dc); return None; } // Prepare BITMAPINFO structure for a 32-bit BGRA DIB let mut bmi: BITMAPINFO = std::mem::zeroed(); bmi.bmiHeader.biSize = std::mem::size_of::() as u32; bmi.bmiHeader.biWidth = width as i32; bmi.bmiHeader.biHeight = -(height as i32); // Negative height for top-down DIB bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; // 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 = null_mut(); let bitmap = CreateDIBSection( mem_dc, // Use the mem_dc here &bmi as *const _ as *mut _, // Pass pointer to BITMAPINFO DIB_RGB_COLORS, &mut bits, null_mut(), // No file mapping object 0 // Offset (must be 0) ); if bitmap.is_null() { eprintln!("CreateDIBSection failed (Error {})", winapi::um::errhandlingapi::GetLastError()); DeleteDC(mem_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 _); // Cast HBITMAP to HGDIOBJ // 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; // 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]; let g = pixels[src_idx + 1]; let b = pixels[src_idx + 2]; let a = pixels[src_idx + 3]; // Write BGRA with premultiplied alpha to DIB section // Premultiply: (color * alpha) / 255 // 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 screen DC (keep mem_dc and bitmap) ReleaseDC(null_mut(), screen_dc); // Create wrapped handles let sync_bitmap = SyncHBITMAP(bitmap); let sync_dc = SyncHDC(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 original cursors *before* hiding save_original_cursors(); // Register cleanup handler (idempotent call) register_cleanup(); // 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 0, // xHotSpot 0, // yHotSpot 1, // nWidth 1, // nHeight and_plane.as_ptr() as *const _, xor_plane.as_ptr() as *const _, ); if empty_cursor.is_null() { eprintln!("Failed to create empty cursor for hiding."); return false; } let mut all_set = true; // Replace all tracked system cursors with the empty one for &cursor_id in SYSTEM_CURSORS.iter() { // Need a fresh copy for each call to SetSystemCursor let cursor_copy = CopyIcon(empty_cursor); if !cursor_copy.is_null() { if SetSystemCursor(cursor_copy, cursor_id) == 0 { 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; } } // 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 } } // Function to update the cursor image without changing system cursors pub fn update_cursor_image(path: &Path) -> bool { 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 clone in the static mutex *CURRENT_CURSOR_IMAGE.lock().unwrap() = Some(rgba_img.clone()); // Create the alpha bitmap for the cursor let bitmap_created = unsafe { create_alpha_bitmap(&rgba_img).is_some() }; 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"); } 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); // Install the mouse hook if !install_mouse_hook_if_needed() { eprintln!("Mouse hook installation failed, custom cursor might not follow mouse."); // We'll continue anyway as this is not a fatal error } // Initialize cursor position immediately after update unsafe { let mut point = POINT { x: 0, y: 0 }; if GetCursorPos(&mut point) != 0 { update_cursor_position(&point); // Force initial update } } true }, Err(e) => { eprintln!("Failed to load cursor image '{}': {}", path.display(), e); false } } } // 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, performing cleanup..."); cleanup(); // Call the main cleanup function // No need to duplicate cleanup logic here } // Public function that used to start the render thread, now a no-op since we use the mouse hook pub fn render_cursor() { // No-op: Cursor rendering is now handled by the mouse hook } } // end mod windows // --- Non-Windows Stubs --- // (Keep these as they are, they don't use static mut) // macOS implementation #[cfg(target_os = "macos")] mod macos { use std::path::Path; pub fn hide_system_cursor() -> bool { println!("macOS system cursor hiding not yet implemented"); false } pub fn update_cursor_image(_path: &Path) -> bool { println!("macOS cursor image update not yet implemented"); false } pub fn restore_cursor() { println!("macOS cursor restoration not yet implemented"); } pub fn render_cursor() { } } // Linux implementation #[cfg(target_os = "linux")] mod linux { use std::path::Path; pub fn hide_system_cursor() -> bool { println!("Linux system cursor hiding not yet implemented"); false } pub fn update_cursor_image(_path: &Path) -> bool { println!("Linux cursor image update not yet implemented"); false } pub fn restore_cursor() { println!("Linux cursor restoration not yet implemented"); } pub fn render_cursor() { } } // --- Public Exports --- // (Keep these as they are) #[cfg(windows)] pub use windows::{restore_cursor, hide_system_cursor, update_cursor_image, render_cursor}; #[cfg(target_os = "macos")] pub use macos::{restore_cursor, render_cursor, hide_system_cursor, update_cursor_image}; #[cfg(target_os = "linux")] pub use linux::{restore_cursor, render_cursor, hide_system_cursor, update_cursor_image}; // Default implementation for other platforms #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))] 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 use unsupported::{restore_cursor, render_cursor, hide_system_cursor, update_cursor_image};