visual picker: marching ants, DWM-aware overlay sizing

This commit is contained in:
2026-05-12 13:07:35 +03:00
parent 509017d56b
commit 5eb27ab779
5 changed files with 301 additions and 51 deletions
+1 -1
View File
@@ -18,7 +18,7 @@ tauri = { version = "2.11", features = ["protocol-asset"] }
tauri-plugin-dialog = "2" tauri-plugin-dialog = "2"
tauri-plugin-global-shortcut = "2" tauri-plugin-global-shortcut = "2"
windows-capture = "2.0" 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" cpal = "0.16"
tokio = { version = "1.47", features = ["full"] } tokio = { version = "1.47", features = ["full"] }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "default capabilities for ByteSize", "description": "default capabilities for ByteSize",
"windows": ["main", "overlay"], "windows": ["main", "overlay", "picker"],
"permissions": [ "permissions": [
"core:default", "core:default",
"core:window:default", "core:window:default",
+132 -16
View File
@@ -798,6 +798,12 @@ fn open_window_picker(
} }
} }
} }
tracing::info!(
"open_window_picker: monitor={}x{} exclude={:?}",
mw,
mh,
exclude
);
let picker = app let picker = app
.get_webview_window("picker") .get_webview_window("picker")
@@ -812,6 +818,28 @@ fn open_window_picker(
let _ = picker.set_ignore_cursor_events(true); let _ = picker.set_ignore_cursor_events(true);
let _ = picker.set_always_on_top(true); let _ = picker.set_always_on_top(true);
picker.show().map_err(|e| e.to_string())?; 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::<RECT>() 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"); let mut slot = state.picker.lock().expect("picker mutex");
@@ -837,6 +865,36 @@ fn close_window_picker(
Ok(()) 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::<RECT>() 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] #[tauri::command]
fn set_overlay_to_window( fn set_overlay_to_window(
app: AppHandle, app: AppHandle,
@@ -845,7 +903,6 @@ fn set_overlay_to_window(
width: u32, width: u32,
height: u32, height: u32,
) -> Result<(), String> { ) -> Result<(), String> {
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
let win = app let win = app
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .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 border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
let outer_x = x - border_phys; // Desired visible bounds of the overlay window (the green frame).
let outer_y = y - border_phys - titlebar_phys; // The capture region is inside the border + below the titlebar.
let outer_w = (width as i32 + border_phys * 2).max(2) as u32; let visible_left = x - border_phys;
let outer_h = (height as i32 + border_phys * 2 + titlebar_phys).max(2) as u32; 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))) // Compensate for the invisible DWM border that Windows adds around
.map_err(|e| e.to_string())?; // top-level windows (Tauri's set_position sets the outer rect, but the
win.set_size(Size::Physical(PhysicalSize::new(outer_w, outer_h))) // visible content sits inside the DWM inset).
.map_err(|e| e.to_string()) 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] #[tauri::command]
fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> { fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
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 let win = app
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .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 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::<RECT>() 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 border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_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_top = border_phys + titlebar_phys;
let inset_sides = border_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 visible_w = visible.right - visible.left;
let height = (size.height as i32 - inset_top - inset_bottom).max(2) as u32; 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 width = (width / 2) * 2;
let height = (height / 2) * 2; let height = (height / 2) * 2;
Ok(CaptureRect { Ok(CaptureRect {
x: pos.x + inset_sides, x: visible.left + inset_sides,
y: pos.y + inset_top, y: visible.top + inset_top,
width, width,
height, height,
}) })
+131 -24
View File
@@ -5,12 +5,34 @@ use std::time::Duration;
use serde::Serialize; use serde::Serialize;
use tauri::{AppHandle, Emitter}; 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::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::WindowsAndMessaging::{ 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<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_LBUTTON: i32 = 0x01;
const VK_ESCAPE: i32 = 0x1B; const VK_ESCAPE: i32 = 0x1B;
@@ -27,13 +49,99 @@ pub struct PickerSession {
handle: Option<std::thread::JoinHandle<()>>, 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 { pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
let running = Arc::new(AtomicBool::new(true)); let running = Arc::new(AtomicBool::new(true));
let running_clone = running.clone(); let running_clone = running.clone();
let handle = thread::spawn(move || { let handle = thread::spawn(move || {
let mut last_hwnd: isize = 0; let mut last_hwnd: isize = 0;
let mut last_pressed = true; let mut last_pressed = true;
let mut last_esc = false; let mut last_esc = true;
loop { loop {
if !running_clone.load(Ordering::Relaxed) { if !running_clone.load(Ordering::Relaxed) {
@@ -46,22 +154,20 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
continue; continue;
} }
let hwnd = unsafe { WindowFromPoint(pt) }; let target = top_window_at(pt, &exclude_hwnds);
let top = unsafe { GetAncestor(hwnd, GA_ROOT) };
let top_id = top.0 as isize;
if top_id == 0 if let Some((id, rect)) = target {
|| exclude_hwnds.contains(&top_id) if id != last_hwnd {
|| unsafe { !IsWindowVisible(top).as_bool() } let class = unsafe { class_of(HWND(id as *mut _)) };
|| unsafe { IsIconic(top).as_bool() } tracing::info!(
{ "picker hover: hwnd={:x} class={} rect=({},{}) {}x{}",
thread::sleep(Duration::from_millis(30)); id,
continue; class,
} rect.left,
rect.top,
if top_id != last_hwnd { rect.right - rect.left,
let mut rect = RECT::default(); rect.bottom - rect.top
if unsafe { GetWindowRect(top, &mut rect) }.is_ok() { );
let _ = app.emit( let _ = app.emit(
"picker-hover", "picker-hover",
Rect { Rect {
@@ -71,16 +177,17 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
height: (rect.bottom - rect.top).max(0) as u32, 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 = let pressed =
unsafe { (GetAsyncKeyState(VK_LBUTTON) as u16 & 0x8000) != 0 }; unsafe { (GetAsyncKeyState(VK_LBUTTON) as u16 & 0x8000) != 0 };
if pressed && !last_pressed && last_hwnd != 0 { if pressed && !last_pressed {
let target = HWND(last_hwnd as *mut _); if let Some((_, rect)) = target {
let mut rect = RECT::default();
if unsafe { GetWindowRect(target, &mut rect) }.is_ok() {
let _ = app.emit( let _ = app.emit(
"picker-pick", "picker-pick",
Rect { Rect {
@@ -90,8 +197,8 @@ pub fn start(app: AppHandle, exclude_hwnds: Vec<isize>) -> PickerSession {
height: (rect.bottom - rect.top).max(0) as u32, height: (rect.bottom - rect.top).max(0) as u32,
}, },
); );
break;
} }
break;
} }
last_pressed = pressed; last_pressed = pressed;
+36 -9
View File
@@ -14,17 +14,28 @@
let scale: number = $state(1) let scale: number = $state(1)
let originX: number = $state(0) let originX: number = $state(0)
let originY: number = $state(0) let originY: number = $state(0)
let dpr: number = $state(1)
let innerW: number = $state(0)
let innerH: number = $state(0)
onMount(() => { onMount(() => {
const win = getCurrentWebviewWindow() const win = getCurrentWebviewWindow()
let unlistenHover: (() => void) | null = null let unlistenHover: (() => void) | null = null
let unlistenMoved: (() => void) | null = null
void (async () => { const refreshOrigin = async () => {
scale = await win.scaleFactor() scale = await win.scaleFactor()
const pos = await win.outerPosition() const pos = await win.innerPosition()
originX = pos.x originX = pos.x
originY = pos.y originY = pos.y
dpr = window.devicePixelRatio
innerW = window.innerWidth
innerH = window.innerHeight
}
void (async () => {
await refreshOrigin()
unlistenMoved = await win.onMoved(refreshOrigin)
unlistenHover = await listen<Rect>("picker-hover", (e) => { unlistenHover = await listen<Rect>("picker-hover", (e) => {
hover = e.payload hover = e.payload
}) })
@@ -32,6 +43,7 @@
return () => { return () => {
unlistenHover?.() unlistenHover?.()
unlistenMoved?.()
} }
}) })
@@ -52,7 +64,14 @@
<div class="dims">{hover.width} x {hover.height}</div> <div class="dims">{hover.width} x {hover.height}</div>
</div> </div>
{/if} {/if}
<div class="hint">click a window to snap. Esc to cancel.</div> <div class="hint">
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}
</div>
</main> </main>
<style> <style>
@@ -73,18 +92,26 @@
.dim { .dim {
position: absolute; position: absolute;
inset: 0; inset: 0;
background: rgba(10, 14, 12, 0.18); background: rgba(10, 14, 12, 0.15);
} }
.frame { .frame {
position: absolute; position: absolute;
box-sizing: border-box;
border: 2px dashed #4a8;
background: rgba(74, 170, 136, 0.08);
animation: march 0.6s linear infinite;
pointer-events: none; pointer-events: none;
background-color: transparent;
background-image:
linear-gradient(90deg, #4a8 50%, transparent 50%),
linear-gradient(90deg, #4a8 50%, transparent 50%),
linear-gradient(0deg, #4a8 50%, transparent 50%),
linear-gradient(0deg, #4a8 50%, transparent 50%);
background-position: 0 0, 0 100%, 0 0, 100% 0;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-size: 12px 2px, 12px 2px, 2px 12px, 2px 12px;
animation: march 0.4s linear infinite;
} }
@keyframes march { @keyframes march {
to { background-position: 16px 0; } to {
background-position: 12px 0, -12px 100%, 0 -12px, 100% 12px;
}
} }
.dims { .dims {
position: absolute; position: absolute;