diff --git a/picker.html b/picker.html new file mode 100644 index 0000000..4759035 --- /dev/null +++ b/picker.html @@ -0,0 +1,12 @@ + + + + + + ByteSize window picker + + +
+ + + diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 04a1ff6..d2f682e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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>, pub last_clip: Mutex>, pub session: Mutex>, + pub picker: Mutex>, } pub struct SessionState { @@ -780,6 +782,61 @@ fn list_windows() -> Vec { 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 = 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!()) diff --git a/src-tauri/src/window_picker.rs b/src-tauri/src/window_picker.rs new file mode 100644 index 0000000..f406ca5 --- /dev/null +++ b/src-tauri/src/window_picker.rs @@ -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, + handle: Option>, +} + +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; + + 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(); + } + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 05eb8a2..3271940 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -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": { diff --git a/src/lib/Overlay.svelte b/src/lib/Overlay.svelte index 2a4fc6e..cc603fb 100644 --- a/src/lib/Overlay.svelte +++ b/src/lib/Overlay.svelte @@ -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("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) { - try { - await invoke("set_overlay_to_window", { - x: w.x, - y: w.y, - width: w.width, - height: w.height, + 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", 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) + })() + return () => { + unlistenPick?.() + unlistenCancel?.() } - pickerOpen = false - } + })
@@ -121,7 +120,7 @@ {width} x {height}
- - {#if pickerOpen} - - {/if} diff --git a/src/lib/Picker.svelte b/src/lib/Picker.svelte new file mode 100644 index 0000000..53e99e9 --- /dev/null +++ b/src/lib/Picker.svelte @@ -0,0 +1,111 @@ + + +
+
+ {#if hover} +
+
{hover.width} x {hover.height}
+
+ {/if} +
click a window to snap. Esc to cancel.
+
+ + diff --git a/src/picker.ts b/src/picker.ts new file mode 100644 index 0000000..eac4fdc --- /dev/null +++ b/src/picker.ts @@ -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 diff --git a/vite.config.ts b/vite.config.ts index ea56c40..aa52d01 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -23,6 +23,7 @@ export default defineConfig({ input: { main: resolve(__dirname, "index.html"), overlay: resolve(__dirname, "overlay.html"), + picker: resolve(__dirname, "picker.html"), }, }, },