use std::mem::size_of; use windows_sys::Win32::UI::{ Input::{ GetRawInputData, MOUSE_MOVE_ABSOLUTE, RAWINPUT, RAWINPUTHEADER, RID_INPUT, RIM_TYPEMOUSE, }, WindowsAndMessaging::{DefWindowProcW, MSG, WM_INPUT}, }; use winit::{event_loop::EventLoopBuilder, platform::windows::EventLoopBuilderExtWindows}; // winit 0.30 tests for MOUSE_MOVE_RELATIVE as a set flag, although its value // is zero. Keep absolute positions out of the relative-look stream. Windows // still sends the pointer movement, button and wheel messages to the window. pub(super) fn ignore_absolute_motion(builder: &mut EventLoopBuilder<()>) { builder.with_msg_hook(|message| { // SAFETY: The winit hook supplies a pointer to a live Win32 MSG until // the callback returns. let message = unsafe { &*message.cast::() }; if message.message != WM_INPUT { return false; } let mut input = RAWINPUT::default(); let mut capacity = size_of::() as u32; // SAFETY: lParam of WM_INPUT is a live HRAWINPUT. The output is // aligned and capacity describes the complete writable buffer. let read = unsafe { GetRawInputData( message.lParam as _, RID_INPUT, (&mut input as *mut RAWINPUT).cast(), &mut capacity, size_of::() as u32, ) }; if read != size_of::() as u32 || !is_absolute_mouse(&input) { return false; } // SAFETY: This is the original, live WM_INPUT message. Since the hook // consumes it, pass it to DefWindowProc to release the input handle. unsafe { DefWindowProcW( message.hwnd, message.message, message.wParam, message.lParam, ) }; true }); } fn is_absolute_mouse(input: &RAWINPUT) -> bool { if input.header.dwType != RIM_TYPEMOUSE { return false; } // SAFETY: The packet type selects the mouse member of the Win32 union. let flags = unsafe { input.data.mouse.usFlags }; flags & MOUSE_MOVE_ABSOLUTE != 0 } #[cfg(test)] mod tests { use super::*; use windows_sys::Win32::UI::Input::{ MOUSE_MOVE_NOCOALESCE, MOUSE_VIRTUAL_DESKTOP, RIM_TYPEKEYBOARD, }; #[test] fn only_absolute_mouse_packets_are_removed_from_raw_look() { let mut input = RAWINPUT::default(); input.header.dwType = RIM_TYPEMOUSE; assert!(!is_absolute_mouse(&input)); input.data.mouse.usFlags = MOUSE_MOVE_NOCOALESCE; assert!(!is_absolute_mouse(&input)); input.data.mouse.usFlags = MOUSE_MOVE_ABSOLUTE | MOUSE_VIRTUAL_DESKTOP; assert!(is_absolute_mouse(&input)); input.header.dwType = RIM_TYPEKEYBOARD; assert!(!is_absolute_mouse(&input)); } }