Files
bytesize/src-tauri/src/window_picker.rs
T

231 lines
6.4 KiB
Rust

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,
};
unsafe fn visible_window_rect(hwnd: HWND) -> Option<RECT> {
let mut rect = RECT::default();
let r = DwmGetWindowAttribute(
hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut rect as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32,
);
if r.is_ok() && rect.right > rect.left && rect.bottom > rect.top {
return Some(rect);
}
let mut fallback = RECT::default();
if GetWindowRect(hwnd, &mut fallback).is_ok() {
Some(fallback)
} else {
None
}
}
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<()>>,
}
struct EnumCtx {
point: POINT,
exclude: Vec<isize>,
found: Option<(isize, RECT)>,
}
const SHELL_CLASSES: &[&str] = &[
"Progman",
"WorkerW",
"Shell_TrayWnd",
"Shell_SecondaryTrayWnd",
"TrayNotifyWnd",
"Button",
"DV2ControlHost",
"MultitaskingViewFrame",
"ForegroundStaging",
"Windows.UI.Core.CoreWindow",
];
unsafe fn class_of(hwnd: HWND) -> String {
let mut buf = [0u16; 128];
let n = GetClassNameW(hwnd, &mut buf);
if n <= 0 {
return String::new();
}
String::from_utf16_lossy(&buf[..n as usize])
}
unsafe extern "system" fn enum_at_point(hwnd: HWND, lparam: LPARAM) -> BOOL {
let ctx = &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);
}
if !IsWindowVisible(hwnd).as_bool() {
return BOOL(1);
}
if IsIconic(hwnd).as_bool() {
return BOOL(1);
}
let ex = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;
if (ex & WS_EX_TOOLWINDOW.0) != 0 {
return BOOL(1);
}
let class_name = class_of(hwnd);
if SHELL_CLASSES.iter().any(|c| class_name == *c) {
return BOOL(1);
}
let rect = match visible_window_rect(hwnd) {
Some(r) => r,
None => 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,
};
unsafe {
let _ = EnumWindows(
Some(enum_at_point),
LPARAM(&mut ctx as *mut EnumCtx as isize),
);
}
ctx.found
}
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 = true;
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 target = top_window_at(pt, &exclude_hwnds);
if let Some((id, rect)) = target {
if id != last_hwnd {
let class = unsafe { class_of(HWND(id as *mut _)) };
tracing::info!(
"picker hover: hwnd={:x} class={} rect=({},{}) {}x{}",
id,
class,
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top
);
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 = id;
}
} else if last_hwnd != 0 {
tracing::info!("picker hover: no target found at ({}, {})", pt.x, pt.y);
last_hwnd = 0;
}
let pressed =
unsafe { (GetAsyncKeyState(VK_LBUTTON) as u16 & 0x8000) != 0 };
if pressed && !last_pressed {
if let Some((_, rect)) = target {
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();
}
}
}