From 5eb27ab77962c0316f8df8c379ec448e8fb486ae Mon Sep 17 00:00:00 2001 From: lashman Date: Tue, 12 May 2026 13:07:35 +0300 Subject: [PATCH] visual picker: marching ants, DWM-aware overlay sizing --- src-tauri/Cargo.toml | 2 +- src-tauri/capabilities/default.json | 2 +- src-tauri/src/lib.rs | 148 +++++++++++++++++++++++--- src-tauri/src/window_picker.rs | 155 +++++++++++++++++++++++----- src/lib/Picker.svelte | 45 ++++++-- 5 files changed, 301 insertions(+), 51 deletions(-) diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 77c1380..2338855 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -18,7 +18,7 @@ tauri = { version = "2.11", features = ["protocol-asset"] } tauri-plugin-dialog = "2" tauri-plugin-global-shortcut = "2" windows-capture = "2.0" -windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_Foundation"] } +windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_Foundation", "Win32_Graphics_Dwm"] } cpal = "0.16" tokio = { version = "1.47", features = ["full"] } serde = { version = "1.0", features = ["derive"] } diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 3fd530d..db3f322 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -2,7 +2,7 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "default capabilities for ByteSize", - "windows": ["main", "overlay"], + "windows": ["main", "overlay", "picker"], "permissions": [ "core:default", "core:window:default", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d2f682e..aa0a585 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -798,6 +798,12 @@ fn open_window_picker( } } } + tracing::info!( + "open_window_picker: monitor={}x{} exclude={:?}", + mw, + mh, + exclude + ); let picker = app .get_webview_window("picker") @@ -812,6 +818,28 @@ fn open_window_picker( let _ = picker.set_ignore_cursor_events(true); let _ = picker.set_always_on_top(true); picker.show().map_err(|e| e.to_string())?; + if let Ok(h) = picker.hwnd() { + use windows::Win32::Foundation::{HWND, RECT}; + use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; + use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; + let hwnd = HWND(h.0 as *mut _); + let mut gr = RECT::default(); + let _ = unsafe { GetWindowRect(hwnd, &mut gr) }; + let mut dr = RECT::default(); + let _ = unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + &mut dr as *mut RECT as *mut std::ffi::c_void, + std::mem::size_of::() as u32, + ) + }; + tracing::info!( + "picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})", + gr.left, gr.top, gr.right, gr.bottom, + dr.left, dr.top, dr.right, dr.bottom + ); + } { let mut slot = state.picker.lock().expect("picker mutex"); @@ -837,6 +865,36 @@ fn close_window_picker( Ok(()) } +fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) { + use windows::Win32::Foundation::{HWND, RECT}; + use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; + use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; + + let hwnd = HWND(hwnd_raw as *mut _); + let mut outer = RECT::default(); + if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() { + return (0, 0, 0, 0); + } + let mut dwm = RECT::default(); + let r = unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + &mut dwm as *mut RECT as *mut std::ffi::c_void, + std::mem::size_of::() as u32, + ) + }; + if r.is_err() || dwm.right <= dwm.left || dwm.bottom <= dwm.top { + return (0, 0, 0, 0); + } + ( + dwm.left - outer.left, + dwm.top - outer.top, + outer.right - dwm.right, + outer.bottom - dwm.bottom, + ) +} + #[tauri::command] fn set_overlay_to_window( app: AppHandle, @@ -845,7 +903,6 @@ fn set_overlay_to_window( width: u32, height: u32, ) -> Result<(), String> { - use tauri::{PhysicalPosition, PhysicalSize, Position, Size}; let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; @@ -853,41 +910,100 @@ fn set_overlay_to_window( let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; - let outer_x = x - border_phys; - let outer_y = y - border_phys - titlebar_phys; - let outer_w = (width as i32 + border_phys * 2).max(2) as u32; - let outer_h = (height as i32 + border_phys * 2 + titlebar_phys).max(2) as u32; + // Desired visible bounds of the overlay window (the green frame). + // The capture region is inside the border + below the titlebar. + let visible_left = x - border_phys; + let visible_top = y - border_phys - titlebar_phys; + let visible_w = width as i32 + border_phys * 2; + let visible_h = height as i32 + border_phys * 2 + titlebar_phys; - win.set_position(Position::Physical(PhysicalPosition::new(outer_x, outer_y))) - .map_err(|e| e.to_string())?; - win.set_size(Size::Physical(PhysicalSize::new(outer_w, outer_h))) - .map_err(|e| e.to_string()) + // Compensate for the invisible DWM border that Windows adds around + // top-level windows (Tauri's set_position sets the outer rect, but the + // visible content sits inside the DWM inset). + let (li, ti, ri, bi) = win + .hwnd() + .map(|h| dwm_insets(h.0 as isize)) + .unwrap_or((0, 0, 0, 0)); + + let outer_x = visible_left - li; + let outer_y = visible_top - ti; + let outer_w = (visible_w + li + ri).max(2) as u32; + let outer_h = (visible_h + ti + bi).max(2) as u32; + + // Bypass Tauri's set_position/set_size which adds extra pixels for + // some unknown reason. Use Win32 SetWindowPos with explicit outer rect. + let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; + use windows::Win32::Foundation::HWND; + use windows::Win32::UI::WindowsAndMessaging::{ + SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER, + }; + let hwnd = HWND(raw.0 as *mut _); + unsafe { + SetWindowPos( + hwnd, + Some(HWND_TOP), + outer_x, + outer_y, + outer_w as i32, + outer_h as i32, + SWP_NOACTIVATE | SWP_NOZORDER, + ) + } + .map_err(|e| format!("SetWindowPos: {e}"))?; + + let _ = (visible_left, visible_top, visible_w, visible_h, scale, border_phys, titlebar_phys); + Ok(()) } #[tauri::command] fn get_overlay_rect(app: AppHandle) -> Result { + use windows::Win32::Foundation::{HWND, RECT}; + use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; + use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; + let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; - let pos = win.outer_position().map_err(|e| e.to_string())?; - let size = win.outer_size().map_err(|e| e.to_string())?; let scale = win.scale_factor().map_err(|e| e.to_string())?; + let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; + let hwnd = HWND(raw.0 as *mut _); + + let mut dwm = RECT::default(); + let dwm_ok = unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + &mut dwm as *mut RECT as *mut std::ffi::c_void, + std::mem::size_of::() as u32, + ) + } + .is_ok(); + let visible = if dwm_ok && dwm.right > dwm.left && dwm.bottom > dwm.top { + dwm + } else { + let mut r = RECT::default(); + unsafe { GetWindowRect(hwnd, &mut r) } + .map_err(|e| format!("GetWindowRect: {e}"))?; + r + }; let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let inset_top = border_phys + titlebar_phys; let inset_sides = border_phys; - let inset_bottom = border_phys; - let width = (size.width as i32 - inset_sides * 2).max(2) as u32; - let height = (size.height as i32 - inset_top - inset_bottom).max(2) as u32; + let visible_w = visible.right - visible.left; + let visible_h = visible.bottom - visible.top; + + let width = (visible_w - inset_sides * 2).max(2) as u32; + let height = (visible_h - inset_top - inset_sides).max(2) as u32; let width = (width / 2) * 2; let height = (height / 2) * 2; Ok(CaptureRect { - x: pos.x + inset_sides, - y: pos.y + inset_top, + x: visible.left + inset_sides, + y: visible.top + inset_top, width, height, }) diff --git a/src-tauri/src/window_picker.rs b/src-tauri/src/window_picker.rs index f406ca5..2fc1a69 100644 --- a/src-tauri/src/window_picker.rs +++ b/src-tauri/src/window_picker.rs @@ -5,12 +5,34 @@ use std::time::Duration; use serde::Serialize; use tauri::{AppHandle, Emitter}; -use windows::Win32::Foundation::{HWND, POINT, RECT}; +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::{ - GetAncestor, GetCursorPos, GetWindowRect, IsIconic, IsWindowVisible, WindowFromPoint, GA_ROOT, + EnumWindows, GetClassNameW, GetCursorPos, GetWindowLongW, GetWindowRect, IsIconic, + IsWindowVisible, GWL_EXSTYLE, WS_EX_TOOLWINDOW, }; +unsafe fn visible_window_rect(hwnd: HWND) -> Option { + 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::() 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; @@ -27,13 +49,99 @@ pub struct PickerSession { 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", +]; + +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) -> 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; + let mut last_esc = true; loop { if !running_clone.load(Ordering::Relaxed) { @@ -46,22 +154,20 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession { continue; } - let hwnd = unsafe { WindowFromPoint(pt) }; - let top = unsafe { GetAncestor(hwnd, GA_ROOT) }; - let top_id = top.0 as isize; + let target = top_window_at(pt, &exclude_hwnds); - 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() { + 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 { @@ -71,16 +177,17 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession { height: (rect.bottom - rect.top).max(0) as u32, }, ); + last_hwnd = id; } - last_hwnd = top_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 && last_hwnd != 0 { - let target = HWND(last_hwnd as *mut _); - let mut rect = RECT::default(); - if unsafe { GetWindowRect(target, &mut rect) }.is_ok() { + if pressed && !last_pressed { + if let Some((_, rect)) = target { let _ = app.emit( "picker-pick", Rect { @@ -90,8 +197,8 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession { height: (rect.bottom - rect.top).max(0) as u32, }, ); + break; } - break; } last_pressed = pressed; diff --git a/src/lib/Picker.svelte b/src/lib/Picker.svelte index 53e99e9..1f52a4c 100644 --- a/src/lib/Picker.svelte +++ b/src/lib/Picker.svelte @@ -14,17 +14,28 @@ let scale: number = $state(1) let originX: number = $state(0) let originY: number = $state(0) + let dpr: number = $state(1) + let innerW: number = $state(0) + let innerH: number = $state(0) onMount(() => { const win = getCurrentWebviewWindow() let unlistenHover: (() => void) | null = null + let unlistenMoved: (() => void) | null = null - void (async () => { + const refreshOrigin = async () => { scale = await win.scaleFactor() - const pos = await win.outerPosition() + const pos = await win.innerPosition() originX = pos.x originY = pos.y + dpr = window.devicePixelRatio + innerW = window.innerWidth + innerH = window.innerHeight + } + void (async () => { + await refreshOrigin() + unlistenMoved = await win.onMoved(refreshOrigin) unlistenHover = await listen("picker-hover", (e) => { hover = e.payload }) @@ -32,6 +43,7 @@ return () => { unlistenHover?.() + unlistenMoved?.() } }) @@ -52,7 +64,14 @@
{hover.width} x {hover.height}
{/if} -
click a window to snap. Esc to cancel.
+
+ origin=({originX},{originY}) scale={scale} dpr={dpr} inner={innerW}x{innerH} ยท + {#if hover} + hover {hover.width}x{hover.height} @ ({hover.x},{hover.y}) + {:else} + move mouse over a window. Esc to cancel. + {/if} +