From e4141f8be883be8c449845475e783cd0058ed5cf Mon Sep 17 00:00:00 2001 From: lashman Date: Wed, 27 May 2026 19:14:33 +0300 Subject: [PATCH] 20 fixes: mutex poisoning recovery, clickthrough shutdown, audio cleanup, config corruption, GIF aspect ratio, ffmpeg crash detection, cancel export, discard confirm, thumbnail cache, keyboard nav, right-click tracking, multi-monitor overlay, click injection fix, update script robustness, effect cleanup, concat guard, dead code removal --- src-tauri/src/audio.rs | 26 ++++-- src-tauri/src/capture.rs | 19 ++++- src-tauri/src/clicks.rs | 48 +++++++---- src-tauri/src/config.rs | 13 ++- src-tauri/src/encode.rs | 29 +++++-- src-tauri/src/lib.rs | 170 ++++++++++++++++++++++----------------- src-tauri/src/updates.rs | 12 +++ src/lib/Main.svelte | 79 ++++++++++++++++-- src/lib/Overlay.svelte | 53 ++++++------ src/lib/api.ts | 1 + 10 files changed, 310 insertions(+), 140 deletions(-) diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs index f909a44..80c70fd 100644 --- a/src-tauri/src/audio.rs +++ b/src-tauri/src/audio.rs @@ -158,6 +158,24 @@ fn capture_thread( // Notify parent that init succeeded. let _ = init_tx.send(Ok((sample_rate, channels))); + let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer); + + unsafe { + let _ = client.Stop(); + } + writer.flush().context("flushing audio writer")?; + + result +} + +fn capture_loop( + running: &Arc, + capture_client: &IAudioCaptureClient, + channels: u16, + bits_per_sample: u16, + is_float: bool, + writer: &mut BufWriter, +) -> Result<()> { while running.load(Ordering::Relaxed) { let mut packet_length = unsafe { capture_client @@ -186,7 +204,6 @@ fn capture_thread( let samples = (num_frames_available as usize) * (channels as usize); if is_silent { - // Write f32 zeros for silent frames. let zero_bytes = samples * 4; let zeros = vec![0u8; zero_bytes]; writer.write_all(&zeros).context("writing silent audio")?; @@ -197,7 +214,6 @@ fn capture_thread( }; writer.write_all(slice).context("writing audio data")?; } else { - // Convert integer PCM to f32 little-endian. match bits_per_sample { 16 => { let i16_slice = unsafe { @@ -241,11 +257,5 @@ fn capture_thread( thread::sleep(std::time::Duration::from_millis(1)); } - - unsafe { - let _ = client.Stop(); - } - - writer.flush().context("flushing audio writer")?; Ok(()) } diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 52e5fb0..a79f85c 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -1,6 +1,8 @@ use std::io::Write; use std::path::PathBuf; use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; use anyhow::{anyhow, bail, Context, Result}; @@ -27,6 +29,7 @@ pub struct CaptureSetup { pub height: u32, pub fps: u32, pub crop: Option, + pub crashed: Arc, } pub struct CaptureHandler { @@ -35,6 +38,7 @@ pub struct CaptureHandler { width: u32, height: u32, scratch: Vec, + crashed: Arc, } impl GraphicsCaptureApiHandler for CaptureHandler { @@ -96,6 +100,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler { width: setup.width, height: setup.height, scratch: Vec::with_capacity(frame_size), + crashed: setup.crashed, }) } @@ -119,7 +124,8 @@ impl GraphicsCaptureApiHandler for CaptureHandler { return Ok(()); } stdin.write_all(&bytes[..expected]).map_err(|e| { - tracing::error!("ffmpeg stdin write failed: {e} — encoder may have crashed"); + tracing::error!("ffmpeg stdin write failed: {e} - encoder may have crashed"); + self.crashed.store(true, Ordering::Release); anyhow!("ffmpeg encoder stopped unexpectedly: {e}") })?; Ok(()) @@ -141,6 +147,7 @@ pub struct CaptureSession { pub width: u32, pub height: u32, pub crop: Option, + pub crashed: Arc, control: CaptureControl, } @@ -203,6 +210,8 @@ pub fn start( let (out_w, out_h) = compute_output_dims(width, height, crop); + let crashed = Arc::new(AtomicBool::new(false)); + let setup = CaptureSetup { output_path: output_path.clone(), ffmpeg_path, @@ -210,6 +219,7 @@ pub fn start( height, fps, crop, + crashed: crashed.clone(), }; let cursor_setting = if capture_cursor { @@ -238,6 +248,7 @@ pub fn start( width: out_w, height: out_h, crop, + crashed, control, }) } @@ -264,6 +275,10 @@ fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option } impl CaptureSession { + pub fn has_crashed(&self) -> bool { + self.crashed.load(Ordering::Acquire) + } + pub fn stop(self) -> Result { self.control .stop() @@ -271,7 +286,7 @@ impl CaptureSession { let meta = std::fs::metadata(&self.output_path) .with_context(|| format!("checking output file {}", self.output_path.display()))?; if meta.len() == 0 { - bail!("capture output file is empty — ffmpeg may have crashed during recording"); + bail!("capture output file is empty - ffmpeg may have crashed during recording"); } Ok(self.output_path) } diff --git a/src-tauri/src/clicks.rs b/src-tauri/src/clicks.rs index a479cb0..fdf8715 100644 --- a/src-tauri/src/clicks.rs +++ b/src-tauri/src/clicks.rs @@ -5,11 +5,19 @@ use std::time::{Duration, Instant}; use serde::Serialize; +#[derive(Debug, Clone, Copy, Serialize)] +pub enum MouseButton { + Left, + Right, + Middle, +} + #[derive(Debug, Clone, Copy, Serialize)] pub struct Click { pub time_secs: f64, pub x: i32, pub y: i32, + pub button: MouseButton, } pub struct ClickRecorder { @@ -30,26 +38,38 @@ pub fn start() -> ClickRecorder { use windows::Win32::UI::WindowsAndMessaging::GetCursorPos; const VK_LBUTTON: i32 = 0x01; + const VK_RBUTTON: i32 = 0x02; + const VK_MBUTTON: i32 = 0x04; + + let buttons = [ + (VK_LBUTTON, MouseButton::Left), + (VK_RBUTTON, MouseButton::Right), + (VK_MBUTTON, MouseButton::Middle), + ]; + let start = Instant::now(); - let mut last_pressed = false; + let mut last_pressed = [false; 3]; while running_clone.load(Ordering::Relaxed) { - let state = unsafe { GetAsyncKeyState(VK_LBUTTON) }; - let pressed = (state as u16 & 0x8000) != 0; - if pressed && !last_pressed { - let mut pt = POINT::default(); - if unsafe { GetCursorPos(&mut pt) }.is_ok() { - let click = Click { - time_secs: start.elapsed().as_secs_f64(), - x: pt.x, - y: pt.y, - }; - if let Ok(mut v) = clicks_clone.lock() { - v.push(click); + for (i, &(vk, button)) in buttons.iter().enumerate() { + let state = unsafe { GetAsyncKeyState(vk) }; + let pressed = (state as u16 & 0x8000) != 0; + if pressed && !last_pressed[i] { + let mut pt = POINT::default(); + if unsafe { GetCursorPos(&mut pt) }.is_ok() { + let click = Click { + time_secs: start.elapsed().as_secs_f64(), + x: pt.x, + y: pt.y, + button, + }; + if let Ok(mut v) = clicks_clone.lock() { + v.push(click); + } } } + last_pressed[i] = pressed; } - last_pressed = pressed; thread::sleep(Duration::from_millis(5)); } }); diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 4c468ad..a67dc89 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -136,7 +136,18 @@ impl Config { return Ok(cfg); } let raw = std::fs::read_to_string(path)?; - Ok(toml::from_str(&raw)?) + match toml::from_str::(&raw) { + Ok(cfg) => Ok(cfg), + Err(e) => { + // Config is corrupt - back it up and return defaults + tracing::warn!("config.toml is corrupt ({e}), backing up and using defaults"); + let backup = path.with_extension("toml.bak"); + let _ = std::fs::copy(path, &backup); + let cfg = Self::default(); + cfg.save(path)?; + Ok(cfg) + } + } } pub fn save(&self, path: &Path) -> Result<()> { diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 2e312aa..8fe2658 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -43,6 +43,8 @@ pub struct TranscodeRequest { pub trim_start_secs: Option, pub trim_end_secs: Option, pub clicks: Vec, + pub clip_width: u32, + pub clip_height: u32, /// Optional channel to report encoding progress. #[doc(hidden)] pub progress_tx: Option>, @@ -70,8 +72,13 @@ fn click_filters(req: &TranscodeRequest) -> Option { let y = click.y - half; let t1 = (click.time_secs - 0.05).max(0.0); let t2 = click.time_secs + 0.25; + let color = match click.button { + crate::clicks::MouseButton::Left => "yellow@0.6", + crate::clicks::MouseButton::Right => "blue@0.6", + crate::clicks::MouseButton::Middle => "green@0.6", + }; parts.push(format!( - "drawbox=x={x}:y={y}:w={size}:h={size}:color=yellow@0.6:t=fill:enable='between(t,{t1:.3},{t2:.3})'" + "drawbox=x={x}:y={y}:w={size}:h={size}:color={color}:t=fill:enable='between(t,{t1:.3},{t2:.3})'" )); } if parts.is_empty() { @@ -334,7 +341,7 @@ fn cleanup_pass_logs(stem: &Path) { fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { let palette_path = req.scratch_dir.join("palette.png"); - let scale_width = estimate_gif_scale_width(req); + let scale_width = estimate_gif_scale_width(req, req.clip_width, req.clip_height); let crop_prefix = crop_filter(req.crop) .map(|c| format!("{c},")) .unwrap_or_default(); @@ -405,11 +412,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { Ok(()) } -fn estimate_gif_scale_width(req: &TranscodeRequest) -> u32 { +fn estimate_gif_scale_width(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> u32 { let bytes_per_pixel_per_frame = 0.5_f64; let frames = (req.fps as f64 * req.duration_secs).max(1.0); let budget = req.target_bytes as f64 / (frames * bytes_per_pixel_per_frame); - let aspect = 16.0_f64 / 9.0; + let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 }; let w = (budget * aspect).sqrt(); let w = w.clamp(120.0, 1280.0).round() as u32; (w / 2) * 2 @@ -536,6 +543,11 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> { Ok(()) } +struct TempFileGuard(PathBuf); +impl Drop for TempFileGuard { + fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); } +} + pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> { if segments.is_empty() { bail!("no segments to concatenate"); @@ -551,6 +563,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re std::fs::create_dir_all(parent).context("creating output parent dir")?; let list_path = parent.join("concat-list.txt"); + let _guard = TempFileGuard(list_path.clone()); let mut body = String::new(); for seg in segments { let s = seg @@ -570,9 +583,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re .arg(&list_path) .args(["-c", "copy"]) .arg(output); - let result = run(&mut cmd, "concat"); - let _ = std::fs::remove_file(&list_path); - result + run(&mut cmd, "concat") } fn run(cmd: &mut Command, label: &str) -> Result<()> { @@ -706,6 +717,8 @@ mod tests { trim_start_secs: None, trim_end_secs: None, clicks: vec![], + clip_width: 1920, + clip_height: 1080, progress_tx: None, } } @@ -780,7 +793,7 @@ mod tests { #[test] fn click_filters_capped_at_max() { let clicks: Vec = (0..100) - .map(|i| Click { time_secs: i as f64, x: i, y: i }) + .map(|i| Click { time_secs: i as f64, x: i, y: i, button: crate::clicks::MouseButton::Left }) .collect(); let req = TranscodeRequest { clicks, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bee2f5e..3666ff6 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -9,7 +9,8 @@ mod window_picker; mod windows_list; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; @@ -20,6 +21,10 @@ use std::str::FromStr; use crate::bootstrap::FfmpegStatus; use crate::config::{Config, Format}; +fn lock(m: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct CaptureRect { pub x: i32, @@ -37,6 +42,7 @@ pub struct AppState { pub last_clip: Mutex>, pub session: Mutex>, pub picker: Mutex>, + pub overlay_poll_shutdown: Arc, } pub struct SessionState { @@ -116,7 +122,7 @@ struct AppStatus { #[tauri::command] fn get_status(state: State<'_, AppState>) -> AppStatus { - let cfg = state.config.lock().expect("config mutex"); + let cfg = lock(&state.config); AppStatus { ffmpeg: bootstrap::check(&state.app_dir), needs_first_run: cfg.needs_first_run(), @@ -125,7 +131,7 @@ fn get_status(state: State<'_, AppState>) -> AppStatus { #[tauri::command] fn get_config(state: State<'_, AppState>) -> Config { - state.config.lock().expect("config mutex").clone() + lock(&state.config).clone() } fn parse_shortcut(s: &str) -> Option { @@ -184,7 +190,7 @@ fn save_config( ) -> Result { let path = config::config_path(&state.app_dir); config.save(&path).map_err(|e| format!("{e:#}"))?; - *state.config.lock().expect("config mutex") = config.clone(); + *lock(&state.config) = config.clone(); let hotkey_result = register_hotkeys(&app, &config); Ok(SaveConfigResult { hotkey_result }) } @@ -324,12 +330,12 @@ fn start_capture( request: Option, ) -> Result<(), String> { { - let slot = state.capture.lock().expect("capture mutex"); + let slot = lock(&state.capture); if slot.is_some() { return Err("a capture is already running".to_string()); } } - let cfg = state.config.lock().expect("config mutex").clone(); + let cfg = lock(&state.config).clone(); let temp = temp_dir(&state.app_dir); std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?; clear_temp_segments(&state.app_dir); @@ -399,40 +405,34 @@ fn start_capture( None }; - *state.session.lock().expect("session mutex") = Some(session_state); - *state.capture.lock().expect("capture mutex") = Some(session); - *state.audio.lock().expect("audio mutex") = audio_session; - *state.click_recorder.lock().expect("click mutex") = click_rec; + *lock(&state.session) = Some(session_state); + *lock(&state.capture) = Some(session); + *lock(&state.audio) = audio_session; + *lock(&state.click_recorder) = click_rec; Ok(()) } #[tauri::command] fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { - let session = state - .capture - .lock() - .expect("capture mutex") + let session = lock(&state.capture) .take() .ok_or_else(|| "no capture in progress".to_string())?; + if session.has_crashed() { + return Err("recording failed - ffmpeg encoder crashed".to_string()); + } let elapsed = session.started_at.elapsed().as_secs_f64(); let path = session.stop().map_err(|e| format!("{e:#}"))?; - let audio_path = state - .audio - .lock() - .expect("audio mutex") + let audio_path = lock(&state.audio) .take() .and_then(|a| a.stop().ok()); - let new_clicks: Vec = state - .click_recorder - .lock() - .expect("click mutex") + let new_clicks: Vec = lock(&state.click_recorder) .take() .map(|r| r.stop()) .unwrap_or_default(); - let mut ss = state.session.lock().expect("session mutex"); + let mut ss = lock(&state.session); let ss = ss .as_mut() .ok_or_else(|| "no session state".to_string())?; @@ -455,13 +455,13 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { #[tauri::command] fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { { - let slot = state.capture.lock().expect("capture mutex"); + let slot = lock(&state.capture); if slot.is_some() { return Err("a capture is already running".to_string()); } } let (capture_cursor, audio, crop, next_idx) = { - let ss = state.session.lock().expect("session mutex"); + let ss = lock(&state.session); let ss = ss .as_ref() .ok_or_else(|| "no session to resume".to_string())?; @@ -473,7 +473,7 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri ) }; - let fps = state.config.lock().expect("config mutex").capture.default_fps; + let fps = lock(&state.config).capture.default_fps; let output = segment_path(&state.app_dir, next_idx); let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { @@ -502,9 +502,9 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri None }; - *state.capture.lock().expect("capture mutex") = Some(session); - *state.audio.lock().expect("audio mutex") = audio_session; - *state.click_recorder.lock().expect("click mutex") = click_rec; + *lock(&state.capture) = Some(session); + *lock(&state.audio) = audio_session; + *lock(&state.click_recorder) = click_rec; Ok(()) } @@ -512,32 +512,29 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result { set_overlay_clickthrough(&app, false); - let mut ss = state - .session - .lock() - .expect("session mutex") + let mut ss = lock(&state.session) .take() .ok_or_else(|| "no session to stop".to_string())?; - let live = state.capture.lock().expect("capture mutex").take(); + let live = lock(&state.capture).take(); if let Some(session) = live { + if session.has_crashed() { + return Err("recording failed - ffmpeg encoder crashed".to_string()); + } let elapsed = session.started_at.elapsed().as_secs_f64(); let path = session.stop().map_err(|e| format!("{e:#}"))?; ss.segments.push(path); ss.total_recorded_secs += elapsed; } - let live_audio = state.audio.lock().expect("audio mutex").take(); + let live_audio = lock(&state.audio).take(); if let Some(a) = live_audio { if let Ok(p) = a.stop() { ss.audio_segments.push(p); } } - let live_clicks = state - .click_recorder - .lock() - .expect("click mutex") + let live_clicks = lock(&state.click_recorder) .take() .map(|r| r.stop()) .unwrap_or_default(); @@ -623,7 +620,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result, format: Format) -> String { - let cfg = state.config.lock().expect("config mutex").clone(); + let cfg = lock(&state.config).clone(); let dir = output_dir(&state.app_dir, &cfg); dir.join(format!( "bytesize-{}.{}", @@ -670,10 +667,7 @@ fn render_preview( state: State<'_, AppState>, request: PreviewRequest, ) -> Result { - let clip = state - .last_clip - .lock() - .expect("clip mutex") + let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); @@ -709,10 +703,7 @@ fn extract_thumbnails( state: State<'_, AppState>, fps: u32, ) -> Result, String> { - let clip = state - .last_clip - .lock() - .expect("clip mutex") + let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); @@ -733,11 +724,8 @@ pub struct ExportResult { const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0; const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0; -fn apply_overlay_region(_win: &tauri::WebviewWindow) -> Result<(), String> { - Ok(()) -} -fn start_overlay_clickthrough_poll(app: AppHandle) { +fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc) { use std::time::Duration; use windows::Win32::Foundation::{HWND, POINT, RECT}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; @@ -746,7 +734,7 @@ fn start_overlay_clickthrough_poll(app: AppHandle) { std::thread::spawn(move || { let mut last_inner: Option = None; - loop { + while !shutdown.load(Ordering::Relaxed) { std::thread::sleep(Duration::from_millis(30)); let overlay = match app.get_webview_window("overlay") { @@ -762,7 +750,7 @@ fn start_overlay_clickthrough_poll(app: AppHandle) { // start_capture already sets ignore_cursor_events(true). Skip polling // so we don't fight it. let state = app.state::(); - let is_recording = state.capture.lock().expect("capture mutex").is_some(); + let is_recording = lock(&state.capture).is_some(); if is_recording { last_inner = Some(true); continue; @@ -843,7 +831,39 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { .ok_or_else(|| "overlay window not found".to_string())?; win.show().map_err(|e| e.to_string())?; let _ = mark_overlay_excluded_from_capture(&win); - let _ = apply_overlay_region(&win); + + // If the overlay is off-screen (monitor disconnected), center on primary + use windows::Win32::Foundation::{HWND, POINT, RECT}; + use windows::Win32::Graphics::Gdi::{ + GetMonitorInfoW, MonitorFromPoint, MONITOR_DEFAULTTOPRIMARY, MONITOR_DEFAULTTONULL, MONITORINFO, + }; + use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER}; + if let Ok(raw) = win.hwnd() { + let hwnd = HWND(raw.0 as *mut _); + let mut rect = RECT::default(); + if unsafe { GetWindowRect(hwnd, &mut rect) }.is_ok() { + let center = POINT { + x: (rect.left + rect.right) / 2, + y: (rect.top + rect.bottom) / 2, + }; + let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) }; + if hmon.0.is_null() { + let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) }; + let mut mi = MONITORINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + if unsafe { GetMonitorInfoW(primary, &mut mi) }.as_bool() { + let work = mi.rcWork; + let w = rect.right - rect.left; + let h = rect.bottom - rect.top; + let cx = (work.left + work.right) / 2 - w / 2; + let cy = (work.top + work.bottom) / 2 - h / 2; + let _ = unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) }; + } + } + } + } win.set_focus().map_err(|e| e.to_string()) } @@ -868,7 +888,6 @@ fn set_overlay_size(app: AppHandle, width: u32, height: u32) -> Result<(), Strin height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0); win.set_size(Size::Logical(LogicalSize::new(final_w, final_h))) .map_err(|e| e.to_string())?; - let _ = apply_overlay_region(&win); Ok(()) } @@ -937,7 +956,7 @@ fn open_window_picker( } { - let mut slot = state.picker.lock().expect("picker mutex"); + let mut slot = lock(&state.picker); if let Some(existing) = slot.take() { existing.stop(); } @@ -951,7 +970,7 @@ fn close_window_picker( app: AppHandle, state: State<'_, AppState>, ) -> Result<(), String> { - if let Some(session) = state.picker.lock().expect("picker mutex").take() { + if let Some(session) = lock(&state.picker).take() { session.stop(); } if let Some(picker) = app.get_webview_window("picker") { @@ -1078,8 +1097,6 @@ fn set_overlay_to_window( } .map_err(|e| format!("SetWindowPos: {e}"))?; - let _ = apply_overlay_region(&win); - let _ = (visible_left, visible_top, visible_w, visible_h, scale, border_phys, titlebar_phys); Ok(()) } @@ -1170,9 +1187,12 @@ fn reveal_in_explorer(path: String) -> Result<(), String> { #[tauri::command] fn open_url(url: String) -> Result<(), String> { - use std::process::Command; - Command::new("cmd") - .args(["/C", "start", "", &url]) + if !url.starts_with("http://") && !url.starts_with("https://") { + return Err("only http/https URLs are supported".to_string()); + } + use std::os::windows::process::CommandExt; + std::process::Command::new("cmd") + .raw_arg(format!("/C start \"\" \"{url}\"")) .spawn() .map_err(|e| format!("opening url: {e}"))?; Ok(()) @@ -1180,11 +1200,8 @@ fn open_url(url: String) -> Result<(), String> { #[tauri::command] fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result { - let cfg = state.config.lock().expect("config mutex").clone(); - let clip = state - .last_clip - .lock() - .expect("clip mutex") + let cfg = lock(&state.config).clone(); + let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; @@ -1238,6 +1255,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> time_secs: c.time_secs, x: (((c.x - src_origin.0) as f64) * scale).round() as i32, y: (((c.y - src_origin.1) as f64) * scale).round() as i32, + button: c.button, }) .collect(); @@ -1258,6 +1276,8 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> trim_start_secs: trim_start, trim_end_secs: trim_end, clicks: transformed_clicks, + clip_width: clip.width, + clip_height: clip.height, progress_tx: None, }; @@ -1322,6 +1342,7 @@ pub fn run() { last_clip: Mutex::new(None), session: Mutex::new(None), picker: Mutex::new(None), + overlay_poll_shutdown: Arc::new(AtomicBool::new(false)), }; tauri::Builder::default() @@ -1334,8 +1355,8 @@ pub fn run() { } let cfg = { let st = app.state::(); - let guard = st.config.lock().expect("config mutex"); - guard.clone() + let cfg = lock(&st.config).clone(); + cfg }; let kind = if cfg .hotkeys @@ -1377,11 +1398,14 @@ pub fn run() { .setup(|app| { let (check_on_launch, cfg) = { let st = app.state::(); - let cfg = st.config.lock().expect("config mutex").clone(); + let cfg = lock(&st.config).clone(); (cfg.updates.check_on_launch, cfg) }; let _ = register_hotkeys(app.handle(), &cfg); - start_overlay_clickthrough_poll(app.handle().clone()); + { + let st = app.state::(); + start_overlay_clickthrough_poll(app.handle().clone(), st.overlay_poll_shutdown.clone()); + } if check_on_launch { let handle = app.handle().clone(); tauri::async_runtime::spawn(async move { diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index d2a2c6a..4aca415 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -106,8 +106,20 @@ pub fn write_apply_script(app_dir: &Path) -> Result { let body = format!( "@echo off\r\n\ timeout /t 1 /nobreak >nul\r\n\ + if not exist \"%~dp0ByteSize.new.exe\" (\r\n\ + echo Update file not found\r\n\ + pause\r\n\ + del \"%~f0\"\r\n\ + exit /b 1\r\n\ + )\r\n\ del \"%~dp0{exe}\"\r\n\ move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\ + if errorlevel 1 (\r\n\ + echo Failed to replace executable\r\n\ + pause\r\n\ + del \"%~f0\"\r\n\ + exit /b 1\r\n\ + )\r\n\ start \"\" \"%~dp0{exe}\"\r\n\ del \"%~f0\"\r\n", exe = exe_name diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index c8dc05e..8b9fbbb 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -48,6 +48,8 @@ let audioWarning: string | null = $state(null) let useFrame: boolean = $state(false) let previewTimer: number | null = null + let thumbCache: Map = $state(new Map()) + let showDiscardConfirm: boolean = $state(false) const PRESETS: [number, number, string][] = [ [1280, 720, "720p"], @@ -182,9 +184,14 @@ async function loadThumbnails() { if (format !== "gif") { thumbnails = []; return } + const cacheKey = `${format}-${fps}` + const cached = thumbCache.get(cacheKey) + if (cached) { thumbnails = cached; deletedFrames = new Set(); return } loadingThumbs = true try { - thumbnails = await api.extractThumbnails(fps) + const thumbs = await api.extractThumbnails(fps) + thumbCache.set(cacheKey, thumbs) + thumbnails = thumbs deletedFrames = new Set() } catch (e) { errMsg = String(e) } finally { loadingThumbs = false } @@ -220,10 +227,30 @@ function startOver() { clip = null; exportResult = null; errMsg = null; encodeProgress = null thumbnails = []; deletedFrames = new Set() + thumbCache = new Map() if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null } elapsed = 0; phase = "idle" } + async function cancelExport() { + try { await api.cancelExport() } catch {} + phase = "editing" + encodeProgress = null + } + + function confirmDiscard() { + showDiscardConfirm = true + } + + function cancelDiscard() { + showDiscardConfirm = false + } + + function doDiscard() { + showDiscardConfirm = false + startOver() + } + function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) } function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } } function minMB(s: number): number { return Math.max(0.1, Math.max(50_000, s * 50_000) / 1_048_576) } @@ -283,10 +310,9 @@ $effect(() => { if (phase === "editing" && format) { - if (previewTimer !== null) clearTimeout(previewTimer) - previewTimer = window.setTimeout(() => { previewTimer = null; void refreshPreview() }, 300) + const timer = window.setTimeout(() => { void refreshPreview() }, 300) + return () => { clearTimeout(timer) } } - return () => { if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null } } }) $effect(() => { @@ -474,6 +500,12 @@ onpointerdown={(e) => startDrag('start', e)} onpointermove={onDrag} onpointerup={endDrag} + onkeydown={(e) => { + if (!clip) return + const step = e.shiftKey ? 0.5 : 0.05 + if (e.key === 'ArrowLeft') { trimStart = Math.max(0, trimStart - step); e.preventDefault() } + else if (e.key === 'ArrowRight') { trimStart = Math.min(trimEnd - 0.1, trimStart + step); e.preventDefault() } + }} >
startDrag('end', e)} onpointermove={onDrag} onpointerup={endDrag} + onkeydown={(e) => { + if (!clip) return + const step = e.shiftKey ? 0.5 : 0.05 + if (e.key === 'ArrowLeft') { trimEnd = Math.max(trimStart + 0.1, trimEnd - step); e.preventDefault() } + else if (e.key === 'ArrowRight') { trimEnd = Math.min(clip.duration_secs, trimEnd + step); e.preventDefault() } + }} >
- +
@@ -629,6 +667,7 @@
{/if}

