|
| 1 | +use std::os::windows::ffi::OsStrExt; |
| 2 | +use std::{ffi::OsStr, iter::once}; |
| 3 | + |
| 4 | +use hidapi::HidApi; |
| 5 | +use log::error; |
| 6 | +use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; |
| 7 | +use winapi::shared::minwindef::{LPARAM, LRESULT, UINT, WPARAM}; |
| 8 | +use winapi::um::libloaderapi::GetModuleHandleW; |
| 9 | +use winapi::um::winuser::{ |
| 10 | + DefWindowProcW, DispatchMessageW, GetMessageW, GetWindowLongPtrW, PostQuitMessage, |
| 11 | + SetWindowLongPtrW, TranslateMessage, GWLP_USERDATA, MSG, WM_CREATE, WM_DESTROY, |
| 12 | + WM_DEVICECHANGE, |
| 13 | +}; |
| 14 | +use winapi::{ |
| 15 | + shared::{ |
| 16 | + ntdef::LPCWSTR, |
| 17 | + windef::{HBRUSH, HCURSOR, HICON, HWND}, |
| 18 | + }, |
| 19 | + um::winuser::{CreateWindowExW, RegisterClassW, WNDCLASSW}, |
| 20 | +}; |
| 21 | + |
| 22 | +pub enum PnPDetectorEvent { |
| 23 | + Plug { device_ref: PnPDetectorDevice }, |
| 24 | + Unplug { device_ref: PnPDetectorDevice }, |
| 25 | +} |
| 26 | + |
| 27 | +#[derive(PartialEq, Clone)] |
| 28 | +pub struct PnPDetectorDevice { |
| 29 | + pub vid: u16, |
| 30 | + pub pid: u16, |
| 31 | +} |
| 32 | + |
| 33 | +pub struct PnPDetector { |
| 34 | + hwnd: HWND, |
| 35 | + hidapi: HidApi, |
| 36 | + tx: UnboundedSender<PnPDetectorEvent>, |
| 37 | + known_devices: Vec<PnPDetectorDevice>, |
| 38 | +} |
| 39 | + |
| 40 | +impl PnPDetector { |
| 41 | + pub fn start() -> UnboundedReceiver<PnPDetectorEvent> { |
| 42 | + let (tx, rx) = unbounded_channel::<PnPDetectorEvent>(); |
| 43 | + tokio::task::spawn_blocking(move || { |
| 44 | + let hidapi = match HidApi::new() { |
| 45 | + Ok(a) => a, |
| 46 | + Err(e) => { |
| 47 | + error!("[Core] Failed to initialize HIDAPI: {}", e); |
| 48 | + return; |
| 49 | + } |
| 50 | + }; |
| 51 | + let mut detector = Self { |
| 52 | + hwnd: std::ptr::null_mut(), |
| 53 | + hidapi, |
| 54 | + tx, |
| 55 | + known_devices: Vec::new(), |
| 56 | + }; |
| 57 | + detector.create_window(); |
| 58 | + detector.list_devices(false); |
| 59 | + detector.detect(); |
| 60 | + }); |
| 61 | + rx |
| 62 | + } |
| 63 | + |
| 64 | + fn handle_hotplug_event(&mut self) { |
| 65 | + self.list_devices(true); |
| 66 | + } |
| 67 | + |
| 68 | + fn list_devices(&mut self, emit_events: bool) { |
| 69 | + let _ = self.hidapi.refresh_devices(); |
| 70 | + // Check for added devices |
| 71 | + let devices = self.hidapi.device_list(); |
| 72 | + for device_info in devices { |
| 73 | + // Check if device already in known devices |
| 74 | + let device = PnPDetectorDevice { |
| 75 | + vid: device_info.vendor_id(), |
| 76 | + pid: device_info.product_id(), |
| 77 | + }; |
| 78 | + if self.known_devices.contains(&device) { |
| 79 | + continue; |
| 80 | + } |
| 81 | + // Add device to known devices |
| 82 | + self.known_devices.push(device.clone()); |
| 83 | + // Emit event |
| 84 | + if emit_events { |
| 85 | + self.tx |
| 86 | + .send(PnPDetectorEvent::Plug { |
| 87 | + device_ref: device.clone(), |
| 88 | + }) |
| 89 | + .unwrap(); |
| 90 | + } |
| 91 | + } |
| 92 | + // Check for removed devices |
| 93 | + let mut removed_devices = Vec::new(); |
| 94 | + for known_device in &self.known_devices { |
| 95 | + let mut found = false; |
| 96 | + let devices = self.hidapi.device_list(); |
| 97 | + for device_info in devices { |
| 98 | + let device = PnPDetectorDevice { |
| 99 | + vid: device_info.vendor_id(), |
| 100 | + pid: device_info.product_id(), |
| 101 | + }; |
| 102 | + if known_device == &device { |
| 103 | + found = true; |
| 104 | + break; |
| 105 | + } |
| 106 | + } |
| 107 | + if !found { |
| 108 | + removed_devices.push(known_device.clone()); |
| 109 | + } |
| 110 | + } |
| 111 | + for removed_device in removed_devices { |
| 112 | + self.known_devices.retain(|d| d != &removed_device); |
| 113 | + // Emit event |
| 114 | + if emit_events { |
| 115 | + self.tx |
| 116 | + .send(PnPDetectorEvent::Unplug { |
| 117 | + device_ref: removed_device, |
| 118 | + }) |
| 119 | + .unwrap(); |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + /// Detect USB events: just run a Windows event loop |
| 125 | + fn detect(&self) { |
| 126 | + unsafe { |
| 127 | + let mut msg: MSG = std::mem::MaybeUninit::zeroed().assume_init(); |
| 128 | + loop { |
| 129 | + let val = GetMessageW(&mut msg, self.hwnd, 0, 0); |
| 130 | + if val == 0 { |
| 131 | + break; |
| 132 | + } else { |
| 133 | + TranslateMessage(&msg); |
| 134 | + DispatchMessageW(&msg); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + /// Window procedure function to handle events |
| 141 | + pub unsafe extern "system" fn window_proc( |
| 142 | + hwnd: HWND, |
| 143 | + msg: UINT, |
| 144 | + wparam: WPARAM, |
| 145 | + lparam: LPARAM, |
| 146 | + ) -> LRESULT { |
| 147 | + match msg { |
| 148 | + WM_CREATE => { |
| 149 | + let create_struct = lparam as *mut winapi::um::winuser::CREATESTRUCTW; |
| 150 | + let window_state_ptr = create_struct.as_ref().unwrap().lpCreateParams; |
| 151 | + SetWindowLongPtrW(hwnd, GWLP_USERDATA, window_state_ptr as isize); |
| 152 | + } |
| 153 | + WM_DESTROY => { |
| 154 | + PostQuitMessage(0); |
| 155 | + } |
| 156 | + WM_DEVICECHANGE => { |
| 157 | + let self_ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA); |
| 158 | + let window_state: &mut Self = &mut *(self_ptr as *mut Self); |
| 159 | + window_state.handle_hotplug_event(); |
| 160 | + } |
| 161 | + _ => return DefWindowProcW(hwnd, msg, wparam, lparam), |
| 162 | + } |
| 163 | + return 0; |
| 164 | + } |
| 165 | + |
| 166 | + /// Create an invisible window to handle WM_DEVICECHANGE message |
| 167 | + fn create_window(&mut self) { |
| 168 | + let winapi_class_name: Vec<u16> = OsStr::new("OyasumiVRPnPDetectWindowClass") |
| 169 | + .encode_wide() |
| 170 | + .chain(once(0)) |
| 171 | + .collect(); |
| 172 | + let hinstance = unsafe { GetModuleHandleW(std::ptr::null()) }; |
| 173 | + |
| 174 | + let wc = WNDCLASSW { |
| 175 | + style: 0, |
| 176 | + lpfnWndProc: Some(Self::window_proc), |
| 177 | + cbClsExtra: 0, |
| 178 | + cbWndExtra: 0, |
| 179 | + hInstance: hinstance, |
| 180 | + hIcon: 0 as HICON, |
| 181 | + hCursor: 0 as HCURSOR, |
| 182 | + hbrBackground: 0 as HBRUSH, |
| 183 | + lpszMenuName: 0 as LPCWSTR, |
| 184 | + lpszClassName: winapi_class_name.as_ptr(), |
| 185 | + }; |
| 186 | + |
| 187 | + let error_code = unsafe { RegisterClassW(&wc) }; |
| 188 | + assert_ne!(error_code, 0, "failed to register the window class"); |
| 189 | + |
| 190 | + let window_name: Vec<u16> = OsStr::new("OyasumiVRPnPDetectWindow") |
| 191 | + .encode_wide() |
| 192 | + .chain(once(0)) |
| 193 | + .collect(); |
| 194 | + |
| 195 | + let hwnd = unsafe { |
| 196 | + CreateWindowExW( |
| 197 | + 0, |
| 198 | + winapi_class_name.as_ptr(), |
| 199 | + window_name.as_ptr(), |
| 200 | + 0, |
| 201 | + 0, |
| 202 | + 0, |
| 203 | + 0, |
| 204 | + 0, |
| 205 | + std::ptr::null_mut(), |
| 206 | + std::ptr::null_mut(), |
| 207 | + hinstance, |
| 208 | + self as *mut _ as *mut _, |
| 209 | + ) |
| 210 | + }; |
| 211 | + |
| 212 | + if hwnd.is_null() { |
| 213 | + panic!("Something went wrong while creating a window"); |
| 214 | + } |
| 215 | + self.hwnd = hwnd; |
| 216 | + } |
| 217 | +} |
0 commit comments