visual window picker with marching ants overlay

This commit is contained in:
2026-05-12 02:22:02 +03:00
parent 2904a7ad29
commit 509017d56b
8 changed files with 364 additions and 140 deletions
+123
View File
@@ -0,0 +1,123 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use serde::Serialize;
use tauri::{AppHandle, Emitter};
use windows::Win32::Foundation::{HWND, POINT, RECT};
use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
use windows::Win32::UI::WindowsAndMessaging::{
GetAncestor, GetCursorPos, GetWindowRect, IsIconic, IsWindowVisible, WindowFromPoint, GA_ROOT,
};
const VK_LBUTTON: i32 = 0x01;
const VK_ESCAPE: i32 = 0x1B;
#[derive(Serialize, Clone)]
pub struct Rect {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
}
pub struct PickerSession {
running: Arc<AtomicBool>,
handle: Option<std::thread::JoinHandle<()>>,
}
pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone();
let handle = thread::spawn(move || {
let mut last_hwnd: isize = 0;
let mut last_pressed = true;
let mut last_esc = false;
loop {
if !running_clone.load(Ordering::Relaxed) {
break;
}
let mut pt = POINT::default();
if unsafe { GetCursorPos(&mut pt) }.is_err() {
thread::sleep(Duration::from_millis(30));
continue;
}
let hwnd = unsafe { WindowFromPoint(pt) };
let top = unsafe { GetAncestor(hwnd, GA_ROOT) };
let top_id = top.0 as isize;
if top_id == 0
|| exclude_hwnds.contains(&top_id)
|| unsafe { !IsWindowVisible(top).as_bool() }
|| unsafe { IsIconic(top).as_bool() }
{
thread::sleep(Duration::from_millis(30));
continue;
}
if top_id != last_hwnd {
let mut rect = RECT::default();
if unsafe { GetWindowRect(top, &mut rect) }.is_ok() {
let _ = app.emit(
"picker-hover",
Rect {
x: rect.left,
y: rect.top,
width: (rect.right - rect.left).max(0) as u32,
height: (rect.bottom - rect.top).max(0) as u32,
},
);
}
last_hwnd = top_id;
}
let pressed =
unsafe { (GetAsyncKeyState(VK_LBUTTON) as u16 & 0x8000) != 0 };
if pressed && !last_pressed && last_hwnd != 0 {
let target = HWND(last_hwnd as *mut _);
let mut rect = RECT::default();
if unsafe { GetWindowRect(target, &mut rect) }.is_ok() {
let _ = app.emit(
"picker-pick",
Rect {
x: rect.left,
y: rect.top,
width: (rect.right - rect.left).max(0) as u32,
height: (rect.bottom - rect.top).max(0) as u32,
},
);
}
break;
}
last_pressed = pressed;
let esc =
unsafe { (GetAsyncKeyState(VK_ESCAPE) as u16 & 0x8000) != 0 };
if esc && !last_esc {
let _ = app.emit("picker-cancel", ());
break;
}
last_esc = esc;
thread::sleep(Duration::from_millis(30));
}
});
PickerSession {
running,
handle: Some(handle),
}
}
impl PickerSession {
pub fn stop(mut self) {
self.running.store(false, Ordering::Relaxed);
if let Some(h) = self.handle.take() {
let _ = h.join();
}
}
}