diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index db3f322..38e2b46 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -7,6 +7,7 @@ "core:default", "core:window:default", "core:window:allow-start-dragging", + "core:window:allow-start-resize-dragging", "core:webview:default", "dialog:default", "global-shortcut:default" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 30edf14..bbda6ac 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -20,6 +20,7 @@ mod capture; mod clicks; mod config; mod encode; +mod overlay_chrome; mod timed_video; mod updates; mod window_picker; @@ -1172,7 +1173,8 @@ pub struct ExportResult { } const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0; -const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0; +const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 44.0; +const OVERLAY_TOOLBAR_WIDTH_LOGICAL_PX: f64 = 380.0; /// Remove temporary recording artifacts (segments, previews, thumbs). /// Called on app exit so a discarded clip doesn't linger in `temp/`. @@ -1242,10 +1244,7 @@ fn overlay_should_ignore_cursor(app: &AppHandle) -> Option { return None; } let state = app.state::(); - if lock(&state.capture).is_some() { - // Mid-recording the frame is inert, so clicks reach the app below it. - return Some(true); - } + let recording_or_paused = lock(&state.session).is_some(); let mut pt = POINT::default(); // SAFETY: `pt` is a live local that GetCursorPos writes through. @@ -1253,7 +1252,7 @@ fn overlay_should_ignore_cursor(app: &AppHandle) -> Option { return None; } let raw = overlay.hwnd().ok()?; - let (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)?; + let (vl, vt, vr, vb) = overlay_client_bounds(raw.0 as isize)?; // SAFETY: `raw` is the overlay's own live HWND from Tauri. let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::())) }; @@ -1268,7 +1267,16 @@ fn overlay_should_ignore_cursor(app: &AppHandle) -> Option { let inner_right = vr - border; let inner_bottom = vb - border; - Some(pt.x >= inner_left && pt.x < inner_right && pt.y >= inner_top && pt.y < inner_bottom) + let toolbar_right = (inner_left + encode::round_i32(OVERLAY_TOOLBAR_WIDTH_LOGICAL_PX * scale)).min(inner_right); + let over_toolbar = pt.x >= inner_left && pt.x < toolbar_right + && pt.y >= vt + border && pt.y < vt + titlebar - border; + let over_frame = pt.y >= vt + titlebar && pt.x >= vl && pt.x < vr && pt.y < vb + && !(pt.x >= inner_left && pt.x < inner_right && pt.y >= inner_top && pt.y < inner_bottom); + let grip = encode::round_i32(13.0 * scale); + let over_corner = pt.x >= vl && pt.x < vr && pt.y >= vt + titlebar && pt.y < vb + && (pt.x < vl + grip || pt.x >= vr - grip) + && (pt.y < vt + titlebar + grip || pt.y >= vb - grip); + Some(!(over_toolbar || (!recording_or_paused && (over_frame || over_corner)))) } fn start_overlay_clickthrough_poll( @@ -1359,7 +1367,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { // If the overlay is off-screen (monitor disconnected), center on primary if let Ok(raw) = win.hwnd() { - if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) { + if let Some((vl, vt, vr, vb)) = overlay_client_bounds(raw.0 as isize) { let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb), @@ -1454,33 +1462,11 @@ fn set_overlay_size( } #[tauri::command] -fn set_overlay_aspect( - app: AppHandle, - state: State<'_, AppState>, - ratio: Option, -) -> Result<(), String> { - *lock(&state.overlay_aspect_ratio) = ratio; - if let Some(r) = ratio { - // Enforce on current size - let win = app - .get_webview_window("overlay") - .ok_or_else(|| "overlay window not found".to_string())?; - let scale = win.scale_factor().unwrap_or(1.0); - let sz = win - .inner_size() - .map_err(|e| format!("getting window size: {e:#}"))?; - let cur_w = f64::from(sz.width) / scale; - let cur_h = f64::from(sz.height) / scale; - let target_h = cur_w / r; - if (target_h - cur_h).abs() > 1.0 { - use tauri::{LogicalSize, Size}; - let final_w = cur_w + (OVERLAY_BORDER_LOGICAL_PX * 2.0); - let final_h = - target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0); - win.set_size(Size::Logical(LogicalSize::new(final_w, final_h))) - .map_err(|e| format!("setting overlay size: {e:#}"))?; - } +fn set_overlay_aspect(state: State<'_, AppState>, ratio: Option) -> Result<(), String> { + if ratio.is_some_and(|value| !value.is_finite() || !(0.1..=10.0).contains(&value)) { + return Err("invalid capture aspect ratio".to_string()); } + *lock(&state.overlay_aspect_ratio) = ratio; Ok(()) } @@ -1491,51 +1477,18 @@ fn get_overlay_aspect(state: State<'_, AppState>) -> Option { #[tauri::command] fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { - use windows::Win32::Foundation::HWND; - use windows::Win32::UI::WindowsAndMessaging::{ - SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER, - }; - + if lock(&state.session).is_some() { + return Ok(()); + } let Some(ratio) = *lock(&state.overlay_aspect_ratio) else { return Ok(()); }; - let win = app - .get_webview_window("overlay") - .ok_or_else(|| "overlay window not found".to_string())?; - let scale = win.scale_factor().unwrap_or(1.0); - let sz = win - .inner_size() - .map_err(|e| format!("getting window size: {e:#}"))?; - let cur_w = f64::from(sz.width) / scale; - let cur_h = f64::from(sz.height) / scale; - let target_h = (cur_w / ratio).round(); - if (target_h - cur_h).abs() <= 2.0 { - return Ok(()); // already correct + let rect = get_overlay_rect(app.clone())?; + let height = encode::round_i32(f64::from(rect.width) / ratio).max(2).cast_unsigned() & !1; + if rect.height.abs_diff(height) <= 2 { + return Ok(()); } - // Use Win32 SetWindowPos for reliable enforcement - let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; - let hwnd = HWND(raw.0.cast::()); - // Compute outer size including borders - let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale); - let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale); - let outer_w = sz.width.cast_signed().max(2); - let outer_h = - encode::round_i32(target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0); - // SAFETY: `hwnd` is the overlay's live handle; the flags keep the resize - // non-activating and non-reordering, and no pointers are involved. - unsafe { - SetWindowPos( - hwnd, - Some(HWND_TOP), - 0, - 0, - outer_w, - outer_h, - SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE, - ) - } - .map_err(|e| format!("SetWindowPos: {e}"))?; - Ok(()) + set_overlay_to_window(app, rect.x, rect.y, rect.width, height) } #[tauri::command] @@ -1552,7 +1505,25 @@ fn list_windows() -> Vec { fn open_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { use tauri::{PhysicalPosition, PhysicalSize, Position, Size}; - let (mw, mh) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?; + use windows::Win32::UI::WindowsAndMessaging::{ + GetSystemMetrics, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, + SM_YVIRTUALSCREEN, + }; + + let desktop = |metric| { + // SAFETY: GetSystemMetrics is a value-only desktop query. + unsafe { GetSystemMetrics(metric) } + }; + let left = desktop(SM_XVIRTUALSCREEN); + let top = desktop(SM_YVIRTUALSCREEN); + let width = desktop(SM_CXVIRTUALSCREEN); + let height = desktop(SM_CYVIRTUALSCREEN); + if width <= 0 || height <= 0 { + return Err("could not get virtual desktop bounds".to_string()); + } + if let Some(previous) = lock(&state.picker).take() { + previous.stop(); + } let mut exclude: Vec = Vec::new(); for label in &["main", "overlay", "picker"] { @@ -1562,22 +1533,16 @@ fn open_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), } } } - tracing::debug!( - "open_window_picker: monitor={}x{} exclude={:?}", - mw, - mh, - exclude - ); - let picker = app .get_webview_window("picker") .ok_or_else(|| "picker window not found".to_string())?; picker - .set_size(Size::Physical(PhysicalSize::new(mw, mh))) - .map_err(|e| format!("setting picker size: {e:#}"))?; - picker - .set_position(Position::Physical(PhysicalPosition::new(0, 0))) + .set_position(Position::Physical(PhysicalPosition::new(left, top))) .map_err(|e| format!("setting picker position: {e:#}"))?; + picker + .set_size(Size::Physical(PhysicalSize::new(width.cast_unsigned(), height.cast_unsigned()))) + .map_err(|e| format!("setting picker size: {e:#}"))?; + drop(app.emit("picker-hover", Option::::None)); drop(picker.set_ignore_cursor_events(false)); drop(picker.set_always_on_top(true)); picker @@ -1615,13 +1580,7 @@ fn open_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), ); } - { - let mut slot = lock(&state.picker); - if let Some(existing) = slot.take() { - existing.stop(); - } - *slot = Some(window_picker::start(app.clone(), exclude)); - } + *lock(&state.picker) = Some(window_picker::start(app.clone(), exclude)); Ok(()) } @@ -1639,70 +1598,30 @@ fn close_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), if let Some(picker) = app.get_webview_window("picker") { drop(picker.hide()); } + drop(app.emit("picker-hover", Option::::None)); Ok(()) } -fn visible_window_bounds(hwnd_raw: isize) -> Option<(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 std::ffi::c_void); - let mut dwm = RECT::default(); - // SAFETY: `dwm` is a live RECT local and the size argument matches it; the - // result is checked and the rect is only read when it is well-formed. - if unsafe { - DwmGetWindowAttribute( - hwnd, - DWMWA_EXTENDED_FRAME_BOUNDS, - (&raw mut dwm).cast::(), - u32::try_from(size_of::()).unwrap_or(0), - ) - } - .is_ok() - && dwm.right > dwm.left - && dwm.bottom > dwm.top - { - return Some((dwm.left, dwm.top, dwm.right, dwm.bottom)); - } - let mut outer = RECT::default(); - // SAFETY: `outer` is a live RECT local that the call writes through. - if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_ok() { - Some((outer.left, outer.top, outer.right, outer.bottom)) - } else { - None - } -} - -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; +fn overlay_client_bounds(hwnd_raw: isize) -> Option<(i32, i32, i32, i32)> { + use windows::Win32::Foundation::{HWND, POINT, RECT}; + use windows::Win32::Graphics::Gdi::ClientToScreen; + use windows::Win32::UI::WindowsAndMessaging::GetClientRect; let hwnd = HWND(hwnd_raw as *mut std::ffi::c_void); - let mut outer = RECT::default(); - // SAFETY: `outer` is a live RECT local that the call writes through. - if unsafe { GetWindowRect(hwnd, &raw mut outer) }.is_err() { - return (0, 0, 0, 0); + let mut client = RECT::default(); + let mut origin = POINT::default(); + // SAFETY: `client` is a live RECT that GetClientRect writes through. + unsafe { GetClientRect(hwnd, &raw mut client) }.ok()?; + // SAFETY: `origin` is a live POINT and `hwnd` is the overlay's window. + if !unsafe { ClientToScreen(hwnd, &raw mut origin) }.as_bool() { + return None; } - let mut dwm = RECT::default(); - // SAFETY: `dwm` is a live RECT local and the size argument matches it. - let r = unsafe { - DwmGetWindowAttribute( - hwnd, - DWMWA_EXTENDED_FRAME_BOUNDS, - (&raw mut dwm).cast::(), - u32::try_from(size_of::()).unwrap_or(0), - ) - }; - 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, - ) + Some(( + origin.x, + origin.y, + origin.x + client.right, + origin.y + client.bottom, + )) } /// Get the DPI scale factor for the monitor containing a given point. @@ -1760,27 +1679,12 @@ fn set_overlay_to_window( let border_phys = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale); let titlebar_phys = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale); - // 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.cast_signed() + border_phys * 2; - let visible_h = height.cast_signed() + border_phys * 2 + titlebar_phys; + // The client fills the HWND, so only the drawn frame adds padding. + let outer_x = x - border_phys; + let outer_y = y - border_phys - titlebar_phys; + let outer_w = (width.cast_signed() + border_phys * 2).max(2); + let outer_h = (height.cast_signed() + border_phys * 2 + titlebar_phys).max(2); - // 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_or((0, 0, 0, 0), |h| dwm_insets(h.0 as isize)); - - let outer_x = visible_left - li; - let outer_y = visible_top - ti; - let outer_w = (visible_w + li + ri).max(2).cast_unsigned(); - let outer_h = (visible_h + ti + bi).max(2).cast_unsigned(); - - // 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}"))?; let hwnd = HWND(raw.0.cast::()); // SAFETY: `hwnd` is the overlay's live handle and every dimension is a @@ -1791,8 +1695,8 @@ fn set_overlay_to_window( Some(HWND_TOP), outer_x, outer_y, - outer_w.cast_signed(), - outer_h.cast_signed(), + outer_w, + outer_h, SWP_NOACTIVATE | SWP_NOZORDER, ) } @@ -1811,8 +1715,8 @@ fn get_overlay_rect(app: AppHandle) -> Result { .map_err(|e| format!("getting scale factor: {e:#}"))?; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; - let (vl, vt, vr, vb) = - visible_window_bounds(raw.0 as isize).ok_or_else(|| "GetWindowRect failed".to_string())?; + let (vl, vt, vr, vb) = overlay_client_bounds(raw.0 as isize) + .ok_or_else(|| "could not measure capture frame".to_string())?; let border_phys = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale); let titlebar_phys = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale); @@ -2329,6 +2233,11 @@ pub fn run() { ) .manage(state) .setup(|app| { + if let Some(overlay) = app.get_webview_window("overlay") { + if let Err(error) = overlay_chrome::configure(&overlay) { + tracing::warn!(%error, "could not configure the capture frame's native styles"); + } + } let (check_on_launch, cfg) = { let st = app.state::(); let cfg = lock(&st.config).clone(); diff --git a/src-tauri/src/overlay_chrome.rs b/src-tauri/src/overlay_chrome.rs new file mode 100644 index 0000000..fb876fc --- /dev/null +++ b/src-tauri/src/overlay_chrome.rs @@ -0,0 +1,109 @@ +use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM}; +use windows::Win32::Graphics::Dwm::{ + DwmSetWindowAttribute, DWMNCRP_DISABLED, DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, + DWMWA_NCRENDERING_POLICY, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND, +}; +use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass}; +use windows::Win32::UI::WindowsAndMessaging::{ + GetWindowLongW, SetWindowLongW, SetWindowPos, GWL_EXSTYLE, GWL_STYLE, STYLESTRUCT, + SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WM_NCACTIVATE, + WM_NCDESTROY, WM_NCPAINT, WM_STYLECHANGING, WS_CAPTION, WS_EX_CLIENTEDGE, WS_EX_WINDOWEDGE, + WS_POPUP, WS_SYSMENU, +}; + +const SUBCLASS_ID: usize = 1; + +fn frame_style(style: u32) -> u32 { + (style & !(WS_CAPTION.0 | WS_SYSMENU.0)) | WS_POPUP.0 +} + +fn frame_extended_style(style: u32) -> u32 { + style & !(WS_EX_CLIENTEDGE.0 | WS_EX_WINDOWEDGE.0) +} + +unsafe extern "system" fn overlay_window_proc( + hwnd: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + subclass_id: usize, + _data: usize, +) -> LRESULT { + match message { + WM_STYLECHANGING if lparam.0 != 0 => { + // SAFETY: WM_STYLECHANGING supplies a writable STYLESTRUCT for the duration of the call. + let styles = unsafe { &mut *(lparam.0 as *mut STYLESTRUCT) }; + let index = wparam.0.cast_signed(); + if index == GWL_STYLE.0 as isize { + // Tao can restore the caption bits on visibility or click-through changes. + styles.styleNew = frame_style(styles.styleNew); + } else if index == GWL_EXSTYLE.0 as isize { + styles.styleNew = frame_extended_style(styles.styleNew); + } + } + WM_NCPAINT => return LRESULT(0), + WM_NCACTIVATE => { + // SAFETY: -1 preserves activation handling while suppressing the system frame redraw. + return unsafe { DefSubclassProc(hwnd, message, wparam, LPARAM(-1)) }; + } + WM_NCDESTROY => { + // SAFETY: This callback is registered on this HWND with the supplied ID. + let _removed = + unsafe { RemoveWindowSubclass(hwnd, Some(overlay_window_proc), subclass_id) }; + } + _ => {} + } + // SAFETY: Forward the original Win32 callback arguments to the next window procedure. + unsafe { DefSubclassProc(hwnd, message, wparam, lparam) } +} + +/// Install on the window's UI thread. +pub(crate) fn configure(window: &tauri::WebviewWindow) -> anyhow::Result<()> { + let hwnd = HWND(window.hwnd()?.0); + // SAFETY: The live HWND belongs to the current thread and the callback needs no user data. + let installed = unsafe { SetWindowSubclass(hwnd, Some(overlay_window_proc), SUBCLASS_ID, 0) }; + anyhow::ensure!( + installed.as_bool(), + "installing the capture frame window procedure failed" + ); + + for (index, filter) in [ + (GWL_STYLE, frame_style as fn(u32) -> u32), + (GWL_EXSTYLE, frame_extended_style), + ] { + // SAFETY: Both indices read value-only styles on the live HWND. + let style = unsafe { GetWindowLongW(hwnd, index) }.cast_unsigned(); + // SAFETY: Only the 32-bit style is modified on the owning thread. + let _previous = unsafe { SetWindowLongW(hwnd, index, filter(style).cast_signed()) }; + } + + for (attribute, value) in [ + (DWMWA_NCRENDERING_POLICY, DWMNCRP_DISABLED.0.cast_unsigned()), + ( + DWMWA_WINDOW_CORNER_PREFERENCE, + DWMWCP_DONOTROUND.0.cast_unsigned(), + ), + (DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE), + ] { + // SAFETY: Each attribute takes a 32-bit value. Older Windows can reject the last two. + if let Err(error) = + unsafe { DwmSetWindowAttribute(hwnd, attribute, (&raw const value).cast(), 4) } + { + tracing::debug!(attribute = attribute.0, %error, "capture frame DWM override unavailable"); + } + } + + // SAFETY: Recalculate the frame on the live HWND without moving, resizing, or activating it. + unsafe { + SetWindowPos( + hwnd, + None, + 0, + 0, + 0, + 0, + SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ) + }?; + Ok(()) +} diff --git a/src-tauri/src/window_picker.rs b/src-tauri/src/window_picker.rs index 6a65ed6..cf1dec7 100644 --- a/src-tauri/src/window_picker.rs +++ b/src-tauri/src/window_picker.rs @@ -46,7 +46,7 @@ unsafe fn visible_window_rect(hwnd: HWND) -> Option { const VK_LBUTTON: i32 = 0x01; const VK_ESCAPE: i32 = 0x1B; -#[derive(Serialize, Clone)] +#[derive(Serialize, Clone, Copy, PartialEq, Eq)] pub(crate) struct Rect { pub x: i32, pub y: i32, @@ -177,7 +177,7 @@ pub(crate) 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_rect = None; let mut last_pressed = true; let mut last_esc = true; @@ -195,51 +195,23 @@ pub(crate) fn start(app: AppHandle, exclude_hwnds: Vec) -> PickerSession let target = top_window_at(pt, &exclude_hwnds); - if let Some((id, rect)) = target { - if id != last_hwnd { - // SAFETY: `id` came from EnumWindows, so it is a live HWND. - let class = unsafe { class_of(HWND(id as *mut std::ffi::c_void)) }; - tracing::info!( - "picker hover: hwnd={:x} class={} rect=({},{}) {}x{}", - id, - class, - rect.left, - rect.top, - rect.right - rect.left, - rect.bottom - rect.top - ); - drop(app.emit( - "picker-hover", - Rect { - x: rect.left, - y: rect.top, - width: (rect.right - rect.left).max(0).cast_unsigned(), - height: (rect.bottom - rect.top).max(0).cast_unsigned(), - }, - )); - last_hwnd = id; - } - } else if last_hwnd != 0 { - tracing::info!("picker hover: no target found at ({}, {})", pt.x, pt.y); - last_hwnd = 0; - } else { - // Still hovering the same window, so the frame is already drawn. + let hover = target.map(|(_, rect)| Rect { + x: rect.left, + y: rect.top, + width: (rect.right - rect.left).max(0).cast_unsigned(), + height: (rect.bottom - rect.top).max(0).cast_unsigned(), + }); + if hover != last_rect { + drop(app.emit("picker-hover", hover)); + last_rect = hover; } let pressed = // SAFETY: a self-contained query with no pointer arguments. unsafe { (GetAsyncKeyState(VK_LBUTTON).cast_unsigned() & 0x8000) != 0 }; if pressed && !last_pressed { - if let Some((_, rect)) = target { - drop(app.emit( - "picker-pick", - Rect { - x: rect.left, - y: rect.top, - width: (rect.right - rect.left).max(0).cast_unsigned(), - height: (rect.bottom - rect.top).max(0).cast_unsigned(), - }, - )); + if let Some(rect) = hover { + drop(app.emit("picker-pick", rect)); break; } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index bea146c..f39b70e 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -32,8 +32,11 @@ "minHeight": 90, "transparent": true, "decorations": false, + "shadow": false, "alwaysOnTop": true, "skipTaskbar": true, + "minimizable": false, + "maximizable": false, "resizable": true, "visible": false }, diff --git a/src/lib/Overlay.svelte b/src/lib/Overlay.svelte index 20fb15e..290b88e 100644 --- a/src/lib/Overlay.svelte +++ b/src/lib/Overlay.svelte @@ -3,214 +3,170 @@ import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow" import { listen, emit } from "@tauri-apps/api/event" import { invoke } from "@tauri-apps/api/core" + import { IconAppWindow, IconGripVertical, IconPlayerPauseFilled, IconPlayerPlayFilled, IconPlayerRecordFilled, IconPlayerStopFilled, IconX } from "./ui/icons" + import { api, type CaptureRect } from "./api" + import { appear, timecode } from "./ui/motion" const win = getCurrentWebviewWindow() - type Rect = { x: number; y: number; width: number; height: number } + type ResizeDirection = Parameters[0] + const corners = [ + { id:"nw", direction:"NorthWest" }, { id:"ne", direction:"NorthEast" }, + { id:"sw", direction:"SouthWest" }, { id:"se", direction:"SouthEast" }, + ] as const + type Phase = "idle" | "recording" | "paused" + let rect: CaptureRect | null = $state(null) + let phase: Phase = $state("idle") + let elapsed = $state(0) + let hotkey = $state(null) + let failure = $state("") + let timer: number | undefined + let resizeDelay: number | undefined + let lockedRatio: number | null = null + let enforcing = false - let width: number = $state(0) - let height: number = $state(0) - let phase: "idle" | "recording" | "paused" = $state("idle") - let elapsed: number = $state(0) - let timer: number | null = null - let lockedRatio: number | null = $state(null) - let enforceTimer: number | null = null - let skipEnforce = false + async function refresh() { + const next = await api.getOverlayRect() + rect = next + await emit("overlay-rect", next) + return next + } + function fail(error: unknown) { failure = String(error) } + function move(event: MouseEvent) { + if (event.button === 0 && phase === "idle") void win.startDragging().catch(fail) + } + function resize(event: PointerEvent, direction: ResizeDirection) { + if (event.button !== 0 || phase !== "idle") return + event.preventDefault() + void win.startResizeDragging(direction).catch(fail) + } + async function command(kind: "start"|"pause"|"stop") { + failure = "" + try { await emit("overlay-control", kind) } catch (error) { fail(error) } + } + async function pick() { + failure = "" + try { await api.openWindowPicker() } catch (error) { fail(error) } + } + async function close() { + try { await api.hideOverlay(); await emit("overlay-closed") } catch (error) { fail(error) } + } onMount(() => { - const updateSize = async () => { - const sz = await win.innerSize() - const sf = await win.scaleFactor() - width = Math.round(sz.width / sf) - height = Math.round(sz.height / sf) + let mounted = true + const listeners: (() => void)[] = [] + function keep(promise: Promise<() => void>) { + void promise.then(fn => { if (mounted) listeners.push(fn); else fn() }).catch(fail) } - - updateSize() - // Get initial ratio - invoke("get_overlay_aspect").then(r => { lockedRatio = r }).catch(() => {}) - - let cleanup: (() => void)[] = [] - - // Listen for ratio changes from Main window via event - listen<{ ratio: number | null }>("overlay-set-ratio", (e) => { - lockedRatio = e.payload.ratio - }).then(fn => cleanup.push(fn)) - - win.onResized(async () => { - if (skipEnforce) return - await updateSize() - if (lockedRatio === null) return - // Debounce: only enforce after resize settles (user released mouse) - if (enforceTimer !== null) clearTimeout(enforceTimer) - enforceTimer = window.setTimeout(async () => { - skipEnforce = true - try { await invoke("enforce_overlay_aspect") } catch {} - await updateSize() - // Skip events from our own enforcement for a bit - setTimeout(() => { skipEnforce = false }, 100) - }, 200) - }).then(fn => cleanup.push(fn)) - - listen<{ phase: "idle"|"recording"|"paused" }>( - "recording-state", (e) => { - if (e.payload.phase === "recording") { - if (phase !== "recording") elapsed = 0 - startTimer() - } else { - stopTimer() - } - if (e.payload.phase === "idle") elapsed = 0 - phase = e.payload.phase + void refresh().catch(fail) + const loadHotkey = () => api.getConfig().then(config => { hotkey = config.hotkeys.start }).catch(fail) + void loadHotkey() + void invoke("get_overlay_aspect").then(value => { lockedRatio = value }).catch(fail) + keep(win.onFocusChanged(event => { if (event.payload) { failure = ""; void refresh().catch(fail); void loadHotkey() } })) + keep(win.onMoved(() => { void refresh().catch(fail) })) + keep(win.onScaleChanged(() => { void refresh().catch(fail) })) + keep(win.onResized(() => { + void refresh().catch(fail) + if (enforcing || lockedRatio === null || phase !== "idle") return + window.clearTimeout(resizeDelay) + resizeDelay = window.setTimeout(async () => { + enforcing = true + try { await invoke("enforce_overlay_aspect"); await refresh() } catch (error) { fail(error) } + finally { enforcing = false } + }, 150) + })) + keep(listen<{ratio: number | null}>("overlay-set-ratio", event => { + lockedRatio = event.payload.ratio + window.clearTimeout(resizeDelay) + })) + keep(listen<{phase: Phase; elapsed: number}>("recording-state", event => { + window.clearInterval(timer) + phase = event.payload.phase + elapsed = event.payload.elapsed + if (phase === "recording") { + const start = performance.now(), initial = elapsed + timer = window.setInterval(() => elapsed = initial + (performance.now() - start) / 1000, 100) } - ).then(fn => cleanup.push(fn)) - - listen("picker-pick", async (e: { payload: Rect }) => { - try { await invoke("set_overlay_to_window", e.payload) } catch {} - try { await invoke("close_window_picker") } catch {} - }).then(fn => cleanup.push(fn)) - - listen("picker-cancel", async () => { - try { await invoke("close_window_picker") } catch {} - }).then(fn => cleanup.push(fn)) - + })) + keep(listen("picker-pick", async event => { + const next = event.payload + failure = "" + try { + lockedRatio = null + await api.setOverlayAspect(null) + await api.setOverlayToWindow(next.x, next.y, next.width, next.height) + await emit("overlay-window-selected", await refresh()) + } catch (error) { fail(error); await emit("picker-cancel") } + finally { await invoke("close_window_picker").catch(fail) } + })) + keep(listen("picker-cancel", () => { void invoke("close_window_picker").catch(fail) })) return () => { - stopTimer() - if (enforceTimer !== null) clearTimeout(enforceTimer) - cleanup.forEach(fn => fn()) + mounted = false + window.clearInterval(timer) + window.clearTimeout(resizeDelay) + listeners.forEach(fn => fn()) } }) - - function startTimer() { - if (timer !== null) return - timer = window.setInterval(() => { elapsed += 0.1 }, 100) - } - function stopTimer() { - if (timer !== null) { clearInterval(timer); timer = null } - } - - function drag(e: MouseEvent) { - if (e.button === 0) win.startDragging().catch(() => {}) - } - - async function openPicker() { - try { await invoke("open_window_picker") } catch (err) { console.error(err) } - } - - async function closeOverlay() { - try { await invoke("hide_overlay") } catch {} - try { await emit("overlay-closed", {}) } catch {} - } -
-