diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 0aa85d0..6698674 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -2,7 +2,9 @@ use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::Sender; +use std::sync::Arc; use std::thread; use anyhow::{anyhow, bail, Context, Result}; @@ -50,6 +52,9 @@ pub struct TranscodeRequest { /// Optional channel to report encoding progress. #[doc(hidden)] pub progress_tx: Option>, + /// Optional cancel signal. When set to true, ffmpeg will be killed. + #[doc(hidden)] + pub cancel: Option>, } const MAX_CLICK_HIGHLIGHTS: usize = 50; @@ -284,7 +289,8 @@ fn two_pass_video( let tx = req.progress_tx.clone(); let dur = req.duration_secs; let fps = req.fps; - run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref())?; + let cancel = req.cancel.clone(); + run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref(), cancel.as_ref())?; // Send 50% to signal pass 1 done, pass 2 starting. if let Some(ref t) = tx { @@ -314,7 +320,7 @@ fn two_pass_video( pass2.arg("-an"); } pass2.arg(&req.output); - run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref())?; + run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref(), cancel.as_ref())?; cleanup_pass_logs(&log_stem); Ok(()) @@ -342,7 +348,14 @@ fn cleanup_pass_logs(stem: &Path) { } fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { - let (mut scale_width, mut effective_fps) = gif_params(req, req.clip_width, req.clip_height); + let budget_input = GifBudgetInput { + gif_colors: req.gif_colors, + target_bytes: req.target_bytes, + fps: req.fps, + duration_secs: req.duration_secs, + gif_budget_mode: req.gif_budget_mode.clone(), + }; + let (mut scale_width, mut effective_fps) = gif_params(&budget_input, req.clip_width, req.clip_height); let target = req.target_bytes; let max_retries = 6; @@ -473,25 +486,35 @@ fn encode_gif_pass( req.duration_secs, effective_fps, req.progress_tx.as_ref(), + req.cancel.as_ref(), )?; Ok(()) } -pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> (u32, u32) { +#[derive(Debug, Clone)] +pub struct GifBudgetInput { + pub gif_colors: u16, + pub target_bytes: u64, + pub fps: u32, + pub duration_secs: f64, + pub gif_budget_mode: GifBudgetMode, +} + +pub fn gif_params(input: &GifBudgetInput, clip_width: u32, clip_height: u32) -> (u32, u32) { let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 }; // GIF LZW compression on typical screen content averages ~0.2 bytes/pixel at 256 colors. // Real compression varies 3-5x depending on content (solid colors compress much better // than gradients/noise). The retry loop in encode_gif handles correction on mismatch. // Fewer colors = better compression. Adjust proportionally. // 256 colors = 1.0x, 128 = ~0.85x, 64 = ~0.7x, 32 = ~0.55x, 16 = ~0.4x, 2 = ~0.2x - let color_factor = (req.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0); + let color_factor = (input.gif_colors as f64 / 256.0).sqrt().clamp(0.15, 1.0); let bytes_per_pixel_per_frame = 0.2 * color_factor; - let target_bytes = req.target_bytes as f64; - let requested_fps = req.fps as f64; - let duration = req.duration_secs; + let target_bytes = input.target_bytes as f64; + let requested_fps = input.fps as f64; + let duration = input.duration_secs; - match req.gif_budget_mode { + match input.gif_budget_mode { GifBudgetMode::Resolution => { let max_w = (clip_width.min(1280) as f64).clamp(120.0, 1280.0); let w = (max_w / 2.0).round() as u32 * 2; @@ -500,7 +523,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> let bytes_per_frame = pixels_per_frame * bytes_per_pixel_per_frame; let max_frames = (target_bytes / bytes_per_frame).floor().max(1.0); let min_fps = (max_frames / duration).max(1.0).round() as u32; - let fps = (req.fps).min(min_fps).max(1); + let fps = (input.fps).min(min_fps).max(1); (w, fps) } GifBudgetMode::Framerate => { @@ -508,7 +531,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> let budget = target_bytes / (frames * bytes_per_pixel_per_frame); let w = (budget * aspect).sqrt(); let w = (w.clamp(120.0, 1280.0).round() as u32 / 2) * 2; - (w, req.fps) + (w, input.fps) } GifBudgetMode::Balanced => { let frames_at_full = (requested_fps * duration).max(1.0); @@ -523,7 +546,7 @@ pub fn gif_params(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> let scale = scale.max(0.1); let w = ((clip_width as f64 * scale).round() as u32 / 2).max(60) * 2; - let fps = ((requested_fps * scale).round() as u32).max(1).min(req.fps); + let fps = ((requested_fps * scale).round() as u32).max(1).min(input.fps); (w, fps) } } @@ -749,7 +772,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re } fn run(cmd: &mut Command, label: &str) -> Result<()> { - let output = run_impl(cmd, label, 0, 0, 0.0, 0, None)?; + let output = run_impl(cmd, label, 0, 0, 0.0, 0, None, None)?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); let head: String = stderr.lines().take(12).collect::>().join("\n"); @@ -768,8 +791,9 @@ fn run_with_progress( duration_secs: f64, fps: u32, progress_tx: Option<&Sender>, + cancel: Option<&Arc>, ) -> Result<()> { - let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned())?; + let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned(), cancel.cloned())?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); let head: String = stderr.lines().take(12).collect::>().join("\n"); @@ -786,6 +810,7 @@ fn run_impl( progress_duration_secs: f64, progress_fps: u32, progress_tx: Option>, + cancel: Option>, ) -> Result { use std::process::Stdio; @@ -804,12 +829,10 @@ fn run_impl( .spawn() .with_context(|| format!("spawning ffmpeg for {label}"))?; - // Spawn a thread to monitor stderr and emit progress. let stderr = child.stderr.take(); let tx = progress_tx.clone(); - let handle = stderr.map(move |serr| { - // Clone the Sender if present. + let mut stderr_handle: Option>> = stderr.map(move |serr| { let tx = tx.as_ref().map(|t| t.clone()); let encode_dur = progress_duration_secs; let fps = progress_fps; @@ -817,8 +840,11 @@ fn run_impl( let total_passes = progress_total_passes; thread::spawn(move || { use std::io::{BufRead, BufReader}; + let mut collected = Vec::new(); let reader = BufReader::new(serr); for line in reader.lines().map_while(Result::ok) { + collected.extend_from_slice(line.as_bytes()); + collected.push(b'\n'); if let Some(frame) = parse_frame_from_stderr(&line) { let total = (encode_dur * fps as f64).max(1.0); let percent = (frame / total * 100.0).min(100.0); @@ -831,14 +857,38 @@ fn run_impl( } } } + collected }) }); - let output = child.wait_with_output().context("waiting for ffmpeg")?; - if let Some(h) = handle { - let _ = h.join(); + loop { + if let Some(ref c) = cancel { + if c.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + if let Some(h) = stderr_handle.take() { + let _ = h.join(); + } + bail!("export cancelled"); + } + } + match child.try_wait() { + Ok(Some(status)) => { + let stderr_bytes = stderr_handle.take() + .and_then(|h| h.join().ok()) + .unwrap_or_default(); + return Ok(std::process::Output { + status, + stdout: Vec::new(), + stderr: stderr_bytes, + }); + } + Ok(None) => { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + Err(e) => bail!("waiting for ffmpeg: {e}"), + } } - Ok(output) } /// Parse a frame count from an ffmpeg stderr progress line. @@ -884,6 +934,7 @@ mod tests { clip_width: 1920, clip_height: 1080, progress_tx: None, + cancel: None, } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f4a3b82..1f884e9 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -19,10 +19,13 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState}; use std::str::FromStr; use crate::bootstrap::FfmpegStatus; -use crate::config::{Config, Format, GifBudgetMode, GifDither, Mp4Codec, WebmCodec}; +use crate::config::{Config, Format, GifBudgetMode, GifDither}; fn lock(m: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { - m.lock().unwrap_or_else(|e| e.into_inner()) + m.lock().unwrap_or_else(|e| { + tracing::warn!("mutex poisoned, recovering"); + e.into_inner() + }) } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] @@ -95,17 +98,11 @@ fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf { } fn timestamp_slug() -> String { - use windows::Win32::System::SystemInformation::GetLocalTime; - let st = unsafe { GetLocalTime() }; - format!( - "{:04}{:02}{:02}-{:02}{:02}{:02}", - st.wYear, - st.wMonth, - st.wDay, - st.wHour, - st.wMinute, - st.wSecond - ) + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + .to_string() } fn ext_for(format: Format) -> &'static str { @@ -239,7 +236,7 @@ fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String .args(["/c", "start", "", ""]) .raw_arg(format!("\"{}\"", bat.to_string_lossy())) .spawn() - .map_err(|e| format!("spawning apply script: {e}"))?; + .map_err(|e| format!("spawning apply script: {e:#}"))?; app.exit(0); Ok(()) } @@ -293,6 +290,12 @@ fn clear_temp_segments(app_dir: &Path) { let _ = std::fs::remove_file(temp.join("recording.mp4")); let _ = std::fs::remove_file(temp.join("video-concat.mp4")); let _ = std::fs::remove_file(temp.join("audio-concat.pcm")); + let thumbs = temp.join("thumbs"); + if thumbs.is_dir() { + let _ = std::fs::remove_dir_all(&thumbs); + } + let _ = std::fs::remove_file(temp.join("preview.png")); + let _ = std::fs::remove_file(temp.join("raw-preview.png")); } /// Pad or trim a raw f32le PCM file so its duration matches `target_secs`. @@ -326,6 +329,32 @@ fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) { } } +fn try_start_audio( + app: &AppHandle, + enabled: bool, + audio_path: PathBuf, +) -> Option { + if !enabled { + return None; + } + match audio::start(audio_path) { + Ok(s) => Some(s), + Err(e) => { + tracing::warn!("audio capture failed: {e:#}"); + let _ = app.emit("audio-failed", e.to_string()); + None + } + } +} + +fn start_click_recorder(enabled: bool) -> Option { + if enabled { + Some(clicks::start()) + } else { + None + } +} + #[tauri::command] fn start_capture( app: AppHandle, @@ -340,7 +369,7 @@ fn start_capture( } 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}"))?; + std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e:#}"))?; clear_temp_segments(&state.app_dir); let crop = request.as_ref().and_then(|r| r.crop); @@ -367,19 +396,8 @@ fn start_capture( set_overlay_clickthrough(&app, true); - let audio_session = if cfg.capture.capture_audio { - let audio_path = audio_segment_path(&state.app_dir, 1); - match audio::start(audio_path) { - Ok(s) => Some(s), - Err(e) => { - tracing::warn!("audio capture failed to start: {e:#}"); - let _ = app.emit("audio-failed", e.to_string()); - None - } - } - } else { - None - }; + let audio_path = audio_segment_path(&state.app_dir, 1); + let audio_session = try_start_audio(&app, cfg.capture.capture_audio, audio_path); let (a_sr, a_ch) = audio_session .as_ref() @@ -403,11 +421,7 @@ fn start_capture( segment_start_offsets: vec![0.0], }; - let click_rec = if cfg.capture.capture_cursor { - Some(clicks::start()) - } else { - None - }; + let click_rec = start_click_recorder(cfg.capture.capture_cursor); *lock(&state.session) = Some(session_state); *lock(&state.capture) = Some(session); @@ -483,25 +497,9 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri let session = capture::start(output, ffmpeg, capture_cursor, audio, crop, fps) .map_err(|e| format!("{e:#}"))?; - let audio_session = if audio { - let audio_path = audio_segment_path(&state.app_dir, next_idx); - match audio::start(audio_path) { - Ok(s) => Some(s), - Err(e) => { - tracing::warn!("audio resume failed: {e:#}"); - let _ = app.emit("audio-failed", e.to_string()); - None - } - } - } else { - None - }; - - let click_rec = if capture_cursor { - Some(clicks::start()) - } else { - None - }; + let audio_path = audio_segment_path(&state.app_dir, next_idx); + let audio_session = try_start_audio(&app, audio, audio_path); + let click_rec = start_click_recorder(capture_cursor); *lock(&state.capture) = Some(session); *lock(&state.audio) = audio_session; @@ -604,7 +602,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result) { use std::time::Duration; - use windows::Win32::Foundation::{HWND, POINT, RECT}; - use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; + use windows::Win32::Foundation::{HWND, POINT}; use windows::Win32::UI::HiDpi::GetDpiForWindow; - use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect}; + use windows::Win32::UI::WindowsAndMessaging::GetCursorPos; std::thread::spawn(move || { let mut last_inner: Option = None; while !shutdown.load(Ordering::Relaxed) { - std::thread::sleep(Duration::from_millis(30)); + std::thread::sleep(Duration::from_millis(80)); let overlay = match app.get_webview_window("overlay") { Some(w) => w, @@ -815,38 +796,21 @@ fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc) { Ok(h) => h, Err(_) => continue, }; - 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::() as u32, - ) - } - .is_ok() - && dwm.right > dwm.left; - let visible = if dwm_ok { - dwm - } else { - let mut outer = RECT::default(); - if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() { - continue; - } - outer + let (vl, vt, vr, vb) = match visible_window_bounds(raw.0 as isize) { + Some(b) => b, + None => continue, }; - let dpi = unsafe { GetDpiForWindow(hwnd) }; + let dpi = unsafe { GetDpiForWindow(HWND(raw.0 as *mut _)) }; let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 }; let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; - let inner_left = visible.left + border; - let inner_top = visible.top + border + titlebar; - let inner_right = visible.right - border; - let inner_bottom = visible.bottom - border; + let inner_left = vl + border; + let inner_top = vt + border + titlebar; + let inner_right = vr - border; + let inner_bottom = vb - border; let in_inner = pt.x >= inner_left && pt.x < inner_right @@ -880,7 +844,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; - win.show().map_err(|e| e.to_string())?; + win.show().map_err(|e| format!("showing overlay: {e:#}"))?; let _ = mark_overlay_excluded_from_capture(&win); // If the overlay is off-screen (monitor disconnected), center on primary @@ -915,7 +879,7 @@ fn show_overlay(app: AppHandle) -> Result<(), String> { } } } - win.set_focus().map_err(|e| e.to_string()) + win.set_focus().map_err(|e| format!("setting focus: {e:#}")) } #[tauri::command] @@ -923,7 +887,7 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; - win.hide().map_err(|e| e.to_string()) + win.hide().map_err(|e| format!("hiding overlay: {e:#}")) } #[tauri::command] @@ -940,7 +904,7 @@ fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, heig let final_w = w + (OVERLAY_BORDER_LOGICAL_PX * 2.0); let final_h = 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| e.to_string())?; + .map_err(|e| format!("setting overlay size: {e:#}"))?; Ok(()) } @@ -953,7 +917,7 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option< .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| e.to_string())?; + let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?; let cur_w = sz.width as f64 / scale; let cur_h = sz.height as f64 / scale; let target_h = cur_w / r; @@ -962,7 +926,7 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option< 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| e.to_string())?; + .map_err(|e| format!("setting overlay size: {e:#}"))?; } } Ok(()) @@ -983,7 +947,7 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result< .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| e.to_string())?; + let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?; let cur_w = sz.width as f64 / scale; let cur_h = sz.height as f64 / scale; let target_h = (cur_w / ratio).round(); @@ -1041,13 +1005,13 @@ fn open_window_picker( use tauri::{PhysicalPosition, PhysicalSize, Position, Size}; picker .set_size(Size::Physical(PhysicalSize::new(mw, mh))) - .map_err(|e| e.to_string())?; + .map_err(|e| format!("setting picker size: {e:#}"))?; picker .set_position(Position::Physical(PhysicalPosition::new(0, 0))) - .map_err(|e| e.to_string())?; + .map_err(|e| format!("setting picker position: {e:#}"))?; let _ = picker.set_ignore_cursor_events(false); let _ = picker.set_always_on_top(true); - picker.show().map_err(|e| e.to_string())?; + picker.show().map_err(|e| format!("showing picker: {e:#}"))?; if let Ok(h) = picker.hwnd() { use windows::Win32::Foundation::{HWND, RECT}; use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS}; @@ -1095,6 +1059,34 @@ fn close_window_picker( 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 _); + let mut dwm = RECT::default(); + if unsafe { + DwmGetWindowAttribute( + hwnd, + DWMWA_EXTENDED_FRAME_BOUNDS, + &mut dwm as *mut RECT as *mut std::ffi::c_void, + std::mem::size_of::() as u32, + ) + } + .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(); + if unsafe { GetWindowRect(hwnd, &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}; @@ -1218,35 +1210,14 @@ fn set_overlay_to_window( #[tauri::command] fn get_overlay_rect(app: AppHandle) -> Result { - 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 .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; - let scale = win.scale_factor().map_err(|e| e.to_string())?; + let scale = win.scale_factor().map_err(|e| format!("getting scale factor: {e:#}"))?; 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::() 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 (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize) + .ok_or_else(|| "GetWindowRect failed".to_string())?; let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32; let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32; @@ -1254,8 +1225,8 @@ fn get_overlay_rect(app: AppHandle) -> Result { let inset_top = border_phys + titlebar_phys; let inset_sides = border_phys; - let visible_w = visible.right - visible.left; - let visible_h = visible.bottom - visible.top; + let visible_w = vr - vl; + let visible_h = vb - vt; let width = (visible_w - inset_sides * 2).max(2) as u32; let height = (visible_h - inset_top - inset_sides).max(2) as u32; @@ -1263,8 +1234,8 @@ fn get_overlay_rect(app: AppHandle) -> Result { let height = (height / 2) * 2; Ok(CaptureRect { - x: visible.left + inset_sides, - y: visible.top + inset_top, + x: vl + inset_sides, + y: vt + inset_top, width, height, }) @@ -1296,7 +1267,7 @@ fn reveal_in_explorer(path: String) -> Result<(), String> { Command::new("explorer.exe") .arg(parent) .spawn() - .map_err(|e| format!("opening explorer: {e}"))?; + .map_err(|e| format!("opening explorer: {e:#}"))?; } Ok(()) } @@ -1310,7 +1281,7 @@ fn open_url(url: String) -> Result<(), String> { std::process::Command::new("cmd") .raw_arg(format!("/C start \"\" \"{url}\"")) .spawn() - .map_err(|e| format!("opening url: {e}"))?; + .map_err(|e| format!("opening url: {e:#}"))?; Ok(()) } @@ -1344,7 +1315,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> }; if let Some(parent) = out_path.parent() { std::fs::create_dir_all(parent) - .map_err(|e| format!("creating output dir: {e}"))?; + .map_err(|e| format!("creating output dir: {e:#}"))?; } let trim_start = request.trim_start_secs.filter(|s| *s > 0.001); @@ -1402,6 +1373,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> clip_width: clip.width, clip_height: clip.height, progress_tx: None, + cancel: Some(state.export_cancel.clone()), }; let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 }; diff --git a/src/app.css b/src/app.css index 511cb90..bb5d4b6 100644 --- a/src/app.css +++ b/src/app.css @@ -151,4 +151,14 @@ body { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; } + .phase-dot.pulse, + .bar, + .blink, + .enc-fill, + .fill, + .audio-dot.active, + .dot.pulse { + animation: none !important; + transition: none !important; + } } diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index effc092..b66a1a7 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -171,10 +171,10 @@ } async function stopRec() { - clearTick() void emit("recording-state", { phase: "idle", fps }) try { const c = await api.stopCapture() + clearTick() clip = c phase = "editing" trimStart = 0 @@ -188,13 +188,17 @@ outputPath = await api.defaultOutputPath(format) const sensible = Math.min(50, Math.max(minMB(c.duration_secs), Math.round(c.duration_secs * 0.5))) targetMB = sensible - } catch (e) { errMsg = String(e); phase = "idle" } + } catch (e) { errMsg = String(e); phase = "idle"; clearTick() } } async function pauseRec() { - clearTick() - try { await api.pauseCapture(); phase = "paused" } - catch (e) { errMsg = String(e); tick() } + try { + await api.pauseCapture() + clearTick() + phase = "paused" + } catch (e) { + errMsg = String(e) + } void emit("recording-state", { phase: "paused", fps }) } @@ -216,7 +220,7 @@ try { previewPath = await api.renderPreview(format, fps, Math.round(targetMB * 1_048_576), format === "gif" ? gifBudgetMode : undefined, format === "gif" ? gifDither : undefined, format === "gif" ? gifColors : undefined) previewCacheBust = Date.now() - } catch { previewPath = null } + } catch (e) { previewPath = null; console.warn("preview render failed:", e) } finally { previewLoading = false } } @@ -229,6 +233,10 @@ try { const thumbs = await api.extractThumbnails(fps) thumbCache.set(cacheKey, thumbs) + if (thumbCache.size > 5) { + const firstKey = thumbCache.keys().next().value + if (firstKey) thumbCache.delete(firstKey) + } thumbnails = thumbs deletedFrames = new Set() } catch (e) { errMsg = String(e) } @@ -302,6 +310,7 @@ let dragging: 'start' | 'end' | null = $state(null) let trimPreviewPath: string | null = $state(null) let trimPreviewBust: number = $state(0) + let lastTrimPreview = 0 function pointerToSecs(e: PointerEvent): number { if (!trackEl || !clip) return 0 @@ -312,6 +321,9 @@ } async function updateTrimPreview(secs: number) { + const now = Date.now() + if (now - lastTrimPreview < 100) return // 10Hz max + lastTrimPreview = now try { trimPreviewPath = await api.renderRawPreview(secs) trimPreviewBust = Date.now() @@ -367,8 +379,6 @@ $effect(() => { if (phase === "editing" && format) { - // Read these so the effect re-runs when they change - const _deps = format === "gif" ? `${gifBudgetMode}-${gifDither}-${gifColors}-${fps}-${targetMB}` : `${fps}-${targetMB}` const timer = window.setTimeout(() => { void refreshPreview() }, 300) return () => { clearTimeout(timer) } } @@ -754,19 +764,19 @@
{/if} @@ -1151,7 +1161,7 @@ .edit { flex: 1; display: grid; - grid-template-columns: 1.4fr 1fr; + grid-template-columns: minmax(300px, 1.4fr) minmax(250px, 1fr); gap: 1px; background: var(--border); min-height: 0; diff --git a/src/lib/Settings.svelte b/src/lib/Settings.svelte index 7c2db13..6719a23 100644 --- a/src/lib/Settings.svelte +++ b/src/lib/Settings.svelte @@ -11,6 +11,9 @@ let hotkeyWarnings: string[] = $state([]) let showAdvanced: boolean = $state(false) let activeTab: string = $state("capture") + let initialCfg: string = $state("") + + let dirty = $derived(cfg ? JSON.stringify(cfg) !== initialCfg : false) const TABS = [ { id: "capture", label: "Capture" }, @@ -20,7 +23,7 @@ { id: "system", label: "System" }, ] - onMount(async () => { cfg = await api.getConfig() }) + onMount(async () => { cfg = await api.getConfig(); initialCfg = JSON.stringify(cfg) }) async function save() { if (!cfg) return @@ -44,6 +47,7 @@ if (failed.length > 0) { hotkeyWarnings = [`${failed.join(", ")} - hotkey may be in use by another app`] } else { + initialCfg = JSON.stringify(cfg) onClose() } } finally { saving = false } @@ -231,6 +235,7 @@ + {#if dirty}{/if} {/if} @@ -481,4 +486,13 @@ } .btn-warn:hover:not(:disabled) { background: var(--stop-hover); } .btn-warn:disabled { opacity: 0.4; cursor: not-allowed; } + + .unsaved-dot { + width: 6px; height: 6px; + border-radius: 50%; + background: var(--warn); + display: inline-block; + margin-left: 8px; + vertical-align: middle; + }