use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use serde::Serialize; #[derive(Debug, Clone, Copy, Serialize)] pub enum MouseButton { Left, Right, Middle, } #[derive(Debug, Clone, Copy, Serialize)] pub struct Click { pub time_secs: f64, pub x: i32, pub y: i32, pub button: MouseButton, } pub struct ClickRecorder { running: Arc, thread: Option>, clicks: Arc>>, } pub(crate) fn start() -> ClickRecorder { let running = Arc::new(AtomicBool::new(true)); let clicks: Arc>> = Arc::new(Mutex::new(Vec::new())); let running_clone = running.clone(); let clicks_clone = clicks.clone(); let thread = thread::spawn(move || { use windows::Win32::Foundation::POINT; use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; use windows::Win32::UI::WindowsAndMessaging::GetCursorPos; const VK_LBUTTON: i32 = 0x01; const VK_RBUTTON: i32 = 0x02; const VK_MBUTTON: i32 = 0x04; let buttons = [ (VK_LBUTTON, MouseButton::Left), (VK_RBUTTON, MouseButton::Right), (VK_MBUTTON, MouseButton::Middle), ]; let start = Instant::now(); let mut last_pressed = [false; 3]; while running_clone.load(Ordering::Relaxed) { for (i, &(vk, button)) in buttons.iter().enumerate() { // SAFETY: both calls are self-contained Win32 queries. `pt` is // a local that GetCursorPos writes, and it is only read after // the call reports success. let state = unsafe { GetAsyncKeyState(vk) }; let pressed = (state.cast_unsigned() & 0x8000) != 0; if pressed && !last_pressed[i] { let mut pt = POINT::default(); // SAFETY: `pt` is a live local the call writes through. if unsafe { GetCursorPos(&raw mut pt) }.is_ok() { let click = Click { time_secs: start.elapsed().as_secs_f64(), x: pt.x, y: pt.y, button, }; if let Ok(mut v) = clicks_clone.lock() { v.push(click); } } } last_pressed[i] = pressed; } thread::sleep(Duration::from_millis(5)); } }); ClickRecorder { running, thread: Some(thread), clicks, } } impl ClickRecorder { pub fn stop(mut self) -> Vec { self.running.store(false, Ordering::Relaxed); if let Some(t) = self.thread.take() { drop(t.join()); } self.clicks .lock() .map(|v| v.clone()) .unwrap_or_default() } }