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::core::BOOL; use windows::Win32::Foundation::{HWND, LPARAM, POINT, RECT}; use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; use windows::Win32::UI::WindowsAndMessaging::{ EnumWindows, GetClassNameW, GetCursorPos, GetWindowLongW, GetWindowRect, IsIconic, IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW, }; /// Resolve the visible frame of a window: the DWM extended frame when the /// compositor reports one, otherwise the raw window rect. /// /// # Safety /// /// The caller must pass a live `HWND`. unsafe fn visible_window_rect(hwnd: HWND) -> Option { let mut rect = RECT::default(); // SAFETY: `rect` is a live RECT local and the size argument matches it. let r = unsafe { DwmGetWindowAttribute( hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, (&raw mut rect).cast::(), u32::try_from(size_of::()).unwrap_or(0), ) }; if r.is_ok() && rect.right > rect.left && rect.bottom > rect.top { return Some(rect); } let mut fallback = RECT::default(); // SAFETY: `fallback` is a live RECT local that the call writes through. if unsafe { GetWindowRect(hwnd, &raw mut fallback) }.is_ok() { Some(fallback) } else { None } } const VK_LBUTTON: i32 = 0x01; const VK_ESCAPE: i32 = 0x1B; #[derive(Serialize, Clone)] pub(crate) struct Rect { pub x: i32, pub y: i32, pub width: u32, pub height: u32, } pub struct PickerSession { running: Arc, handle: Option>, } struct EnumCtx { point: POINT, exclude: Vec, found: Option<(isize, RECT)>, } const SHELL_CLASSES: &[&str] = &[ "Progman", "WorkerW", "Shell_TrayWnd", "Shell_SecondaryTrayWnd", "TrayNotifyWnd", "Button", "DV2ControlHost", "MultitaskingViewFrame", "ForegroundStaging", "Windows.UI.Core.CoreWindow", ]; /// Read a window's class name into a fixed buffer. /// /// # Safety /// /// The caller must pass a live `HWND`. unsafe fn class_of(hwnd: HWND) -> String { let mut buf = [0u16; 128]; // SAFETY: GetClassNameW writes at most buf.len() UTF-16 units into `buf`; // it returns the count written, which is bounds-checked before slicing. let n = unsafe { GetClassNameW(hwnd, &mut buf) }; if n <= 0 { return String::new(); } // n is a positive count of UTF-16 units written by the call above; getting // it wrong means an empty class name, never a panic. let written = usize::try_from(n).ok().and_then(|n| buf.get(..n)); String::from_utf16_lossy(written.unwrap_or_default()) } /// `EnumWindows` callback: records the first top-level window containing the /// target point. Returning FALSE stops the enumeration. /// /// # Safety /// /// `EnumWindows` hands back the `LPARAM` that `top_window_at` passed in, which /// is a live `*mut EnumCtx` for the duration of the enumeration. unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL { // SAFETY: `lparam` is the pointer passed to EnumWindows by top_window_at, // and that EnumCtx outlives the call. let ctx = unsafe { &mut *(lparam.0 as *mut EnumCtx) }; if ctx.found.is_some() { return BOOL(1); } let id = hwnd.0 as isize; if ctx.exclude.contains(&id) { return BOOL(1); } // The checks below are all read-only queries against the window handle // EnumWindows just handed us, so it is live for this call. // // SAFETY: `hwnd` is a live top-level window handle. if !unsafe { IsWindowVisible(hwnd) }.as_bool() { return BOOL(1); } // SAFETY: same live handle. if unsafe { IsIconic(hwnd) }.as_bool() { return BOOL(1); } // SAFETY: same live handle; GWL_EXSTYLE reads a window style word. let ex = unsafe { GetWindowLongW(hwnd, GWL_EXSTYLE) }.cast_unsigned(); if (ex & WS_EX_TOOLWINDOW.0) != 0 { return BOOL(1); } // SAFETY: `hwnd` is the live handle described above. let class_name = unsafe { class_of(hwnd) }; if SHELL_CLASSES.iter().any(|c| class_name == *c) { return BOOL(1); } // SAFETY: `hwnd` is the live handle described above. let Some(rect) = (unsafe { visible_window_rect(hwnd) }) else { return BOOL(1); }; if ctx.point.x < rect.left || ctx.point.x >= rect.right || ctx.point.y < rect.top || ctx.point.y >= rect.bottom { return BOOL(1); } let w = rect.right - rect.left; let h = rect.bottom - rect.top; if w < 40 || h < 40 { return BOOL(1); } ctx.found = Some((id, rect)); BOOL(0) } fn top_window_at(pt: POINT, exclude: &[isize]) -> Option<(isize, RECT)> { let mut ctx = EnumCtx { point: pt, exclude: exclude.to_vec(), found: None, }; // SAFETY: `ctx` is a live local of exactly the type enum_at_point expects, // and it outlives the call because EnumWindows runs to completion here. unsafe { drop(EnumWindows( Some(enum_at_point), LPARAM((&raw mut ctx).cast::() as isize), )); } ctx.found } pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> 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 = true; loop { if !running_clone.load(Ordering::Relaxed) { break; } let mut pt = POINT::default(); // SAFETY: `pt` is a live local that GetCursorPos writes through. if unsafe { GetCursorPos(&raw mut pt) }.is_err() { thread::sleep(Duration::from_millis(30)); continue; } let target = top_window_at(pt, &exclude_hwnds); if let Some((id, rect)) = target { if id != last_hwnd { // SAFETY: `id` came from EnumWindows, so it is a live HWND. let class = unsafe { class_of(HWND(id as *mut std::ffi::c_void)) }; tracing::info!( "picker hover: hwnd={:x} class={} rect=({},{}) {}x{}", id, class, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top ); drop(app.emit( "picker-hover", Rect { x: rect.left, y: rect.top, width: (rect.right - rect.left).max(0).cast_unsigned(), height: (rect.bottom - rect.top).max(0).cast_unsigned(), }, )); last_hwnd = id; } } else if last_hwnd != 0 { tracing::info!("picker hover: no target found at ({}, {})", pt.x, pt.y); last_hwnd = 0; } else { // Still hovering the same window, so the frame is already drawn. } let pressed = // SAFETY: a self-contained query with no pointer arguments. unsafe { (GetAsyncKeyState(VK_LBUTTON).cast_unsigned() & 0x8000) != 0 }; if pressed && !last_pressed { if let Some((_, rect)) = target { drop(app.emit( "picker-pick", Rect { x: rect.left, y: rect.top, width: (rect.right - rect.left).max(0).cast_unsigned(), height: (rect.bottom - rect.top).max(0).cast_unsigned(), }, )); break; } } last_pressed = pressed; let esc = // SAFETY: a self-contained query with no pointer arguments. unsafe { (GetAsyncKeyState(VK_ESCAPE).cast_unsigned() & 0x8000) != 0 }; if esc && !last_esc { drop(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() { drop(h.join()); } } }