quality pass: safe timestamps, cancel support, dedup, frontend polish

- replace unsafe GetLocalTime with safe SystemTime epoch
- lock() logs warning on mutex poison recovery
- extract try_start_audio/start_click_recorder helpers to dedup capture code
- cancel_export now actually kills ffmpeg via polling loop + cancel flag
- extract visible_window_bounds helper for DWM rect lookups
- clear_temp_segments cleans thumbs dir and preview files
- gif_params takes focused GifBudgetInput instead of full TranscodeRequest
- consistent error messages with full context chain
- reduce overlay clickthrough poll from 30ms to 80ms
- throttle trim preview to 10Hz
- bound thumbnail cache at 5 entries
- timer ticks until stopCapture resolves
- crop fields validate against clip dimensions
- settings shows unsaved indicator dot
- edit grid uses minmax for fluid responsive layout
- animations respect prefers-reduced-motion
- pauseRec only clears timer after successful pause
- refreshPreview logs errors instead of swallowing
- remove dead _deps string from preview effect
This commit is contained in:
2026-05-29 23:38:18 +03:00
parent e9005415c4
commit d57e554ece
5 changed files with 236 additions and 179 deletions
+116 -144
View File
@@ -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<T>(m: &std::sync::Mutex<T>) -> 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<audio::AudioSession> {
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<clicks::ClickRecorder> {
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<RecordedCl
} else if video_concat != final_path {
std::fs::rename(&video_concat, &final_path)
.or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ()))
.map_err(|e| format!("finalizing: {e}"))?;
.map_err(|e| format!("finalizing: {e:#}"))?;
let _ = std::fs::remove_file(&video_concat);
}
@@ -686,30 +684,14 @@ fn render_preview(
}
let target_width: u32 = if request.format == Format::Gif {
let req = encode::TranscodeRequest {
input: clip.temp_path.clone(),
output: PathBuf::new(),
format: request.format,
target_bytes: request.target_bytes,
duration_secs: clip.duration_secs,
fps: request.fps,
keep_audio: false,
gif_dither: GifDither::FloydSteinberg,
let budget = encode::GifBudgetInput {
gif_colors: request.gif_colors.unwrap_or(256),
webm_codec: WebmCodec::Vp9,
mp4_codec: Mp4Codec::H264,
scratch_dir: PathBuf::new(),
crop: None,
target_bytes: request.target_bytes,
fps: request.fps,
duration_secs: clip.duration_secs,
gif_budget_mode: request.gif_budget_mode,
deleted_frame_indices: vec![],
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
clip_width: clip.width,
clip_height: clip.height,
progress_tx: None,
};
let (w, _) = encode::gif_params(&req, clip.width, clip.height);
let (w, _) = encode::gif_params(&budget, clip.width, clip.height);
w
} else {
clip.width.min(1280).max(160)
@@ -781,15 +763,14 @@ const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
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<bool> = 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<AtomicBool>) {
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::<RECT>() 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::<RECT>() 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<CaptureRect, String> {
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::<RECT>() 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<CaptureRect, String> {
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<CaptureRect, String> {
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 };