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 struct Click { pub time_secs: f64, pub x: i32, pub y: i32, } pub struct ClickRecorder { running: Arc, thread: Option>, clicks: Arc>>, } pub 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; let start = Instant::now(); let mut last_pressed = false; while running_clone.load(Ordering::Relaxed) { let state = unsafe { GetAsyncKeyState(VK_LBUTTON) }; let pressed = (state as u16 & 0x8000) != 0; if pressed && !last_pressed { let mut pt = POINT::default(); if unsafe { GetCursorPos(&mut pt) }.is_ok() { let click = Click { time_secs: start.elapsed().as_secs_f64(), x: pt.x, y: pt.y, }; if let Ok(mut v) = clicks_clone.lock() { v.push(click); } } } last_pressed = 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() { let _ = t.join(); } self.clicks .lock() .map(|v| v.clone()) .unwrap_or_default() } }