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
+12
View File
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ByteSize window picker</title>
</head>
<body>
<div id="picker"></div>
<script type="module" src="/src/picker.ts"></script>
</body>
</html>
+60
View File
@@ -5,6 +5,7 @@ mod clicks;
mod config;
mod encode;
mod updates;
mod window_picker;
mod windows_list;
use std::path::{Path, PathBuf};
@@ -36,6 +37,7 @@ pub struct AppState {
pub click_recorder: Mutex<Option<clicks::ClickRecorder>>,
pub last_clip: Mutex<Option<RecordedClip>>,
pub session: Mutex<Option<SessionState>>,
pub picker: Mutex<Option<window_picker::PickerSession>>,
}
pub struct SessionState {
@@ -780,6 +782,61 @@ fn list_windows() -> Vec<windows_list::WindowInfo> {
windows_list::list_visible_windows()
}
#[tauri::command]
fn open_window_picker(
app: AppHandle,
state: State<'_, AppState>,
) -> Result<(), String> {
let (mw, mh) =
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
let mut exclude: Vec<isize> = Vec::new();
for label in &["main", "overlay", "picker"] {
if let Some(w) = app.get_webview_window(label) {
if let Ok(h) = w.hwnd() {
exclude.push(h.0 as isize);
}
}
}
let picker = app
.get_webview_window("picker")
.ok_or_else(|| "picker window not found".to_string())?;
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
picker
.set_size(Size::Physical(PhysicalSize::new(mw, mh)))
.map_err(|e| e.to_string())?;
picker
.set_position(Position::Physical(PhysicalPosition::new(0, 0)))
.map_err(|e| e.to_string())?;
let _ = picker.set_ignore_cursor_events(true);
let _ = picker.set_always_on_top(true);
picker.show().map_err(|e| e.to_string())?;
{
let mut slot = state.picker.lock().expect("picker mutex");
if let Some(existing) = slot.take() {
existing.stop();
}
*slot = Some(window_picker::start(app.clone(), exclude));
}
Ok(())
}
#[tauri::command]
fn close_window_picker(
app: AppHandle,
state: State<'_, AppState>,
) -> Result<(), String> {
if let Some(session) = state.picker.lock().expect("picker mutex").take() {
session.stop();
}
if let Some(picker) = app.get_webview_window("picker") {
let _ = picker.hide();
}
Ok(())
}
#[tauri::command]
fn set_overlay_to_window(
app: AppHandle,
@@ -1005,6 +1062,7 @@ pub fn run() {
click_recorder: Mutex::new(None),
last_clip: Mutex::new(None),
session: Mutex::new(None),
picker: Mutex::new(None),
};
tauri::Builder::default()
@@ -1102,6 +1160,8 @@ pub fn run() {
set_overlay_size,
set_overlay_to_window,
list_windows,
open_window_picker,
close_window_picker,
get_overlay_rect,
])
.run(tauri::generate_context!())
+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();
}
}
}
+15
View File
@@ -35,6 +35,21 @@
"skipTaskbar": true,
"resizable": true,
"visible": false
},
{
"label": "picker",
"title": "ByteSize window picker",
"url": "picker.html",
"width": 1920,
"height": 1080,
"transparent": true,
"decorations": false,
"alwaysOnTop": true,
"skipTaskbar": true,
"resizable": false,
"visible": false,
"focus": false,
"shadow": false
}
],
"security": {
+33 -139
View File
@@ -4,14 +4,6 @@
import { listen } from "@tauri-apps/api/event"
import { invoke } from "@tauri-apps/api/core"
type WindowInfo = {
title: string
x: number
y: number
width: number
height: number
}
const win = getCurrentWebviewWindow()
let width: number = $state(0)
@@ -20,9 +12,6 @@
let fps: number = $state(30)
let elapsed: number = $state(0)
let timer: number | null = null
let pickerOpen: boolean = $state(false)
let windows: WindowInfo[] = $state([])
let loadingWindows: boolean = $state(false)
onMount(() => {
const updateSize = async () => {
@@ -78,36 +67,46 @@
}
}
async function togglePicker() {
if (pickerOpen) {
pickerOpen = false
return
}
loadingWindows = true
pickerOpen = true
async function openPicker() {
try {
windows = await invoke<WindowInfo[]>("list_windows")
await invoke("open_window_picker")
} catch (e) {
console.error("list_windows", e)
windows = []
} finally {
loadingWindows = false
console.error("open_window_picker", e)
}
}
async function pickWindow(w: WindowInfo) {
onMount(() => {
let unlistenPick: (() => void) | null = null
let unlistenCancel: (() => void) | null = null
void (async () => {
unlistenPick = await listen<{ x: number; y: number; width: number; height: number }>(
"picker-pick",
async (e) => {
try {
await invoke("set_overlay_to_window", {
x: w.x,
y: w.y,
width: w.width,
height: w.height,
await invoke("set_overlay_to_window", e.payload)
} catch (err) {
console.error("set_overlay_to_window", err)
}
try {
await invoke("close_window_picker")
} catch (err) {
console.error("close_window_picker", err)
}
},
)
unlistenCancel = await listen("picker-cancel", async () => {
try {
await invoke("close_window_picker")
} catch (err) {
console.error("close_window_picker", err)
}
})
} catch (e) {
console.error("set_overlay_to_window", e)
}
pickerOpen = false
})()
return () => {
unlistenPick?.()
unlistenCancel?.()
}
})
</script>
<div class="frame">
@@ -121,7 +120,7 @@
<span class="dim" data-tauri-drag-region>{width} x {height}</span>
<button
class="pick-btn"
onclick={togglePicker}
onclick={openPicker}
onmousedown={(e) => e.stopPropagation()}
title="snap to window"
type="button"
@@ -132,31 +131,6 @@
</span>
{/if}
</div>
{#if pickerOpen}
<div class="picker" role="dialog" tabindex="-1" onmousedown={(e) => e.stopPropagation()}>
<div class="picker-head">
<span>pick a window</span>
<button onclick={() => (pickerOpen = false)} type="button">×</button>
</div>
{#if loadingWindows}
<div class="picker-empty">listing...</div>
{:else if windows.length === 0}
<div class="picker-empty">no windows found</div>
{:else}
<ul class="picker-list">
{#each windows as w}
<li>
<button onclick={() => pickWindow(w)} type="button">
<span class="w-title">{w.title}</span>
<span class="w-dim">{w.width}x{w.height}</span>
</button>
</li>
{/each}
</ul>
{/if}
</div>
{/if}
</div>
<style>
@@ -229,84 +203,4 @@
background: rgba(0, 0, 0, 0.35);
color: #fff;
}
.picker {
background: #1a1a1a;
border: 1px solid #4a8;
border-radius: 4px;
margin: 4px;
max-height: calc(100vh - 32px);
display: flex;
flex-direction: column;
overflow: hidden;
font: 12px ui-monospace, monospace;
color: #ddd;
}
.picker-head {
display: flex;
justify-content: space-between;
align-items: center;
padding: 4px 8px;
background: #222;
border-bottom: 1px solid #2a2a2a;
color: #aaa;
text-transform: uppercase;
letter-spacing: 0.05em;
font-size: 10px;
}
.picker-head button {
background: transparent;
border: none;
color: #888;
font-size: 14px;
cursor: pointer;
padding: 0 4px;
}
.picker-head button:hover {
color: #fff;
}
.picker-empty {
padding: 12px;
text-align: center;
color: #888;
}
.picker-list {
list-style: none;
margin: 0;
padding: 4px;
overflow-y: auto;
flex: 1;
}
.picker-list li {
margin: 0;
}
.picker-list button {
width: 100%;
background: transparent;
border: none;
color: #ddd;
font: inherit;
text-align: left;
padding: 4px 6px;
border-radius: 2px;
cursor: pointer;
display: flex;
gap: 6px;
justify-content: space-between;
align-items: center;
}
.picker-list button:hover {
background: #2a3a35;
color: #fff;
}
.w-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
}
.w-dim {
color: #888;
font-size: 10px;
flex-shrink: 0;
}
</style>
+111
View File
@@ -0,0 +1,111 @@
<script lang="ts">
import { onMount } from "svelte"
import { listen } from "@tauri-apps/api/event"
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"
type Rect = {
x: number
y: number
width: number
height: number
}
let hover: Rect | null = $state(null)
let scale: number = $state(1)
let originX: number = $state(0)
let originY: number = $state(0)
onMount(() => {
const win = getCurrentWebviewWindow()
let unlistenHover: (() => void) | null = null
void (async () => {
scale = await win.scaleFactor()
const pos = await win.outerPosition()
originX = pos.x
originY = pos.y
unlistenHover = await listen<Rect>("picker-hover", (e) => {
hover = e.payload
})
})()
return () => {
unlistenHover?.()
}
})
let style = $derived.by(() => {
if (!hover) return ""
const left = (hover.x - originX) / scale
const top = (hover.y - originY) / scale
const width = hover.width / scale
const height = hover.height / scale
return `left: ${left}px; top: ${top}px; width: ${width}px; height: ${height}px;`
})
</script>
<main>
<div class="dim"></div>
{#if hover}
<div class="frame" style={style}>
<div class="dims">{hover.width} x {hover.height}</div>
</div>
{/if}
<div class="hint">click a window to snap. Esc to cancel.</div>
</main>
<style>
:global(html), :global(body), :global(#picker) {
margin: 0;
padding: 0;
background: transparent;
height: 100vh;
width: 100vw;
overflow: hidden;
cursor: crosshair;
}
main {
position: relative;
width: 100vw;
height: 100vh;
}
.dim {
position: absolute;
inset: 0;
background: rgba(10, 14, 12, 0.18);
}
.frame {
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;
}
@keyframes march {
to { background-position: 16px 0; }
}
.dims {
position: absolute;
top: -22px;
left: 0;
padding: 1px 6px;
background: #4a8;
color: #0e1a16;
font: 11px ui-monospace, monospace;
border-radius: 3px;
}
.hint {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 6px 14px;
background: rgba(0, 0, 0, 0.7);
color: #fff;
border-radius: 999px;
font: 13px ui-monospace, monospace;
pointer-events: none;
}
</style>
+8
View File
@@ -0,0 +1,8 @@
import { mount } from "svelte"
import Picker from "./lib/Picker.svelte"
const app = mount(Picker, {
target: document.getElementById("picker")!,
})
export default app
+1
View File
@@ -23,6 +23,7 @@ export default defineConfig({
input: {
main: resolve(__dirname, "index.html"),
overlay: resolve(__dirname, "overlay.html"),
picker: resolve(__dirname, "picker.html"),
},
},
},