ffmpeg is encoding your clip

+ @@ -650,6 +689,18 @@ {/if} + + {#if showDiscardConfirm} +
+
+

Discard this recording?

+
+ + +
+
+
+ {/if} @@ -1373,4 +1424,22 @@ } .mono { font-family: var(--mono); } + + /* ---- Confirm overlay ---- */ + .confirm-overlay { + position: fixed; inset: 0; + background: rgba(0,0,0,0.5); + display: grid; place-items: center; + z-index: 50; + } + .confirm-card { + background: var(--bg-2); + border: 1px solid var(--border); + border-radius: var(--r-md); + padding: 24px; + min-width: 280px; + text-align: center; + } + .confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); } + .confirm-actions { display: flex; gap: 10px; justify-content: center; } diff --git a/src/lib/Overlay.svelte b/src/lib/Overlay.svelte index 13b4873..1908e60 100644 --- a/src/lib/Overlay.svelte +++ b/src/lib/Overlay.svelte @@ -22,39 +22,34 @@ height = Math.round(sz.height / sf) } updateSize() - const rp = win.onResized(updateSize) + let cleanup: (() => void)[] = [] - let rp2: Promise<() => void> | null = null - void (async () => { - rp2 = listen<{ phase: "idle"|"recording"|"paused"; fps: number }>( - "recording-state", (e) => { - fps = e.payload.fps - if (e.payload.phase === "recording") { - if (phase !== "recording") elapsed = 0 - startTimer() - } else { - stopTimer() - } - if (e.payload.phase === "idle") { elapsed = 0; phase = "idle" } - phase = e.payload.phase + win.onResized(updateSize).then(fn => cleanup.push(fn)) + + listen<{ phase: "idle"|"recording"|"paused"; fps: number }>( + "recording-state", (e) => { + fps = e.payload.fps + if (e.payload.phase === "recording") { + if (phase !== "recording") elapsed = 0 + startTimer() + } else { + stopTimer() } - ) - })() + if (e.payload.phase === "idle") { elapsed = 0; phase = "idle" } + phase = e.payload.phase + } + ).then(fn => cleanup.push(fn)) - let rp3: Promise<() => void> | null = null - void (async () => { - rp3 = listen("picker-pick", async (e: { payload: Rect }) => { - try { await invoke("set_overlay_to_window", e.payload) } catch {} - try { await invoke("close_window_picker") } catch {} - }) - })() - void (async () => { - await listen("picker-cancel", async () => { - try { await invoke("close_window_picker") } catch {} - }) - })() + 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)) - return () => { stopTimer(); void rp.then(fn => fn()); void rp2?.then(fn => fn()); void rp3?.then(fn => fn()) } + listen("picker-cancel", async () => { + try { await invoke("close_window_picker") } catch {} + }).then(fn => cleanup.push(fn)) + + return () => { stopTimer(); cleanup.forEach(fn => fn()) } }) function startTimer() { diff --git a/src/lib/api.ts b/src/lib/api.ts index 654ee24..d3217be 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -184,6 +184,7 @@ export const api = { listen("encode-progress", (e) => handler(e.payload)), onAudioFailed: (handler: (msg: string) => void): Promise => listen("audio-failed", (e) => handler(e.payload)), + cancelExport: () => invoke("cancel_export"), } export function formatBytes(n: number): string {