// Tauri deserializes every #[tauri::command] argument from the JS call and hands // it over by value - State<'_, T>, AppHandle, String, the request structs. // Taking them by reference would break the generated command wrapper, so the // by-value signatures below are required rather than incidental. #![allow( clippy::needless_pass_by_value, reason = "tauri::command arguments are passed by value by the generated wrapper" )] // The remaining `exit` hit is inside tauri::generate_context! itself, so it can // only be silenced at crate scope; app.exit in this code is deliberate (see // apply_update). #![allow( clippy::exit, reason = "bounded by the tauri macro expansion, which exits on its own terms" )] mod audio; mod bootstrap; mod capture; mod clicks; mod config; mod encode; mod timed_video; mod updates; mod window_picker; mod windows_list; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; use std::str::FromStr; use tauri::{AppHandle, Emitter, Manager, State}; use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter}; use crate::bootstrap::FfmpegStatus; use crate::config::{CaptureConfig, CaptureQuality, Config, Format, GifBudgetMode, GifDither}; fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| { tracing::warn!("mutex poisoned, recovering"); e.into_inner() }) } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub struct CaptureRect { pub x: i32, pub y: i32, pub width: u32, pub height: u32, } pub struct AppState { pub app_dir: PathBuf, pub config: Mutex, pub capture: Mutex>, audio: Mutex>, pub click_recorder: Mutex>, pub last_clip: Mutex>, unexported_clip: AtomicBool, pub session: Mutex>, capture_transition: Mutex<()>, pub picker: Mutex>, pub overlay_poll_shutdown: Arc, pub export_cancel: Arc, pub exporting: Arc, thumbnail_operation: Mutex<()>, pub overlay_aspect_ratio: Mutex>, /// (active flag, condvar) so the overlay click-through poll thread can park /// itself when no overlay is on screen instead of waking every 80ms. /// `show_overlay/hide_overlay` flip the flag and notify. pub overlay_poll_live: Arc<(Mutex, std::sync::Condvar)>, } pub struct SessionState { pub segments: Vec, audio_segments: Vec, next_audio_index: usize, pub total_recorded_secs: f64, pub capture_cursor: bool, pub audio: bool, rate_limit: Option, quality: CaptureQuality, pub crop: Option, pub width: u32, pub height: u32, pub monitor_width: u32, pub monitor_height: u32, pub clicks: Vec, pub segment_start_offsets: Vec, } impl AppState { fn begin_capture_transition(&self) -> Result, String> { self.capture_transition .try_lock() .map_err(|_| "a capture operation is already in progress".to_string()) } } #[derive(Debug, Clone, Serialize)] pub struct RecordedClip { pub temp_path: PathBuf, pub duration_secs: f64, pub width: u32, pub height: u32, pub monitor_width: u32, pub monitor_height: u32, pub crop: Option, pub clicks: Vec, } fn exe_dir() -> Result { let exe = std::env::current_exe()?; Ok(exe .parent() .ok_or_else(|| anyhow!("exe has no parent directory"))? .to_path_buf()) } fn temp_dir(app_dir: &Path) -> PathBuf { app_dir.join("temp") } fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf { cfg.output_dir .clone() .unwrap_or_else(|| app_dir.join("output")) } fn timestamp_slug() -> String { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs() .to_string() } fn ext_for(format: Format) -> &'static str { match format { Format::Gif => "gif", Format::Webm => "webm", Format::Mp4 => "mp4", } } #[derive(Serialize)] struct AppStatus { ffmpeg: FfmpegStatus, needs_first_run: bool, } #[tauri::command] fn get_status(state: State<'_, AppState>) -> AppStatus { let cfg = lock(&state.config); AppStatus { ffmpeg: bootstrap::check(&state.app_dir), needs_first_run: cfg.needs_first_run(), } } #[tauri::command] fn get_config(state: State<'_, AppState>) -> Config { lock(&state.config).clone() } fn parse_shortcut(s: &str) -> Option { Shortcut::from_str(s).ok() } /// Result of attempting to register all hotkeys. /// Each field is None if the hotkey was not set, or Some(true/false) for success/failure. #[derive(Debug, Clone, Serialize)] pub struct HotkeyRegistrationResult { pub start_ok: Option, pub stop_ok: Option, pub pause_ok: Option, } fn register_hotkeys(app: &AppHandle, cfg: &Config) -> HotkeyRegistrationResult { let gs = app.global_shortcut(); drop(gs.unregister_all()); let start_ok = cfg .hotkeys .start .as_deref() .and_then(parse_shortcut) .map(|sc| gs.register(sc).is_ok()); let stop_ok = cfg .hotkeys .stop .as_deref() .and_then(parse_shortcut) .map(|sc| gs.register(sc).is_ok()); let pause_ok = cfg .hotkeys .pause .as_deref() .and_then(parse_shortcut) .map(|sc| gs.register(sc).is_ok()); HotkeyRegistrationResult { start_ok, stop_ok, pause_ok, } } #[derive(Serialize)] struct SaveConfigResult { hotkey_result: HotkeyRegistrationResult, } fn validate_config(config: &Config) -> Result<(), String> { let mut keys = Vec::new(); if let Some(k) = config .hotkeys .start .as_deref() .filter(|s| !s.trim().is_empty()) { keys.push(("start", k)); } if let Some(k) = config .hotkeys .stop .as_deref() .filter(|s| !s.trim().is_empty()) { keys.push(("stop", k)); } if let Some(k) = config .hotkeys .pause .as_deref() .filter(|s| !s.trim().is_empty()) { keys.push(("pause", k)); } for (i, (a, ka)) in keys.iter().enumerate() { for (b, kb) in keys.iter().skip(i + 1) { if ka.eq_ignore_ascii_case(kb) { return Err(format!("duplicate hotkey: {a} and {b} both use {ka}")); } } } Ok(()) } #[tauri::command] fn save_config( app: AppHandle, state: State<'_, AppState>, config: Config, ) -> Result { validate_config(&config)?; let path = config::config_path(&state.app_dir); config.save(&path).map_err(|e| format!("{e:#}"))?; *lock(&state.config) = config.clone(); let hotkey_result = register_hotkeys(&app, &config); Ok(SaveConfigResult { hotkey_result }) } #[derive(Clone, Serialize)] struct DownloadProgress { downloaded: u64, total: Option, } type UpdateDownloadProgress = DownloadProgress; #[tauri::command] async fn download_update( app: AppHandle, state: State<'_, AppState>, url: String, ) -> Result<(), String> { let app_handle = app.clone(); updates::download(&url, &state.app_dir, move |downloaded, total| { drop(app_handle.emit( "update-download-progress", UpdateDownloadProgress { downloaded, total }, )); }) .await .map_err(|e| format!("{e:#}")) } // Tauri's app.exit is how this process is meant to hand over to the apply // script; the updater cannot replace a running exe, so exiting is the point. #[allow( clippy::exit, reason = "app.exit is the intended way to let the update script replace the running exe" )] #[tauri::command] fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { if state.capture_transition.try_lock().is_err() || lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst) || state.unexported_clip.load(Ordering::Relaxed) { return Err("finish or discard the current recording before applying the update".to_string()); } let _operation = updates::UpdateOperation::begin().map_err(|e| format!("{e:#}"))?; updates::start_install(&state.app_dir).map_err(|e| format!("{e:#}"))?; app.exit(0); Ok(()) } #[tauri::command] fn pending_update(state: State<'_, AppState>) -> bool { updates::has_pending_update(&state.app_dir) } #[tauri::command] async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { let app_dir = state.app_dir.clone(); let app_handle = app.clone(); bootstrap::download(&app_dir, move |downloaded, total| { drop(app_handle.emit("ffmpeg-progress", DownloadProgress { downloaded, total })); }) .await .map_err(|e| format!("{e:#}")) } #[derive(Debug, Deserialize)] pub struct StartCaptureRequest { pub crop: Option, pub options: Option, } fn segment_path(app_dir: &Path, idx: usize) -> PathBuf { temp_dir(app_dir).join(format!("segment-{idx:03}.mp4")) } fn audio_segment_path(app_dir: &Path, idx: usize) -> PathBuf { temp_dir(app_dir).join(format!("audio-{idx:03}.pcm")) } /// Remove temporary recording artifacts (segments, previews, thumbs). /// /// `keep_previews` is set when a capture starts mid-session: the frontend can /// still be holding a live `convertFileSrc` URL for preview.png or /// raw-preview.png from the previous clip, and deleting them under it made the /// asset protocol log "file does not exist" and briefly broke the preview. /// Startup and exit sweep everything. /// Case-insensitive extension test, for the temp sweeps: Windows file names are /// case-preserving, so `ends_with(".mp4")` would miss `SEGMENT-001.MP4`. fn has_ext(name: &str, ext: &str) -> bool { Path::new(name) .extension() .is_some_and(|e| e.eq_ignore_ascii_case(ext)) } fn clear_temp_segments(app_dir: &Path, keep_previews: bool) { let temp = temp_dir(app_dir); if let Ok(entries) = std::fs::read_dir(&temp) { for entry in entries.flatten() { if let Some(name) = entry.file_name().to_str() { // The padtmp files carry a double extension, so they are matched // on the whole name rather than through Path::extension. let padtmp = name.to_ascii_lowercase().ends_with(".pcm.padtmp"); if ((name.starts_with("segment-") || name.starts_with("preview-edit-") || name.starts_with("recording-")) && has_ext(name, "mp4")) || (name.starts_with("output-review-") && ["gif", "webm", "mp4"].iter().any(|ext| has_ext(name, ext))) || (name.starts_with("audio-") && has_ext(name, "pcm")) || (name.starts_with("preview-palette-") && has_ext(name, "png")) // Two-pass stats, named ffmpeg2pass-0.log and its .mbtree // sibling. cleanup_pass_logs only runs on a successful // encode, so a cancelled one left them here forever. || name.starts_with("ffmpeg2pass") || padtmp { drop(std::fs::remove_file(entry.path())); } } } } drop(std::fs::remove_file(temp.join("recording.mp4"))); drop(std::fs::remove_file(temp.join("video-concat.mp4"))); drop(std::fs::remove_file(temp.join("audio-concat.pcm"))); let thumbs = temp.join("thumbs"); if thumbs.is_dir() { drop(std::fs::remove_dir_all(&thumbs)); } if !keep_previews { drop(std::fs::remove_file(temp.join("preview.png"))); drop(std::fs::remove_file(temp.join("raw-preview.png"))); } } struct ActiveAudio { session: audio::AudioSession, start_secs: f64, } impl ActiveAudio { fn stop(self, end_secs: f64) -> encode::AudioSegment { let sample_rate = self.session.sample_rate; let channels = self.session.channels; encode::AudioSegment { path: self.session.stop(), sample_rate, channels, start_secs: self.start_secs, end_secs, } } } fn try_start_audio( app: &AppHandle, audio_path: PathBuf, video_started_at: std::time::Instant, segment_start_secs: f64, ) -> Option { let handle = app.clone(); match audio::start(audio_path, move |status| match status { Ok(()) => drop(handle.emit("audio-recovered", ())), Err(message) => drop(handle.emit("audio-failed", message)), }) { Ok(session) => { let start_secs = segment_start_secs + session .started_at .saturating_duration_since(video_started_at) .as_secs_f64(); Some(ActiveAudio { session, start_secs }) } Err(e) => { tracing::warn!("audio capture failed: {e:#}"); drop(app.emit("audio-failed", format!("{e:#}"))); None } } } fn finish_audio(state: &AppState, end_secs: f64) -> Option { let audio = lock(&state.audio).take()?; Some(audio.stop(end_secs)) } fn start_click_recorder(enabled: bool) -> Option { if enabled { Some(clicks::start()) } else { None } } #[tauri::command] fn start_capture( app: AppHandle, state: State<'_, AppState>, request: Option, ) -> Result<(), String> { let _transition = state.begin_capture_transition()?; if state.exporting.load(Ordering::SeqCst) { return Err("wait for the current output operation".to_string()); } { let slot = lock(&state.capture); if slot.is_some() { return Err("a capture is already running".to_string()); } } let options = request.as_ref().and_then(|request| request.options.clone()) .unwrap_or_else(|| lock(&state.config).capture.clone()); let rate_limit = options.limit_capture_fps.then(|| options.default_fps.clamp(1, 60)); let temp = temp_dir(&state.app_dir); std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e:#}"))?; let _thumbnails = state.thumbnail_operation.try_lock() .map_err(|_| "wait for thumbnail generation to finish".to_string())?; *lock(&state.last_clip) = None; state.unexported_clip.store(false, Ordering::Relaxed); clear_temp_segments(&state.app_dir, true); let crop = request.as_ref().and_then(|r| r.crop); let output = segment_path(&state.app_dir, 1); let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found - run the encoder setup first".to_string()); } let (monitor_w, monitor_h) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?; let session = capture::start( output, ffmpeg, options.capture_cursor, crop, rate_limit, options.capture_quality, ) .map_err(|e| format!("{e:#}"))?; let audio_session = if options.capture_audio { let path = audio_segment_path(&state.app_dir, 1); try_start_audio(&app, path, session.started_at, 0.0) } else { None }; let session_state = SessionState { segments: Vec::new(), audio_segments: Vec::new(), next_audio_index: 2, total_recorded_secs: 0.0, capture_cursor: options.capture_cursor, audio: options.capture_audio, rate_limit, quality: options.capture_quality, crop: session.crop, width: session.width, height: session.height, monitor_width: monitor_w, monitor_height: monitor_h, clicks: Vec::new(), segment_start_offsets: vec![0.0], }; let click_rec = start_click_recorder(options.capture_cursor); *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(async)] fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { let _transition = state.begin_capture_transition()?; let session = lock(&state.capture) .take() .ok_or_else(|| "no capture in progress".to_string())?; let end = std::time::Instant::now(); session.mark_stopped_at(end); let elapsed = end.saturating_duration_since(session.started_at).as_secs_f64(); let previously_recorded = lock(&state.session) .as_ref() .ok_or_else(|| "no session state".to_string())? .total_recorded_secs; let audio = finish_audio(&state, previously_recorded + elapsed); let path = session.stop().map_err(|e| format!("{e:#}"))?; let new_clicks: Vec = lock(&state.click_recorder) .take() .map(clicks::ClickRecorder::stop) .unwrap_or_default(); let mut ss = lock(&state.session); let ss = ss.as_mut().ok_or_else(|| "no session state".to_string())?; let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0); for c in new_clicks { ss.clicks.push(clicks::Click { time_secs: offset + c.time_secs, ..c }); } ss.segments.push(path); if let Some(audio) = audio { ss.audio_segments.push(audio); } ss.total_recorded_secs += elapsed; ss.segment_start_offsets.push(ss.total_recorded_secs); Ok(()) } #[tauri::command] fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { let _transition = state.begin_capture_transition()?; { 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, audio_idx, segment_start_secs, rate_limit, quality) = { let mut ss = lock(&state.session); let ss = ss .as_mut() .ok_or_else(|| "no session to resume".to_string())?; let audio_idx = ss.next_audio_index; ss.next_audio_index += 1; ( ss.capture_cursor, ss.audio, ss.crop, ss.segments.len() + 1, audio_idx, ss.total_recorded_secs, ss.rate_limit, ss.quality, ) }; let output = segment_path(&state.app_dir, next_idx); let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found".to_string()); } let session = capture::start(output, ffmpeg, capture_cursor, crop, rate_limit, quality) .map_err(|e| format!("{e:#}"))?; let audio_session = if audio { let path = audio_segment_path(&state.app_dir, audio_idx); try_start_audio(&app, path, session.started_at, segment_start_secs) } else { None }; let click_rec = start_click_recorder(capture_cursor); *lock(&state.capture) = Some(session); *lock(&state.audio) = audio_session; *lock(&state.click_recorder) = click_rec; Ok(()) } /// Restart the audio capture mid-recording. Used when the initial WASAPI /// session failed (e.g. endpoint was busy) and the user wants to retry /// without ending the recording. Stops the current session, appends its /// pcm segment to the session, and starts a new one with a fresh file. #[tauri::command] fn restart_audio_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { let _transition = state.begin_capture_transition()?; let started_at = lock(&state.capture) .as_ref() .ok_or_else(|| "resume recording before retrying audio".to_string())? .started_at; let (next_idx, segment_start_secs) = { let mut ss = lock(&state.session); let ss = ss .as_mut() .ok_or_else(|| "no session in progress".to_string())?; if !ss.audio { return Err("audio is not enabled for this recording".to_string()); } let end_secs = ss.total_recorded_secs + started_at.elapsed().as_secs_f64(); if let Some(audio) = finish_audio(&state, end_secs) { ss.audio_segments.push(audio); } let next_idx = ss.next_audio_index; ss.next_audio_index += 1; (next_idx, ss.total_recorded_secs) }; let audio_path = audio_segment_path(&state.app_dir, next_idx); let audio = try_start_audio(&app, audio_path, started_at, segment_start_secs); *lock(&state.audio) = audio; Ok(()) } #[allow( clippy::too_many_lines, reason = "one recording-finalisation transaction; the steps share session state and temp paths" )] #[tauri::command(async)] fn stop_capture(state: State<'_, AppState>) -> Result { let _transition = state.begin_capture_transition()?; let mut ss = lock(&state.session) .take() .ok_or_else(|| "no session to stop".to_string())?; let live = lock(&state.capture).take(); if let Some(session) = live { let end = std::time::Instant::now(); session.mark_stopped_at(end); ss.total_recorded_secs += end.saturating_duration_since(session.started_at).as_secs_f64(); if let Some(audio) = finish_audio(&state, ss.total_recorded_secs) { ss.audio_segments.push(audio); } ss.segments.push(session.stop().map_err(|e| format!("{e:#}"))?); } let live_clicks = lock(&state.click_recorder) .take() .map(clicks::ClickRecorder::stop) .unwrap_or_default(); let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0); for c in live_clicks { ss.clicks.push(clicks::Click { time_secs: offset + c.time_secs, ..c }); } if ss.segments.is_empty() { return Err("no recorded segments".to_string()); } let temp = temp_dir(&state.app_dir); let final_path = temp.join(format!("recording-{}.mp4", timestamp_slug())); let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); let video_concat = if ss.segments.len() == 1 { ss.segments.remove(0) } else { if !ffmpeg.is_file() { return Err("ffmpeg.exe not found for concatenation".to_string()); } let vc = temp.join("video-concat.mp4"); encode::concat_segments(&ffmpeg, &ss.segments, &vc) .map_err(|e| format!("concat: {e:#}"))?; for seg in &ss.segments { drop(std::fs::remove_file(seg)); } vc }; let audio_concat = temp.join("audio-concat.pcm"); let audio_format = encode::assemble_pcm( &ffmpeg, &ss.audio_segments, &audio_concat, ss.total_recorded_secs, ) .map_err(|e| format!("assembling audio: {e:#}"))?; if let Some((sample_rate, channels)) = audio_format { encode::mux_with_audio( &ffmpeg, &video_concat, &audio_concat, sample_rate, channels, &final_path, ) .map_err(|e| format!("mux: {e:#}"))?; if video_concat != final_path { drop(std::fs::remove_file(&video_concat)); } } else { // No audio to mux. `video_concat` is either the one segment or the // concat output, and `final_path` is always recording.mp4, so it always // needs moving into place. std::fs::rename(&video_concat, &final_path) .or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ())) .map_err(|e| format!("finalizing: {e:#}"))?; drop(std::fs::remove_file(&video_concat)); } drop(std::fs::remove_file(&audio_concat)); for audio in &ss.audio_segments { drop(std::fs::remove_file(&audio.path)); } let clip = RecordedClip { temp_path: final_path, duration_secs: ss.total_recorded_secs, width: ss.width, height: ss.height, monitor_width: ss.monitor_width, monitor_height: ss.monitor_height, crop: ss.crop, clicks: ss.clicks.clone(), }; *lock(&state.last_clip) = Some(clip.clone()); state.unexported_clip.store(true, Ordering::Relaxed); Ok(clip) } #[tauri::command] fn discard_clip(state: State<'_, AppState>) -> Result<(), String> { let _transition = state.begin_capture_transition()?; if state.exporting.load(Ordering::SeqCst) { return Err("wait for the current preview or export".to_string()); } *lock(&state.last_clip) = None; state.unexported_clip.store(false, Ordering::Relaxed); Ok(()) } #[derive(Debug, Deserialize)] pub struct ExportRequest { pub format: Format, pub target_bytes: u64, pub fps: u32, pub keep_audio: bool, #[serde(default)] pub deleted_frame_indices: Vec, #[serde(default)] pub trim_start_secs: Option, #[serde(default)] pub trim_end_secs: Option, #[serde(default)] pub output_path: Option, #[serde(default)] pub crop: Option, #[serde(default)] pub gif_budget_mode: GifBudgetMode, #[serde(default)] pub gif_dither: Option, #[serde(default)] pub gif_colors: Option, } #[tauri::command] fn default_output_path(state: State<'_, AppState>, format: Format) -> String { let dir = output_dir(&state.app_dir, &lock(&state.config)); dir.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format))) .to_string_lossy() .into_owned() } #[derive(Debug, Deserialize)] pub struct PreviewRequest { pub format: Format, pub fps: u32, pub target_bytes: u64, #[serde(default)] pub gif_budget_mode: GifBudgetMode, #[serde(default)] pub gif_dither: Option, #[serde(default)] pub gif_colors: Option, /// Optional clip dimensions/duration. Required by `estimate_gif_params`, /// unused by `render_preview` (which uses the current `last_clip`). #[serde(default)] pub clip_width: u32, #[serde(default)] pub clip_height: u32, #[serde(default)] pub duration_secs: Option, } #[tauri::command(async)] fn render_preview(state: State<'_, AppState>, request: PreviewRequest) -> Result { let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found".to_string()); } let target_width: u32 = if request.format == Format::Gif { let budget = encode::GifBudgetInput { gif_colors: request.gif_colors.unwrap_or(256), target_bytes: request.target_bytes, fps: request.fps, duration_secs: clip.duration_secs, gif_budget_mode: request.gif_budget_mode, }; let (w, _) = encode::gif_params(&budget, clip.width, clip.height); w } else { clip.width.clamp(160, 1280) }; let preview_path = temp_dir(&state.app_dir).join("preview.png"); let midpoint = (clip.duration_secs / 2.0).max(0.0); if request.format == Format::Gif { let dither_str = match request.gif_dither.unwrap_or(GifDither::FloydSteinberg) { GifDither::FloydSteinberg => "floyd_steinberg", GifDither::Bayer => "bayer:bayer_scale=3", GifDither::None => "none", }; encode::render_gif_preview( &ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width, request.gif_colors.unwrap_or(256), dither_str, clip.duration_secs, ) .map_err(|e| format!("{e:#}"))?; } else { encode::render_preview( &ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width, ) .map_err(|e| format!("{e:#}"))?; } Ok(preview_path) } #[derive(Debug, Serialize)] pub struct GifEstimate { pub width: u32, pub fps: u32, pub height: u32, pub dims_label: String, } #[derive(Debug, Serialize)] pub struct GifEstimateTable { /// Sorted ascending. Frontend interpolates between points. pub points: Vec, } #[derive(Debug, Serialize)] pub struct GifEstimatePoint { pub target_bytes: u64, pub width: u32, pub fps: u32, pub height: u32, } #[tauri::command] fn estimate_gif_params(request: PreviewRequest) -> GifEstimate { let budget = encode::GifBudgetInput { gif_colors: request.gif_colors.unwrap_or(256), target_bytes: request.target_bytes, fps: request.fps, duration_secs: request.duration_secs.unwrap_or(0.0), gif_budget_mode: request.gif_budget_mode, }; let (w, fps) = encode::gif_params(&budget, request.clip_width, request.clip_height); let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height); let dims_label = format!("{w}x{height} @ {fps}fps"); GifEstimate { width: w, fps, height, dims_label, } } /// Geometric grid from 100KB to 200MB, used to sample the GIF size estimator /// across a range of targets so the frontend can interpolate locally. const GIF_ESTIMATE_GRID: &[u64] = &[ 100_000, 200_000, 500_000, 1_048_576, 2_097_152, 5_242_880, 10_485_760, 20_971_520, 52_428_800, 104_857_600, 209_715_200, ]; /// The size-table scan sweeps target sizes itself, so it needs only the inputs /// that shape a GIF budget - not the single requested target that /// `PreviewRequest` requires. #[derive(Debug, Deserialize)] pub struct GifTableRequest { pub fps: u32, #[serde(default)] pub gif_budget_mode: GifBudgetMode, #[serde(default)] pub gif_colors: Option, #[serde(default)] pub clip_width: u32, #[serde(default)] pub clip_height: u32, #[serde(default)] pub duration_secs: Option, } /// Return estimates for a grid of `target_bytes` values so the frontend can /// interpolate on slider drag without an IPC per debounce tick. The grid is /// geometric from 100KB to 200MB. #[tauri::command] fn estimate_gif_params_table(request: GifTableRequest) -> GifEstimateTable { let colors = request.gif_colors.unwrap_or(256); let dur = request.duration_secs.unwrap_or(0.0).max(0.1); let fps = request.fps; let mode = request.gif_budget_mode; let mut points = Vec::with_capacity(GIF_ESTIMATE_GRID.len()); for &target in GIF_ESTIMATE_GRID { let budget = encode::GifBudgetInput { gif_colors: colors, target_bytes: target, fps, duration_secs: dur, gif_budget_mode: mode, }; let (w, f) = encode::gif_params(&budget, request.clip_width, request.clip_height); let h = encode::gif_height_for_width(w, request.clip_width, request.clip_height); points.push(GifEstimatePoint { target_bytes: target, width: w, fps: f, height: h, }); } GifEstimateTable { points } } #[cfg(test)] mod tests { // Tests fail by panicking, which is the harness contract; unwrap and expect // are denied to keep panics out of the shipping paths. #![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")] use super::*; fn make_request(target_bytes: u64, fps: u32, mode: GifBudgetMode) -> PreviewRequest { PreviewRequest { format: Format::Gif, fps, target_bytes, gif_budget_mode: mode, gif_dither: Some(GifDither::FloydSteinberg), gif_colors: Some(256), clip_width: 1920, clip_height: 1080, duration_secs: Some(5.0), } } /// Windows keeps whatever case a name was created with, so the temp sweep /// matches extensions case-insensitively. It used to compare with /// `ends_with(".mp4")`, which silently missed an upper-case recording. #[test] fn extension_match_ignores_case() { assert!(has_ext("segment-001.mp4", "mp4")); assert!(has_ext("SEGMENT-001.MP4", "mp4")); assert!(has_ext("Segment-001.Mp4", "mp4")); assert!(!has_ext("segment-001.mkv", "mp4")); assert!(!has_ext("segment-001", "mp4")); assert!(!has_ext("notsegment.mp4.bak", "mp4")); } /// The pcm head-padding step writes a sibling `*.pcm.padtmp` next to the /// concatenated audio. It used to fall outside every sweep pattern, so a /// crash mid-pad left a file the size of the whole audio track in temp/. #[test] fn sweep_removes_padtmp_but_spares_previews_mid_session() { let dir = std::env::temp_dir().join(format!("bytesize-sweep-test-{}", std::process::id())); let temp = dir.join("temp"); drop(std::fs::remove_dir_all(&dir)); std::fs::create_dir_all(&temp).unwrap(); for name in [ "audio-concat.pcm.padtmp", "segment-001.mp4", "audio-001.pcm", "preview.png", "raw-preview.png", "ffmpeg2pass-0.log", "ffmpeg2pass-0.log.mbtree", ] { std::fs::write(temp.join(name), b"x").unwrap(); } // Mid-session: drop the recording artifacts, keep the live previews. clear_temp_segments(&dir, true); assert!( !temp.join("audio-concat.pcm.padtmp").exists(), "padtmp should be swept" ); assert!(!temp.join("segment-001.mp4").exists()); assert!(!temp.join("audio-001.pcm").exists()); assert!( !temp.join("ffmpeg2pass-0.log").exists(), "pass stats should be swept" ); assert!(!temp.join("ffmpeg2pass-0.log.mbtree").exists()); assert!( temp.join("preview.png").exists(), "preview must survive a new capture" ); assert!(temp.join("raw-preview.png").exists()); // Exit/startup: everything goes. clear_temp_segments(&dir, false); assert!(!temp.join("preview.png").exists()); assert!(!temp.join("raw-preview.png").exists()); drop(std::fs::remove_dir_all(&dir)); } #[test] fn estimate_balanced_matches_gif_params() { // The frontend uses estimate_gif_params for the on-screen dims label. // The backend uses gif_params for the actual encode. The two must agree. let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced); let est = estimate_gif_params(req); let budget = encode::GifBudgetInput { gif_colors: 256, target_bytes: 8 * 1024 * 1024, fps: 30, duration_secs: 5.0, gif_budget_mode: GifBudgetMode::Balanced, }; let (encode_w, encode_fps) = encode::gif_params(&budget, 1920, 1080); assert_eq!(est.width, encode_w); assert_eq!(est.fps, encode_fps); // height should be a multiple of 2 and within aspect assert_eq!(est.height % 2, 0); let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080); assert_eq!(est.height, expected_height); // dims_label should be "{w}x{h} @ {fps}fps" assert_eq!( est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps) ); } #[test] fn estimate_zero_height_falls_back_aspect() { let mut req = make_request(1024, 30, GifBudgetMode::Balanced); req.clip_height = 0; let est = estimate_gif_params(req); // Should not panic and should produce some height assert!(est.height > 0 || est.width == 0); } } #[tauri::command(async)] fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result, String> { let _thumbnails = lock(&state.thumbnail_operation); let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found".to_string()); } let thumbs_dir = temp_dir(&state.app_dir).join("thumbs"); encode::extract_thumbnails(&ffmpeg, &clip.temp_path, &thumbs_dir, fps, clip.crop) .map_err(|e| format!("{e:#}")) } #[tauri::command(async)] fn render_raw_preview(state: State<'_, AppState>, timestamp: f64) -> Result { let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found".to_string()); } let out_path = temp_dir(&state.app_dir).join("raw-preview.png"); encode::render_preview( &ffmpeg, &clip.temp_path, &out_path, timestamp, clip.width.min(1280), ) .map_err(|e| format!("{e:#}"))?; Ok(out_path) } #[derive(Debug, Serialize)] pub struct ExportResult { pub output_path: PathBuf, pub size_bytes: u64, pub target_bytes: u64, pub met_target: bool, } const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0; const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0; /// Remove temporary recording artifacts (segments, previews, thumbs). /// Called on app exit so a discarded clip doesn't linger in `temp/`. fn cleanup_temp_on_exit(app: &AppHandle) { let Some(st) = app.try_state::() else { return; }; clear_temp_segments(&st.app_dir, false); } /// Keep click-through decisions in the poller so its cached state stays current. fn lock_instance(app_dir: &Path) -> std::io::Result { use std::os::windows::fs::OpenOptionsExt; let temp = temp_dir(app_dir); std::fs::create_dir_all(&temp)?; std::fs::OpenOptions::new() .write(true) .create(true) .truncate(false) .share_mode(0) .open(temp.join("instance.lock")) } fn close_main(window: &tauri::Window) { use windows::core::w; use windows::Win32::Foundation::HWND; use windows::Win32::UI::WindowsAndMessaging::{ MessageBoxW, IDYES, MB_DEFBUTTON2, MB_ICONINFORMATION, MB_ICONWARNING, MB_OK, MB_YESNO, }; let state = window.state::(); let app = window.app_handle(); let owner = window.hwnd().ok().map(|handle| HWND(handle.0)); let transitioning = state.capture_transition.try_lock().is_err(); if transitioning || lock(&state.session).is_some() || state.exporting.load(Ordering::SeqCst) || state.thumbnail_operation.try_lock().is_err() { // SAFETY: The owner is the main window. Both strings have static storage. unsafe { MessageBoxW(owner, w!("Stop recording or wait for the current export, preview, or frame thumbnails before closing."), w!("ByteSize"), MB_OK | MB_ICONINFORMATION); } return; } if lock(&state.last_clip).is_some() && state.unexported_clip.load(Ordering::Relaxed) { // SAFETY: The owner is the main window. Both strings have static storage. let response = unsafe { MessageBoxW(owner, w!("Discard the current recording and close ByteSize?"), w!("ByteSize"), MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) }; if response != IDYES { return; } } app.exit(0); } /// Keep click-through decisions in the poller so its cached state stays current. fn overlay_should_ignore_cursor(app: &AppHandle) -> Option { use windows::Win32::Foundation::{HWND, POINT}; use windows::Win32::UI::HiDpi::GetDpiForWindow; use windows::Win32::UI::WindowsAndMessaging::GetCursorPos; let overlay = app.get_webview_window("overlay")?; if !overlay.is_visible().unwrap_or(false) { 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 mut pt = POINT::default(); // SAFETY: `pt` is a live local that GetCursorPos writes through. if unsafe { GetCursorPos(&raw mut pt) }.is_err() { return None; } let raw = overlay.hwnd().ok()?; let (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)?; // SAFETY: `raw` is the overlay's own live HWND from Tauri. let dpi = unsafe { GetDpiForWindow(HWND(raw.0.cast::())) }; let scale = if dpi > 0 { f64::from(dpi) / 96.0 } else { 1.0 }; let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale); let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale); // The border and titlebar stay interactive so the frame can still be dragged // and resized; only the capture area itself passes clicks through. let inner_left = vl + border; let inner_top = vt + border + titlebar; 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) } fn start_overlay_clickthrough_poll( app: AppHandle, shutdown: Arc, live: Arc<(Mutex, std::sync::Condvar)>, ) { use std::time::Duration; std::thread::spawn(move || { let mut last: Option = None; while !shutdown.load(Ordering::Relaxed) { // Park until the overlay is shown. Without this the poller woke // every 80ms for the whole process lifetime just to re-check // visibility; now it sleeps on the condvar until show_overlay // flips the flag and notifies. { let (lock, cvar) = &*live; let mut active = lock .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); while !*active && !shutdown.load(Ordering::Relaxed) { let (g, _timeout) = cvar .wait_timeout(active, Duration::from_secs(1)) .unwrap_or_else(std::sync::PoisonError::into_inner); active = g; } } let target = overlay_should_ignore_cursor(&app); if target != last { if let (Some(overlay), Some(value)) = (app.get_webview_window("overlay"), target) { drop(overlay.set_ignore_cursor_events(value)); } last = target; } // The only sleep in the loop, and deliberately unconditional: every // branch above has to pace itself, or the thread spins at full speed // for the whole recording. std::thread::sleep(Duration::from_millis(80)); } }); } fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(), String> { use windows::Win32::Foundation::HWND; use windows::Win32::UI::WindowsAndMessaging::{ SetWindowDisplayAffinity, WDA_EXCLUDEFROMCAPTURE, }; let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?; let hwnd = HWND(raw.0.cast::()); // SAFETY: `hwnd` is the overlay's live window handle and the affinity flag // is a plain enum with no pointer arguments. unsafe { SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) .map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?; } Ok(()) } #[tauri::command] fn show_overlay(app: AppHandle) -> Result<(), String> { use windows::Win32::Foundation::{HWND, POINT}; use windows::Win32::Graphics::Gdi::{ GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY, }; use windows::Win32::UI::WindowsAndMessaging::{ SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, }; let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; win.show().map_err(|e| format!("showing overlay: {e:#}"))?; drop(mark_overlay_excluded_from_capture(&win)); // Wake the click-through poll thread out of its parked state. { let st = app.state::(); let (lock, cvar) = &*st.overlay_poll_live; *lock .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = true; cvar.notify_one(); } // 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) { let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb), }; // MonitorFromPoint only reads the POINT by value and returns null // for "no monitor", which the next branch handles. // // SAFETY: the POINTs passed in are plain values constructed here. let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) }; if hmon.0.is_null() { let hwnd = HWND(raw.0.cast::()); // SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot // fail on a running desktop. let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) }; // cbSize is required by GetMonitorInfoW and is set from the // actual struct size, so the write below stays in bounds. let mut mi = MONITORINFO { cbSize: u32::try_from(size_of::()).unwrap_or(0), ..Default::default() }; // SAFETY: `mi` is a live local of the declared size, and the // result is checked with as_bool() before mi is read. if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() { let work = mi.rcWork; let w = vr - vl; let h = vb - vt; let cx = i32::midpoint(work.left, work.right) - w / 2; let cy = i32::midpoint(work.top, work.bottom) - h / 2; drop( // SAFETY: `hwnd` is the overlay's live handle; the flags // keep this a size-only, non-activating move. unsafe { SetWindowPos( hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE, ) }, ); } } } } win.set_focus().map_err(|e| format!("setting focus: {e:#}")) } #[tauri::command] fn hide_overlay(app: AppHandle) -> Result<(), String> { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; // Leave the click-through state alone - it is the poll thread's to own, and // it stays consistent with the window because nothing else writes it. Just // park the poller until show_overlay wakes it again. { let st = app.state::(); let (lock, cvar) = &*st.overlay_poll_live; *lock .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = false; cvar.notify_one(); } win.hide().map_err(|e| format!("hiding overlay: {e:#}")) } #[tauri::command] fn set_overlay_size( app: AppHandle, state: State<'_, AppState>, width: u32, height: u32, ) -> Result<(), String> { use tauri::{LogicalSize, Size}; let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; let ratio = lock(&state.overlay_aspect_ratio); let (w, mut h) = (f64::from(width), f64::from(height)); if let Some(r) = *ratio { h = w / r; } 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| format!("setting overlay size: {e:#}"))?; Ok(()) } #[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:#}"))?; } } Ok(()) } #[tauri::command] fn get_overlay_aspect(state: State<'_, AppState>) -> Option { *lock(&state.overlay_aspect_ratio) } #[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, }; 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 } // 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(()) } #[tauri::command] fn list_windows() -> Vec { windows_list::list_visible_windows() } #[tauri::command] 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:#}"))?; let mut exclude: Vec = Vec::new(); for label in &["main", "overlay", "picker"] { if let Some(w) = app.get_webview_window(label) { if let Ok(h) = w.hwnd() { exclude.push(h.0 as isize); } } } 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))) .map_err(|e| format!("setting picker position: {e:#}"))?; drop(picker.set_ignore_cursor_events(false)); drop(picker.set_always_on_top(true)); 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}; use windows::Win32::UI::WindowsAndMessaging::GetWindowRect; let hwnd = HWND(h.0.cast::()); let mut gr = RECT::default(); // SAFETY: `gr` is a live local that GetWindowRect writes through. drop(unsafe { GetWindowRect(hwnd, &raw mut gr) }); let mut dr = RECT::default(); // SAFETY: `dr` is a live RECT local, the attribute is the documented // DWMWA_EXTENDED_FRAME_BOUNDS, and the size passed matches its type. drop(unsafe { DwmGetWindowAttribute( hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, (&raw mut dr).cast::().cast::(), u32::try_from(size_of::()).unwrap_or(0), ) }); tracing::debug!( "picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})", gr.left, gr.top, gr.right, gr.bottom, dr.left, dr.top, dr.right, dr.bottom ); } { let mut slot = lock(&state.picker); if let Some(existing) = slot.take() { existing.stop(); } *slot = Some(window_picker::start(app.clone(), exclude)); } Ok(()) } #[tauri::command] /// Tauri deserializes the return into a JS Result, so the wrapper stays even /// though there is no failure path. #[allow( clippy::unnecessary_wraps, reason = "Result is part of the tauri::command contract the frontend invokes" )] fn close_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { if let Some(session) = lock(&state.picker).take() { session.stop(); } if let Some(picker) = app.get_webview_window("picker") { drop(picker.hide()); } 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; 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 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, ) } /// Get the DPI scale factor for the monitor containing a given point. fn scale_factor_at_point(x: i32, y: i32) -> f64 { use windows::Win32::Foundation::POINT; use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST}; use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MONITOR_DPI_TYPE}; let pt = POINT { x, y }; // SAFETY: value-only call; a null result is handled on the next line. let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) }; if hmonitor.0.is_null() { return 1.0; } let mut dpi_x = 0u32; let mut dpi_y = 0u32; // SAFETY: both out-params are live u32 locals that the call writes through, // and `hmonitor` was checked non-null above. let hr = unsafe { GetDpiForMonitor( hmonitor, MONITOR_DPI_TYPE(0), // MdtEffectiveDpi &raw mut dpi_x, &raw mut dpi_y, ) }; if hr.is_ok() && dpi_x > 0 { f64::from(dpi_x) / 96.0 } else { 1.0 } } #[tauri::command] fn set_overlay_to_window( app: AppHandle, x: i32, y: i32, width: u32, height: u32, ) -> Result<(), String> { use windows::Win32::Foundation::HWND; use windows::Win32::UI::WindowsAndMessaging::{ SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER, }; let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".to_string())?; // Use the target monitor's scale factor, not the overlay's current one, // so border/titlebar compensation is correct when snapping across monitors. let cx = x.saturating_add(width.cast_signed() / 2); let cy = y.saturating_add(height.cast_signed() / 2); let scale = scale_factor_at_point(cx, cy); 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; // 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 // plain integer computed above; no pointers are passed. unsafe { SetWindowPos( hwnd, Some(HWND_TOP), outer_x, outer_y, outer_w.cast_signed(), outer_h.cast_signed(), SWP_NOACTIVATE | SWP_NOZORDER, ) } .map_err(|e| format!("SetWindowPos: {e}"))?; Ok(()) } #[tauri::command] fn get_overlay_rect(app: AppHandle) -> Result { let win = app .get_webview_window("overlay") .ok_or_else(|| "overlay window not found".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 (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize).ok_or_else(|| "GetWindowRect failed".to_string())?; let border_phys = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale); let titlebar_phys = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale); let inset_top = border_phys + titlebar_phys; let inset_sides = border_phys; let visible_w = vr - vl; let visible_h = vb - vt; let width = (visible_w - inset_sides * 2).max(2).cast_unsigned(); let height = (visible_h - inset_top - inset_sides).max(2).cast_unsigned(); let width = (width / 2) * 2; let height = (height / 2) * 2; Ok(CaptureRect { x: vl + inset_sides, y: vt + inset_top, width, height, }) } #[tauri::command] fn reveal_in_explorer(path: String) -> Result<(), String> { use std::os::windows::process::CommandExt; use std::process::Command; let canonical = std::fs::canonicalize(&path).ok(); let normalized = canonical .as_ref() .map_or_else(|| path.clone(), |p| p.to_string_lossy().into_owned()); let stripped = normalized .strip_prefix(r"\\?\") .unwrap_or(&normalized) .replace('/', "\\"); let select_result = Command::new("explorer.exe") .raw_arg(format!("/select,\"{stripped}\"")) .spawn(); if select_result.is_err() { let parent = Path::new(&stripped) .parent() .ok_or_else(|| "no parent dir".to_string())?; Command::new("explorer.exe") .arg(parent) .spawn() .map_err(|e| format!("opening explorer: {e:#}"))?; } Ok(()) } fn open_shell_target(target: &std::ffi::OsStr) -> Result<(), String> { use windows::core::{w, HSTRING, PCWSTR}; use windows::Win32::UI::Shell::ShellExecuteW; use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL; let target = HSTRING::from(target); // SAFETY: Both NUL-terminated strings outlive the call. let result = unsafe { ShellExecuteW( None, w!("open"), &target, PCWSTR::null(), PCWSTR::null(), SW_SHOWNORMAL, ) }; // ShellExecuteW returns an error code when the result is 32 or lower. let code = result.0 as isize; if code <= 32 { return Err(format!("opening the target failed (Windows shell error {code})")); } Ok(()) } #[tauri::command] fn open_url(url: String) -> Result<(), String> { let url = reqwest::Url::parse(&url).map_err(|e| format!("invalid URL: {e}"))?; if !matches!(url.scheme(), "http" | "https") || !url.has_host() { return Err("only http/https URLs are supported".to_string()); } open_shell_target(std::ffi::OsStr::new(url.as_str())) } #[derive(Debug, Serialize)] pub struct DiagnosticsInfo { pub app_version: String, pub ffmpeg_version: String, pub log_dir: String, pub log_tail: String, } /// Read the tail of the most recent daily-rotated log file so the Diagnostics /// tab can show recent activity without the user having to find the file. /// Logs are written by tracing-appender to {app_dir}/logs/bytesize.log.YYYY-MM-DD. fn read_log_tail(log_dir: &Path) -> String { const TAIL_BYTES: usize = 8 * 1024; let Ok(entries) = std::fs::read_dir(log_dir) else { return String::new(); }; // Pick the newest bytesize.log.* by mtime. let mut newest: Option<(std::time::SystemTime, PathBuf)> = None; for entry in entries.flatten() { let name = entry.file_name(); let Some(name) = name.to_str() else { continue }; if !name.starts_with("bytesize.log") { continue; } if let Ok(meta) = entry.metadata() { if let Ok(mtime) = meta.modified() { if newest.as_ref().is_none_or(|(t, _)| mtime > *t) { newest = Some((mtime, entry.path())); } } } } let Some((_, path)) = newest else { return String::new(); }; let Ok(data) = std::fs::read(&path) else { return String::new(); }; // saturating_sub keeps start at or below data.len(), so the tail slice // always exists; get() just makes that explicit. let start = data.len().saturating_sub(TAIL_BYTES); String::from_utf8_lossy(data.get(start..).unwrap_or_default()).into_owned() } #[tauri::command(async)] fn diagnostics_info(state: State<'_, AppState>) -> DiagnosticsInfo { let log_dir = state.app_dir.join("logs"); let log_tail = read_log_tail(&log_dir); let ffmpeg_version = { let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if ffmpeg.is_file() { std::process::Command::new(&ffmpeg) .arg("-version") .output() .ok() .and_then(|o| { String::from_utf8_lossy(&o.stdout) .lines() .next() .map(ToString::to_string) }) .unwrap_or_else(|| "ffmpeg present (version unreadable)".to_string()) } else { "not installed".to_string() } }; DiagnosticsInfo { app_version: env!("CARGO_PKG_VERSION").to_string(), ffmpeg_version, log_dir: log_dir.to_string_lossy().into_owned(), log_tail, } } #[tauri::command] fn open_log_dir(state: State<'_, AppState>) -> Result<(), String> { use std::os::windows::process::CommandExt; let log_dir = state.app_dir.join("logs"); drop(std::fs::create_dir_all(&log_dir)); std::process::Command::new("explorer.exe") .raw_arg(log_dir.to_string_lossy().to_string()) .spawn() .map_err(|e| format!("opening log dir: {e:#}"))?; Ok(()) } #[tauri::command] fn cancel_export(state: State<'_, AppState>) { state.export_cancel.store(true, Ordering::SeqCst); } #[tauri::command(async)] /// Tauri deserializes the return into a JS Result, so the wrapper stays even /// though there is no failure path. #[allow( clippy::unnecessary_wraps, reason = "Result is part of the tauri::command contract the frontend invokes" )] fn codec_availability(state: State<'_, AppState>) -> Result { let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir); if !ffmpeg.is_file() { return Ok(encode::CodecAvailability::all_unknown()); } Ok(encode::codec_availability(&ffmpeg)) } /// Clears the export flag on every exit path, including the `?` returns below. struct ExportGuard(Arc); impl Drop for ExportGuard { fn drop(&mut self) { self.0.store(false, Ordering::SeqCst); } } // One export is one transaction: resolve the output path, translate the trim // and crop into encoder terms, run the encode, and report the size. Splitting // it would mean threading the same resolved state through the pieces. #[allow( clippy::too_many_lines, reason = "one export transaction; the request translation feeds directly into the encode call" )] #[tauri::command] async fn export( app: AppHandle, state: State<'_, AppState>, request: ExportRequest, ) -> Result { if state.exporting.swap(true, Ordering::SeqCst) { return Err("an export is already running".to_string()); } let _export = ExportGuard(state.exporting.clone()); let (cfg, clip, app_dir, export_cancel) = { let cfg = lock(&state.config).clone(); let clip = lock(&state.last_clip) .clone() .ok_or_else(|| "no recorded clip available".to_string())?; ( cfg, clip, state.app_dir.clone(), state.export_cancel.clone(), ) }; let ffmpeg = bootstrap::ffmpeg_path(&app_dir); if !ffmpeg.is_file() { return Err("ffmpeg.exe not found - run the encoder setup first".to_string()); } let out_path: PathBuf = match request.output_path.as_deref() { Some(p) if !p.trim().is_empty() => PathBuf::from(p), _ => { let out_dir = output_dir(&app_dir, &cfg); out_dir.join(format!( "bytesize-{}.{}", timestamp_slug(), ext_for(request.format) )) } }; if let Some(parent) = out_path.parent() { std::fs::create_dir_all(parent).map_err(|e| format!("creating output dir: {e:#}"))?; } let trim_start = request.trim_start_secs.filter(|s| *s > 0.001); let trim_end = request .trim_end_secs .filter(|e| *e < clip.duration_secs - 0.001); let effective_duration = match (trim_start, trim_end) { (Some(s), Some(e)) => (e - s).max(0.1), (Some(s), None) => (clip.duration_secs - s).max(0.1), (None, Some(e)) => e.max(0.1), (None, None) => clip.duration_secs, }; let (src_w, src_origin) = if let Some(c) = clip.crop { (c.width, (c.x, c.y)) } else { (clip.monitor_width.max(1), (0, 0)) }; let scale = f64::from(clip.width) / f64::from(src_w); let transformed_clicks: Vec = clip .clicks .iter() .map(|c| clicks::Click { time_secs: c.time_secs, x: encode::round_i32(f64::from(c.x - src_origin.0) * scale), y: encode::round_i32(f64::from(c.y - src_origin.1) * scale), button: c.button, }) .collect(); let req = encode::TranscodeRequest { input: clip.temp_path.clone(), output: out_path.clone(), format: request.format, target_bytes: request.target_bytes, duration_secs: effective_duration, fps: request.fps, keep_audio: request.keep_audio, gif_dither: request.gif_dither.unwrap_or(cfg.export.gif_dither), gif_colors: request.gif_colors.unwrap_or(256), webm_codec: cfg.export.webm_codec, mp4_codec: cfg.export.mp4_codec, scratch_dir: temp_dir(&app_dir), crop: request.crop, gif_budget_mode: request.gif_budget_mode, deleted_frame_indices: request.deleted_frame_indices, trim_start_secs: trim_start, trim_end_secs: trim_end, clicks: transformed_clicks, clip_width: clip.width, clip_height: clip.height, progress_tx: None, cancel: Some(export_cancel.clone()), }; let (tx, rx) = std::sync::mpsc::channel(); let mut req_with_progress = req; req_with_progress.progress_tx = Some(tx); let app_handle = app.clone(); // Spawn a thread to forward encode progress to the frontend. The encoder // owns total_passes: 2 for two-pass video, max_retries (up to 12) for GIF // so the progress bar accumulates across retry attempts. std::thread::spawn(move || { while let Ok(progress) = rx.recv() { drop(app_handle.emit( "encode-progress", encode::EncodeProgress { pass: progress.pass, total_passes: progress.total_passes, percent: progress.percent, }, )); } }); export_cancel.store(false, Ordering::SeqCst); // Run the (potentially minutes-long) ffmpeg encode on a blocking thread so // we don't hold a Tauri async worker for the whole duration. let ffmpeg_arc = Arc::new(ffmpeg); let ffmpeg_for_task = ffmpeg_arc.clone(); let result = tauri::async_runtime::spawn_blocking(move || { encode::transcode(&ffmpeg_for_task, &req_with_progress) }) .await .map_err(|e| format!("encode task panicked: {e:#}"))?; result.map_err(|e| format!("{e:#}"))?; let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len()); state.unexported_clip.store(false, Ordering::Relaxed); Ok(ExportResult { met_target: size_bytes <= request.target_bytes, target_bytes: request.target_bytes, output_path: out_path, size_bytes, }) } fn show_startup_error(message: &str) { use windows::core::{w, HSTRING}; use windows::Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_ICONINFORMATION, MB_OK}; // SAFETY: The owned message and the caption are NUL-terminated. unsafe { MessageBoxW(None, &HSTRING::from(message), w!("ByteSize"), MB_OK | MB_ICONINFORMATION); } } /// # Panics /// /// Panics if the executable's own directory cannot be resolved or if /// `config.toml` cannot be created there. Both are fatal for a portable build: /// there is nowhere to write config, logs or temp files. #[allow( clippy::expect_used, reason = "fatal startup conditions with no sensible recovery" )] #[allow( clippy::too_many_lines, reason = "app wiring: logging, state, plugins, hotkeys, updater, then the event loop - one sequence" )] pub fn run() { let app_dir = exe_dir().expect("resolve exe directory"); let _instance = match lock_instance(&app_dir) { Ok(lock) => lock, Err(e) => { let message = if e.raw_os_error() == Some(32) { "ByteSize is already open from this folder.".to_string() } else { format!("Could not open the ByteSize working folder: {e}") }; show_startup_error(&message); return; } }; // Sweep temp/ before anything else so a crash on the previous run does not // leave orphaned segments, previews, or thumbs behind - the portability // spec promises no trace, and stale temp is trace. clear_temp_segments(&app_dir, false); let log_dir = app_dir.join("logs"); drop(std::fs::create_dir_all(&log_dir)); let file_appender = tracing_appender::rolling::daily(&log_dir, "bytesize.log"); let (file_writer, _log_guard) = tracing_appender::non_blocking(file_appender); let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); let file_layer = tracing_subscriber::fmt::layer() .with_writer(file_writer) .with_ansi(false); let registry = tracing_subscriber::registry() .with(env_filter) .with(file_layer); #[cfg(debug_assertions)] let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout)); #[cfg(test)] drop(registry.try_init()); #[cfg(not(test))] registry.init(); let webview_dir = app_dir.join("temp").join("webview"); match std::fs::create_dir_all(&webview_dir) { Ok(()) => { // SAFETY: must be set before Tauri reads the environment. No other threads exist yet. // set_var is deprecated in Rust 2024 edition; migrate when upgrading toolchain. unsafe { std::env::set_var("WEBVIEW2_USER_DATA_FOLDER", &webview_dir); } } Err(e) => { tracing::error!( "could not create webview data dir at {}: {e}", webview_dir.display() ); tracing::error!( "WebView2 will fall back to the system default - portability may be broken" ); } } let cfg_path = config::config_path(&app_dir); let cfg = Config::load_or_create(&cfg_path).expect("load or create config.toml"); tracing::info!(?app_dir, "starting ByteSize"); let state = AppState { app_dir, config: Mutex::new(cfg), capture: Mutex::new(None), audio: Mutex::new(None), click_recorder: Mutex::new(None), last_clip: Mutex::new(None), unexported_clip: AtomicBool::new(false), session: Mutex::new(None), capture_transition: Mutex::new(()), thumbnail_operation: Mutex::new(()), picker: Mutex::new(None), overlay_poll_shutdown: Arc::new(AtomicBool::new(false)), export_cancel: Arc::new(AtomicBool::new(false)), exporting: Arc::new(AtomicBool::new(false)), overlay_aspect_ratio: Mutex::new(None), overlay_poll_live: Arc::new((Mutex::new(false), std::sync::Condvar::new())), }; let app = tauri::Builder::default() .on_window_event(|window, event| { if window.label() == "main" { if let tauri::WindowEvent::CloseRequested { api, .. } = event { api.prevent_close(); close_main(window); } } }) .plugin(tauri_plugin_dialog::init()) .plugin( tauri_plugin_global_shortcut::Builder::new() .with_handler(|app, shortcut, event| { if event.state() != ShortcutState::Pressed { return; } let cfg = { let st = app.state::(); let cfg = lock(&st.config).clone(); cfg }; let kind = if cfg .hotkeys .start .as_deref() .and_then(parse_shortcut) .as_ref() == Some(shortcut) { Some("start") } else if cfg .hotkeys .stop .as_deref() .and_then(parse_shortcut) .as_ref() == Some(shortcut) { Some("stop") } else if cfg .hotkeys .pause .as_deref() .and_then(parse_shortcut) .as_ref() == Some(shortcut) { Some("pause") } else { None }; if let Some(k) = kind { drop(app.emit("hotkey", k)); } }) .build(), ) .manage(state) .setup(|app| { let (check_on_launch, cfg) = { let st = app.state::(); let cfg = lock(&st.config).clone(); (cfg.updates.check_on_launch, cfg) }; // Result is not Drop, so the old drop() here did nothing beyond // extending its lifetime; the hotkey outcome is logged upstream. let _hotkeys = register_hotkeys(app.handle(), &cfg); { let st = app.state::(); start_overlay_clickthrough_poll( app.handle().clone(), st.overlay_poll_shutdown.clone(), st.overlay_poll_live.clone(), ); } if check_on_launch { let handle = app.handle().clone(); let app_dir = app.state::().app_dir.clone(); tauri::async_runtime::spawn(async move { // Skip the network call if we checked within the last 6 hours. if !updates::should_check(&app_dir, std::time::Duration::from_hours(6)) { tracing::debug!("update check skipped (TTL not elapsed)"); return; } match updates::check_for_update().await { Ok(Some(info)) => { tracing::info!(version = info.version, "update available"); drop(handle.emit("update-available", &info)); updates::stamp_check(&app_dir); } Ok(None) => { tracing::debug!("no update available"); updates::stamp_check(&app_dir); } // No stamp on failure, so a transient network error does // not silence the check for the whole TTL. Err(e) => tracing::warn!("update check failed: {e:#}"), } }); } Ok(()) }) .invoke_handler(tauri::generate_handler![ get_status, get_config, save_config, download_ffmpeg, download_update, apply_update, pending_update, start_capture, pause_capture, resume_capture, restart_audio_capture, stop_capture, discard_clip, export, default_output_path, extract_thumbnails, render_preview, render_raw_preview, estimate_gif_params, estimate_gif_params_table, reveal_in_explorer, open_url, show_overlay, hide_overlay, set_overlay_size, set_overlay_aspect, get_overlay_aspect, enforce_overlay_aspect, set_overlay_to_window, list_windows, open_window_picker, close_window_picker, get_overlay_rect, cancel_export, codec_availability, diagnostics_info, open_log_dir, ]) .build(tauri::generate_context!()) .expect("error while building ByteSize"); app.run(|app, event| { if let tauri::RunEvent::Exit = event { if let Some(st) = app.try_state::() { st.overlay_poll_shutdown.store(true, Ordering::SeqCst); } cleanup_temp_on_exit(app); } }); }