From 9f6f3442dcfa5f4c6b0a85dec77211368e698595 Mon Sep 17 00:00:00 2001 From: JobyGitGud Date: Sat, 10 May 2025 23:42:25 -0500 Subject: [PATCH] unclean implimentation of windows cursor set as image --- src/app/state.rs | 7 +- src/platform/mod.rs | 2 +- src/platform/windows/cursor.rs | 527 +++++++++++++-------------------- src/platform/windows/hook.rs | 40 +-- src/platform/windows/mod.rs | 2 +- src/platform/windows/state.rs | 11 +- src/platform/windows/window.rs | 90 +----- src/ui/tray.rs | 1 - 8 files changed, 229 insertions(+), 451 deletions(-) diff --git a/src/app/state.rs b/src/app/state.rs index fe1891d..26c95f7 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -24,7 +24,6 @@ pub fn update_app(state: &mut CursorRush, message: Message) -> Task { // Apply the new cursor if let Some(cursor) = state.cursors.get(state.current_index) { apply_cursor(&cursor.path); - // No need to call render_cursor anymore as the mouse hook handles rendering // Load the new cursor image let current_cursor_image = match image::open(&cursor.path) { @@ -50,7 +49,6 @@ pub fn update_app(state: &mut CursorRush, message: Message) -> Task { // Apply the selected cursor if let Some(cursor) = state.cursors.get(state.current_index) { apply_cursor(&cursor.path); - // No need to call render_cursor anymore as the mouse hook handles rendering // Load the new cursor image let current_cursor_image = match image_open(&cursor.path) { @@ -253,10 +251,10 @@ impl Default for CursorRush { pub fn app_subscription(_state: &CursorRush) -> Subscription { // Create a vector to hold all subscriptions let mut subs = vec![ - // Listen for events but filter out mouse movement events to avoid spamming + // Listen for events event::listen().map(|event| { match event { - // Skip cursor movement events to avoid spamming + // We no longer need to handle cursor movement events since we're using SetSystemCursor iced::Event::Mouse(iced::mouse::Event::CursorMoved { .. }) => { // Return TrayEvent which is essentially a no-op Message::TrayEvent @@ -340,7 +338,6 @@ pub fn boot_app() -> (CursorRush, Task) { // Apply the first cursor by default if let Some(cursor) = cursors.first() { apply_cursor(&cursor.path); - // No need to call render_cursor anymore as the mouse hook handles rendering } // Create shared state diff --git a/src/platform/mod.rs b/src/platform/mod.rs index 873c902..2b0b37d 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -20,7 +20,7 @@ mod unsupported; // Export the platform-specific functions #[cfg(windows)] -pub use windows::{hide_system_cursor, update_cursor_image, restore_cursor}; +pub use windows::{hide_system_cursor, update_cursor_image, restore_cursor, handle_mouse_move}; #[cfg(target_os = "macos")] pub use macos::{hide_system_cursor, update_cursor_image, restore_cursor, render_cursor}; diff --git a/src/platform/windows/cursor.rs b/src/platform/windows/cursor.rs index 4f2e34e..76baef1 100644 --- a/src/platform/windows/cursor.rs +++ b/src/platform/windows/cursor.rs @@ -6,26 +6,22 @@ use std::sync::atomic::Ordering; use winapi::{ um::winuser::{ GetDC, ReleaseDC, GetCursorPos, LoadCursorW, SetSystemCursor, CopyIcon, - CreateCursor, SystemParametersInfoW, SPI_SETCURSORS, UpdateLayeredWindow, - SetWindowPos, HWND_TOPMOST, SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, - MAKEINTRESOURCEW, IDC_ARROW, ULW_ALPHA, DestroyWindow, + CreateCursor, SystemParametersInfoW, SPI_SETCURSORS, SetCursor, + MAKEINTRESOURCEW, IDC_ARROW, CreateIconIndirect, ICONINFO, + GetIconInfo, DestroyIcon, }, um::wingdi::{ CreateCompatibleDC, DeleteDC, SelectObject, DeleteObject, - AC_SRC_OVER, AC_SRC_ALPHA, BITMAPINFO, BITMAPINFOHEADER, - DIB_RGB_COLORS, BI_RGB, CreateDIBSection, + BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS, BI_RGB, CreateDIBSection, }, um::consoleapi::SetConsoleCtrlHandler, - shared::minwindef::{TRUE, FALSE}, - shared::windef::{POINT, SIZE}, + shared::minwindef::{TRUE, FALSE, DWORD}, + shared::windef::{POINT, HBITMAP}, }; use ::image::{RgbaImage, open as image_open}; -use winapi::um::wingdi::BLENDFUNCTION; use super::types::*; use super::state::*; -use super::window::create_cursor_window; -use super::hook::{install_mouse_hook_if_needed, uninstall_mouse_hook}; // Control handler function for console events (Ctrl+C, close, etc.) extern "system" fn ctrl_handler(_ctrl_type: u32) -> i32 { @@ -34,103 +30,13 @@ extern "system" fn ctrl_handler(_ctrl_type: u32) -> i32 { FALSE // Allow other handlers (like default exit) to run } -// Function to update the cursor position -pub 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 - }; - - // Update the layered window atomically - 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, - ); - - // 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, - ); - } - - if result == 0 { - use std::io::Error; - let error = Error::last_os_error(); - eprintln!("UpdateLayeredWindow failed: {}", error); - } - - ReleaseDC(null_mut(), screen_dc); - } else { - eprintln!("Failed to get screen DC for UpdateLayeredWindow"); - } - } - } - } -} - -// Create a bitmap from an RGBA image -unsafe fn create_bitmap_from_image(image: &RgbaImage) -> Option<(SyncHBITMAP, SyncHDC)> { +// Create a cursor from an RGBA image +unsafe fn create_cursor_from_image(image: &RgbaImage) -> Option { let (width, height) = image.dimensions(); let width_i32 = width as i32; let height_i32 = height as i32; - // Create a device context compatible with the screen + // Create device context and bitmap for the color data let screen_dc = GetDC(null_mut()); if screen_dc.is_null() { eprintln!("Failed to get screen DC"); @@ -138,9 +44,18 @@ unsafe fn create_bitmap_from_image(image: &RgbaImage) -> Option<(SyncHBITMAP, Sy } // Create a compatible DC for our bitmap - let memory_dc = CreateCompatibleDC(screen_dc); - if memory_dc.is_null() { - eprintln!("Failed to create compatible DC"); + let color_dc = CreateCompatibleDC(screen_dc); + if color_dc.is_null() { + eprintln!("Failed to create compatible DC for color"); + ReleaseDC(null_mut(), screen_dc); + return None; + } + + // Create a compatible DC for our mask bitmap + let mask_dc = CreateCompatibleDC(screen_dc); + if mask_dc.is_null() { + eprintln!("Failed to create compatible DC for mask"); + DeleteDC(color_dc); ReleaseDC(null_mut(), screen_dc); return None; } @@ -154,203 +69,185 @@ unsafe fn create_bitmap_from_image(image: &RgbaImage) -> Option<(SyncHBITMAP, Sy bitmap_info.bmiHeader.biBitCount = 32; // 32 bits per pixel (BGRA) bitmap_info.bmiHeader.biCompression = BI_RGB; - // Create the DIB section - let mut bits_ptr: *mut std::ffi::c_void = null_mut(); - let bitmap = CreateDIBSection( - memory_dc, + // Create the color DIB section + let mut color_bits_ptr: *mut std::ffi::c_void = null_mut(); + let color_bitmap = CreateDIBSection( + color_dc, &bitmap_info, DIB_RGB_COLORS, - &mut bits_ptr, + &mut color_bits_ptr, null_mut(), 0, ); - if bitmap.is_null() || bits_ptr.is_null() { - eprintln!("Failed to create DIB section"); - DeleteDC(memory_dc); + if color_bitmap.is_null() || color_bits_ptr.is_null() { + eprintln!("Failed to create color DIB section"); + DeleteDC(mask_dc); + DeleteDC(color_dc); ReleaseDC(null_mut(), screen_dc); return None; } - // Select the bitmap into the DC - let old_bitmap = SelectObject(memory_dc, bitmap as _); - if old_bitmap.is_null() { - eprintln!("Failed to select bitmap into DC"); - DeleteObject(bitmap as _); - DeleteDC(memory_dc); + // Create the mask DIB section (1-bit monochrome) + bitmap_info.bmiHeader.biBitCount = 1; // 1 bit per pixel for mask + let mut mask_bits_ptr: *mut std::ffi::c_void = null_mut(); + let mask_bitmap = CreateDIBSection( + mask_dc, + &bitmap_info, + DIB_RGB_COLORS, + &mut mask_bits_ptr, + null_mut(), + 0, + ); + + if mask_bitmap.is_null() || mask_bits_ptr.is_null() { + eprintln!("Failed to create mask DIB section"); + DeleteObject(color_bitmap as _); + DeleteDC(mask_dc); + DeleteDC(color_dc); ReleaseDC(null_mut(), screen_dc); return None; } - // Copy the image data to the DIB, converting RGBA to BGRA with premultiplied alpha - let bits = std::slice::from_raw_parts_mut(bits_ptr as *mut u8, (width * height * 4) as usize); + // Select the bitmaps into the DCs + let old_color_bitmap = SelectObject(color_dc, color_bitmap as _); + let old_mask_bitmap = SelectObject(mask_dc, mask_bitmap as _); + + if old_color_bitmap.is_null() || old_mask_bitmap.is_null() { + eprintln!("Failed to select bitmaps into DCs"); + DeleteObject(mask_bitmap as _); + DeleteObject(color_bitmap as _); + DeleteDC(mask_dc); + DeleteDC(color_dc); + ReleaseDC(null_mut(), screen_dc); + return None; + } + + // Copy the image data to the color DIB, converting RGBA to BGRA + let color_bits = std::slice::from_raw_parts_mut(color_bits_ptr as *mut u8, (width * height * 4) as usize); + + // Calculate mask stride in bytes (1 bit per pixel, padded to DWORD) + let mask_stride = ((width + 31) / 32) * 4; + let mask_bits = std::slice::from_raw_parts_mut(mask_bits_ptr as *mut u8, (mask_stride * height) as usize); + + // Clear mask bits (all transparent initially) + for i in 0..(mask_stride * height) as usize { + mask_bits[i] = 0xFF; // All bits set = transparent + } + + // Process image pixels for y in 0..height { for x in 0..width { let pixel = image.get_pixel(x, y); - let idx = ((y * width + x) * 4) as usize; + let color_idx = ((y * width + x) * 4) as usize; // Get RGBA components - let r = pixel[0] as u16; - let g = pixel[1] as u16; - let b = pixel[2] as u16; - let a = pixel[3] as u16; + let r = pixel[0]; + let g = pixel[1]; + let b = pixel[2]; + let a = pixel[3]; - // Premultiply alpha and convert to BGRA - bits[idx + 0] = ((b * a) / 255) as u8; // B - bits[idx + 1] = ((g * a) / 255) as u8; // G - bits[idx + 2] = ((r * a) / 255) as u8; // R - bits[idx + 3] = a as u8; // A + // Set color data (BGR order) + color_bits[color_idx + 0] = b; + color_bits[color_idx + 1] = g; + color_bits[color_idx + 2] = r; + color_bits[color_idx + 3] = a; + + // Update mask bit if pixel is not transparent + if a > 0 { + // Calculate bit position in mask + let byte_idx = (y * mask_stride + (x / 8)) as usize; + let bit_idx = 7 - (x % 8); // Bits are stored MSB first + + // Clear the bit (0 = opaque in AND mask) + mask_bits[byte_idx] &= !(1 << bit_idx); + } } } - // Clean up + // Create ICONINFO structure + let mut icon_info: ICONINFO = std::mem::zeroed(); + icon_info.fIcon = FALSE; // This is a cursor, not an icon + icon_info.xHotspot = width as DWORD / 2; // Center hotspot + icon_info.yHotspot = height as DWORD / 2; + icon_info.hbmMask = mask_bitmap; + icon_info.hbmColor = color_bitmap; + + // Create the cursor + let cursor = CreateIconIndirect(&mut icon_info as *mut _); + + // Clean up resources + SelectObject(color_dc, old_color_bitmap); + SelectObject(mask_dc, old_mask_bitmap); + DeleteDC(color_dc); + DeleteDC(mask_dc); ReleaseDC(null_mut(), screen_dc); - // Return the bitmap and DC - Some((SyncHBITMAP(bitmap), SyncHDC(memory_dc))) + // Windows makes a copy of the bitmaps for the cursor, so we can delete them + DeleteObject(color_bitmap as _); + DeleteObject(mask_bitmap as _); + + if cursor.is_null() { + eprintln!("Failed to create cursor"); + return None; + } + + // Return the cursor wrapped in our thread-safe type + Some(SyncHCURSOR(cursor)) } // Cleanup function to restore cursors and clean up resources pub 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 - super::state::reset_system_cursors(); + // Also try the A version just in case + super::state::reset_system_cursors(); } - 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."); - super::state::reset_system_cursors(); // Explicitly call the reset function - } - - println!("System cursors restoration attempt complete."); - } - - // 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 { + // Reset to default arrow cursor 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()); + let arrow_cursor = LoadCursorW(null_mut(), MAKEINTRESOURCEW(IDC_ARROW as u16)); + if !arrow_cursor.is_null() { + SetCursor(arrow_cursor); + println!("Reset to default arrow cursor."); } } + + println!("System cursors restoration complete."); + } + + // Destroy the custom cursor if it exists + let custom_cursor_to_destroy = CUSTOM_CURSOR.lock().unwrap().take(); + if let Some(cursor_wrapper) = custom_cursor_to_destroy { + unsafe { + DestroyIcon(cursor_wrapper.0); + println!("Custom cursor destroyed during cleanup."); + } } // Reset the last known cursor position *LAST_CURSOR_POS.lock().unwrap() = None; - // Unregister control handler (less critical now, but good practice) + // Unregister control handler 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."); - } - } + 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."); + } + } } } // --- Public API Functions --- -// Hide the system cursor +// Hide the system cursor - now just initializes the control handler pub fn hide_system_cursor() -> bool { // Initialize once INIT.get_or_init(|| { @@ -370,35 +267,15 @@ pub fn hide_system_cursor() -> bool { return true; // Already hidden } - // Save original cursors before hiding + // Save original cursors for restoration let mut original_cursors = Vec::new(); unsafe { for &cursor_id in SYSTEM_CURSORS.iter() { - // Use MAKEINTRESOURCEW to convert IDC_ARROW to a resource pointer - let empty_cursor = CreateCursor( - null_mut(), // hInst - 0, 0, // hotspot x, y - 1, 1, // width, height (minimum size) - &[0xFF] as *const _ as *const std::ffi::c_void, // AND mask (all bits 1 = transparent) - &[0x00] as *const _ as *const std::ffi::c_void, // XOR mask (all bits 0 = black) - ); - - if !empty_cursor.is_null() { - // Get the original cursor first - let original_cursor = CopyIcon(LoadCursorW(null_mut(), MAKEINTRESOURCEW(cursor_id as u16))); - if !original_cursor.is_null() { - // Save the original cursor for restoration - original_cursors.push((cursor_id, SyncHCURSOR(original_cursor))); - } - - // Set the empty cursor - if SetSystemCursor(empty_cursor, cursor_id) == 0 { - eprintln!("Failed to set system cursor {}", cursor_id); - // Don't destroy the cursor on failure, let Windows manage it - } - // SetSystemCursor takes ownership of the cursor - } else { - eprintln!("Failed to create empty cursor"); + // Get the original cursor + let original_cursor = CopyIcon(LoadCursorW(null_mut(), MAKEINTRESOURCEW(cursor_id as u16))); + if !original_cursor.is_null() { + // Save the original cursor for restoration + original_cursors.push((cursor_id, SyncHCURSOR(original_cursor))); } } } @@ -408,30 +285,13 @@ pub fn hide_system_cursor() -> bool { *ORIGINAL_CURSORS.lock().unwrap() = Some(original_cursors); } - // Mark as hidden + // Mark as hidden - this is now just a flag to indicate we've saved the original cursors CURSOR_HIDDEN.store(true, Ordering::SeqCst); - // Create the cursor window - unsafe { - let hwnd_wrapper = create_cursor_window(); - if let Some(hwnd) = hwnd_wrapper { - *CURSOR_WINDOW.lock().unwrap() = Some(hwnd); - } else { - eprintln!("Failed to create cursor window"); - return false; - } - } - - // Install the mouse hook - if !install_mouse_hook_if_needed() { - eprintln!("Failed to install mouse hook"); - return false; - } - true } -// Update the cursor image +// Update the cursor image - creates and sets a custom cursor for all system cursors pub fn update_cursor_image(path: &Path) -> bool { // Load the image let image = match image_open(path) { @@ -442,46 +302,60 @@ pub fn update_cursor_image(path: &Path) -> bool { } }; - // Store the image for rendering + // Store the image for reference *CURRENT_CURSOR_IMAGE.lock().unwrap() = Some(image.clone()); - // Create bitmap and DC unsafe { - // Clean up old bitmap and DC if they exist - let mut bitmap_guard = CURSOR_BITMAP.lock().unwrap(); - let mut dc_guard = CURSOR_DC.lock().unwrap(); - - if bitmap_guard.is_some() { - if let Some(bitmap_wrapper) = bitmap_guard.take() { - DeleteObject(bitmap_wrapper.0 as _); - } + // Clean up old cursor if it exists + let mut cursor_guard = CUSTOM_CURSOR.lock().unwrap(); + if let Some(cursor_wrapper) = cursor_guard.take() { + DestroyIcon(cursor_wrapper.0); } - if dc_guard.is_some() { - if let Some(dc_wrapper) = dc_guard.take() { - DeleteDC(dc_wrapper.0); - } - } + // Create new cursor + if let Some(cursor_wrapper) = create_cursor_from_image(&image) { + // Store the cursor for later use + *cursor_guard = Some(cursor_wrapper); - // Create new bitmap and DC - if let Some((bitmap_wrapper, dc_wrapper)) = create_bitmap_from_image(&image) { - *bitmap_guard = Some(bitmap_wrapper); - *dc_guard = Some(dc_wrapper); + // Apply the custom cursor to all system cursors + let success = apply_cursor_to_all_system_cursors(cursor_wrapper.0); + if !success { + eprintln!("Failed to apply cursor to all system cursors"); + // Even if we failed to set all system cursors, try to at least set the current cursor + SetCursor(cursor_wrapper.0); + } + + return true; } else { - eprintln!("Failed to create bitmap from image"); + eprintln!("Failed to create cursor from image"); return false; } } +} - // Force an update of the cursor position - unsafe { - let mut point = POINT { x: 0, y: 0 }; - if GetCursorPos(&mut point) != 0 { - update_cursor_position(&point); +// Apply a cursor to all system cursors +unsafe fn apply_cursor_to_all_system_cursors(cursor: winapi::shared::windef::HCURSOR) -> bool { + let mut success = true; + + // Apply the cursor to all system cursor types + for &cursor_id in SYSTEM_CURSORS.iter() { + // Make a copy of the cursor for each system cursor type + let cursor_copy = CopyIcon(cursor); + if cursor_copy.is_null() { + eprintln!("Failed to copy cursor for system cursor ID: {}", cursor_id); + success = false; + continue; + } + + // Set the system cursor + if SetSystemCursor(cursor_copy, cursor_id) == 0 { + eprintln!("Failed to set system cursor for ID: {}", cursor_id); + DestroyIcon(cursor_copy); // Clean up the copy if we failed to set it + success = false; } } - true + success } // Restore the system cursor @@ -489,4 +363,9 @@ pub fn restore_cursor() { cleanup(); } -// Render cursor functionality is now handled by the mouse hook +// Function to handle mouse movement and update the cursor +pub fn handle_mouse_move() { + // With SetSystemCursor, we don't need to constantly update the cursor on mouse move + // This function is kept for API compatibility, but it's now a no-op + // System cursors are already set to our custom cursor +} diff --git a/src/platform/windows/hook.rs b/src/platform/windows/hook.rs index 1b65d3d..42c3ed2 100644 --- a/src/platform/windows/hook.rs +++ b/src/platform/windows/hook.rs @@ -2,20 +2,17 @@ use std::ptr::null_mut; use std::sync::atomic::Ordering; -use std::time::Instant; use winapi::{ um::winuser::{ - SetWindowsHookExW, UnhookWindowsHookEx, CallNextHookEx, SetWindowPos, + SetWindowsHookExW, UnhookWindowsHookEx, CallNextHookEx, WH_MOUSE_LL, HC_ACTION, MSLLHOOKSTRUCT, - WM_MOUSEMOVE, WM_RBUTTONDOWN, HWND_TOPMOST, SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, }, um::libloaderapi::GetModuleHandleW, - shared::minwindef::{WPARAM, LPARAM, LRESULT, UINT}, + shared::minwindef::{WPARAM, LPARAM, LRESULT}, }; use super::types::*; use super::state::*; -use super::cursor::update_cursor_position; // Low-level mouse hook procedure pub unsafe extern "system" fn low_level_mouse_proc(n_code: i32, w_param: WPARAM, l_param: LPARAM) -> LRESULT { @@ -26,36 +23,11 @@ pub unsafe extern "system" fn low_level_mouse_proc(n_code: i32, w_param: WPARAM, 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 = Instant::now(); + // Store the current position for reference + *LAST_CURSOR_POS.lock().unwrap() = Some(current_pos); - 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 */ } - } + // We don't need to do anything special for mouse movement anymore + // since we're using SetSystemCursor to set all system cursors } } diff --git a/src/platform/windows/mod.rs b/src/platform/windows/mod.rs index 7e40c77..b66ba6c 100644 --- a/src/platform/windows/mod.rs +++ b/src/platform/windows/mod.rs @@ -7,4 +7,4 @@ mod hook; mod state; // Re-export the public API -pub use cursor::{hide_system_cursor, update_cursor_image, restore_cursor}; +pub use cursor::{hide_system_cursor, update_cursor_image, restore_cursor, handle_mouse_move}; diff --git a/src/platform/windows/state.rs b/src/platform/windows/state.rs index 9058b2d..412f7d1 100644 --- a/src/platform/windows/state.rs +++ b/src/platform/windows/state.rs @@ -23,15 +23,22 @@ pub static CURRENT_CURSOR_IMAGE: Lazy>> = Lazy::new(|| M pub static LAST_CURSOR_POS: Lazy>> = Lazy::new(|| Mutex::new(None)); // Use Lazy>> for WinAPI handles with our thread-safe wrappers +pub static CUSTOM_CURSOR: Lazy>> = Lazy::new(|| Mutex::new(None)); + +// Legacy variables - deprecated, no longer used with direct system cursor approach +// Kept only for API compatibility +#[deprecated(since = "0.2.0", note = "No longer used with direct system cursor approach")] pub static CURSOR_WINDOW: Lazy>> = Lazy::new(|| Mutex::new(None)); +#[deprecated(since = "0.2.0", note = "No longer used with direct system cursor approach")] pub static CURSOR_BITMAP: Lazy>> = Lazy::new(|| Mutex::new(None)); +#[deprecated(since = "0.2.0", note = "No longer used with direct system cursor approach")] pub static CURSOR_DC: Lazy>> = Lazy::new(|| Mutex::new(None)); -// Mouse hook related variables +// Mouse hook related variables - still used for tracking cursor position pub static MOUSE_HOOK_HANDLE: Lazy>> = Lazy::new(|| Mutex::new(None)); -// This one is for CallNextHookEx to avoid locking inside the hook callback pub static CURRENT_HOOK_FOR_CALLBACK: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); +#[deprecated(since = "0.2.0", note = "No longer used with direct system cursor approach")] pub static LAST_MOUSE_MOVE_TIME: Lazy>> = Lazy::new(|| Mutex::new(None)); // Use OnceCell for INIT to avoid `static mut` diff --git a/src/platform/windows/window.rs b/src/platform/windows/window.rs index 832d5c5..cc51f6f 100644 --- a/src/platform/windows/window.rs +++ b/src/platform/windows/window.rs @@ -1,89 +1,13 @@ // Windows platform window management - -use std::ffi::OsStr; -use std::os::windows::ffi::OsStrExt; -use std::ptr::null_mut; -use winapi::{ - um::winuser::{ - CreateWindowExW, DestroyWindow, ShowWindow, SetWindowPos, - RegisterClassExW, DefWindowProcW, LoadCursorW, - WS_EX_LAYERED, WS_EX_TRANSPARENT, WS_EX_TOPMOST, WS_EX_TOOLWINDOW, WS_EX_NOACTIVATE, - WS_POPUP, SW_SHOW, HWND_TOPMOST, SWP_NOSIZE, SWP_NOMOVE, - CS_HREDRAW, CS_VREDRAW, WNDCLASSEXW, MAKEINTRESOURCEW, - WM_DESTROY, WM_CLOSE, IDC_ARROW, - }, - shared::windef::HWND, - shared::minwindef::{UINT, WPARAM, LPARAM, LRESULT}, -}; +// This file is kept for compatibility but no longer creates a transparent window +// since we're now using SetSystemCursor to set the Windows cursor directly use super::types::*; -use super::state::*; -// Window procedure for our cursor window -pub 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 - 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), - } -} - -// Create a layered, topmost window for our cursor +// Create a cursor window - now a stub function that returns None +// since we no longer need a transparent window for the cursor pub 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 - 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(); - 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, - 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)) + // Return None to indicate no window was created + // This is intentional as we're now using SetSystemCursor instead + None } diff --git a/src/ui/tray.rs b/src/ui/tray.rs index 967b29c..2707b26 100644 --- a/src/ui/tray.rs +++ b/src/ui/tray.rs @@ -86,7 +86,6 @@ pub fn setup_tray_icon( if let Some(cursor) = state.cursors.get(state.current_index) { println!("Tray: Updating cursor image: {}", cursor.name); crate::app::apply_cursor(&cursor.path); - // No need to call render_cursor anymore as the mouse hook handles rendering state.current_cursor_image = image_open(&cursor.path).ok().map(|img| img.to_rgba8()); } }