diff --git a/src-tauri/src/bootstrap.rs b/src-tauri/src/bootstrap.rs index d7a6f7a..dcf81ce 100644 --- a/src-tauri/src/bootstrap.rs +++ b/src-tauri/src/bootstrap.rs @@ -343,8 +343,9 @@ fn extract_ffmpeg_from_7z(archive_path: &Path, dest: &Path) -> Result<()> { let Some(src) = found else { bail!("ffmpeg.exe not found inside the 7z archive"); }; - fs::copy(&src, dest).context("write ffmpeg.exe from 7z")?; - Ok(()) + install_from(dest, |staging| { + fs::copy(&src, staging).map(|_| ()).context("write ffmpeg.exe from 7z") + }) } fn find_ffmpeg_in(dir: &Path) -> Option { @@ -366,6 +367,21 @@ fn find_ffmpeg_in(dir: &Path) -> Option { None } +/// Write `dest` through a sibling staging file and rename it into place. A +/// half-written ffmpeg.exe used to be left behind by a failed extraction, and +/// `check` reports any file at that path as ready - so every later encode failed +/// on a truncated binary with no way to tell it apart from a good install. +fn install_from(dest: &Path, write: impl FnOnce(&Path) -> Result<()>) -> Result<()> { + let staging = dest.with_extension("exe.part"); + drop(fs::remove_file(&staging)); + let staged = write(&staging) + .and_then(|()| fs::rename(&staging, dest).context("moving ffmpeg.exe into place")); + if staged.is_err() { + drop(fs::remove_file(&staging)); + } + staged +} + fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { let file = File::open(archive_path).context("opening zip archive")?; let mut zip = zip::ZipArchive::new(file).context("open zip archive")?; @@ -376,9 +392,11 @@ fn extract_ffmpeg_from_zip(archive_path: &Path, dest: &Path) -> Result<()> { } let name = entry.name().to_string(); if is_ffmpeg_entry(&name) { - let mut out = File::create(dest).context("create ffmpeg.exe")?; - io::copy(&mut entry, &mut out).context("write ffmpeg.exe from zip")?; - return Ok(()); + return install_from(dest, |staging| { + let mut out = File::create(staging).context("create ffmpeg.exe")?; + io::copy(&mut entry, &mut out).context("write ffmpeg.exe from zip")?; + Ok(()) + }); } } bail!("ffmpeg.exe not found inside the zip archive"); diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 6755c31..06a2b8d 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -27,7 +27,14 @@ pub struct Config { pub theme: Theme, } +// Every persisted section carries a container-level `serde(default)`, so a +// config.toml written by an older build still loads once a field is added. The +// outer Config already defaulted its own fields; without the same treatment here +// a single unknown field made the whole file fail to parse, and the recovery +// path backs it up and rewrites defaults - losing the user's hotkeys and +// dropping them back into first-run. #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct ExportConfig { pub default_format: Format, pub gif_dither: GifDither, @@ -48,15 +55,16 @@ pub enum CaptureQuality { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct CaptureConfig { pub default_fps: u32, pub capture_cursor: bool, pub capture_audio: bool, - #[serde(default)] pub capture_quality: CaptureQuality, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default)] pub struct HotkeyConfig { pub start: Option, pub stop: Option, @@ -64,6 +72,7 @@ pub struct HotkeyConfig { } #[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(default)] pub struct UpdatesConfig { pub check_on_launch: bool, } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index f65a2c3..e2485b1 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -369,6 +369,10 @@ fn clear_temp_segments(app_dir: &Path, keep_previews: bool) { if (name.starts_with("segment-") && has_ext(name, "mp4")) || (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())); @@ -622,7 +626,7 @@ fn start_capture( Ok(()) } -#[tauri::command] +#[tauri::command(async)] fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { let session = lock(&state.capture) .take() @@ -760,7 +764,7 @@ fn restart_audio_capture( clippy::too_many_lines, reason = "one recording-finalisation transaction; the steps share session state and temp paths" )] -#[tauri::command] +#[tauri::command(async)] fn stop_capture(state: State<'_, AppState>) -> Result { let mut ss = lock(&state.session) .take() @@ -955,7 +959,7 @@ pub struct PreviewRequest { pub duration_secs: Option, } -#[tauri::command] +#[tauri::command(async)] fn render_preview( state: State<'_, AppState>, request: PreviewRequest, @@ -1138,6 +1142,8 @@ mod tests { "audio-001.pcm", "preview.png", "raw-preview.png", + "ffmpeg2pass-0.log", + "ffmpeg2pass-0.log.mbtree", ] { std::fs::write(temp.join(name), b"x").unwrap(); } @@ -1147,6 +1153,8 @@ mod tests { 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()); @@ -1192,7 +1200,7 @@ mod tests { } } -#[tauri::command] +#[tauri::command(async)] fn extract_thumbnails( state: State<'_, AppState>, fps: u32, @@ -1209,7 +1217,7 @@ fn extract_thumbnails( .map_err(|e| format!("{e:#}")) } -#[tauri::command] +#[tauri::command(async)] fn render_raw_preview( state: State<'_, AppState>, timestamp: f64, @@ -1889,7 +1897,7 @@ fn read_log_tail(log_dir: &Path) -> String { String::from_utf8_lossy(data.get(start..).unwrap_or_default()).into_owned() } -#[tauri::command] +#[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); @@ -1936,7 +1944,7 @@ fn cancel_export(state: State<'_, AppState>) { state.export_cancel.store(true, Ordering::SeqCst); } -#[tauri::command] +#[tauri::command(async)] /// Tauri deserializes the return into a JS Result, so the wrapper stays even /// though there is no failure path. #[allow( diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 02d8030..8779fcd 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -1,12 +1,17 @@ use std::path::{Path, PathBuf}; -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use futures_util::StreamExt; use serde::{Deserialize, Serialize}; const GITEA_LATEST: &str = "https://git.lashman.live/api/v1/repos/lashman/bytesize/releases/latest"; +/// Everything the updater will fetch has to live under this prefix. The download +/// URL arrives from the frontend, and an unconstrained one there would let +/// anything that can reach the webview hand the app a new executable to install. +const UPDATE_ORIGIN: &str = "https://git.lashman.live/"; + #[derive(Debug, Clone, Serialize)] pub(crate) struct UpdateInfo { pub version: String, @@ -37,7 +42,14 @@ pub(crate) async fn check_for_update() -> Result> { .build()?; let resp = client.get(GITEA_LATEST).send().await?; if !resp.status().is_success() { - tracing::debug!("update check returned status {}", resp.status()); + // A 404 means the endpoint itself is wrong or the repo has no releases - + // not that the app is up to date, which is how it reads if this is only + // ever a debug line. + if resp.status() == reqwest::StatusCode::NOT_FOUND { + tracing::warn!("no release published at {GITEA_LATEST}"); + } else { + tracing::warn!("update check returned status {}", resp.status()); + } return Ok(None); } let body = resp.text().await?; @@ -69,6 +81,10 @@ where { use std::io::Write; + if !url.starts_with(UPDATE_ORIGIN) { + bail!("refusing to download an update from {url}"); + } + if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent).context("creating update parent dir")?; } diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index d69f004..ab5c114 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -149,38 +149,34 @@ }) onMount(() => { - let unlistenHotkey: (() => void) | null = null - let unlistenProgress: (() => void) | null = null - let unlistenAudio: (() => void) | null = null - let unlistenAudioRecovered: (() => void) | null = null - let unlistenOverlayClosed: (() => void) | null = null + const unlisten: (() => void)[] = [] + // Registered one at a time rather than through a single Promise.all: one + // rejected registration used to lose the whole batch, which left every + // listener live and none of them removable - hotkeys included. + const keep = (p: Promise<() => void>) => { + void p.then(fn => unlisten.push(fn)) + .catch(e => console.warn("could not register a listener:", e)) + } + + keep(listen("overlay-closed", () => { useFrame = false })) + keep(api.onHotkey((kind) => { + if (kind === "start" && phase === "idle") void startRec() + else if (kind === "pause") { + if (phase === "recording") void pauseRec() + else if (phase === "paused") void resumeRec() + } else if (kind === "stop") { + if (phase === "recording" || phase === "paused") void stopRec() + } + })) + keep(api.onEncodeProgress((p) => { + encodeProgress = { pass: p.pass, total: p.total_passes, pct: p.percent } + })) + keep(api.onAudioFailed((msg) => { + audioWarning = msg || "audio capture failed - audio will not be recorded" + })) + keep(listen("audio-recovered", () => { audioWarning = null })) void (async () => { - const [overlayClosed, hotkey, progress, audio, audioRecovered] = await Promise.all([ - listen("overlay-closed", () => { useFrame = false }), - api.onHotkey((kind) => { - if (kind === "start" && phase === "idle") void startRec() - else if (kind === "pause") { - if (phase === "recording") void pauseRec() - else if (phase === "paused") void resumeRec() - } else if (kind === "stop") { - if (phase === "recording" || phase === "paused") void stopRec() - } - }), - api.onEncodeProgress((p) => { - encodeProgress = { pass: p.pass, total: p.total_passes, pct: p.percent } - }), - api.onAudioFailed((msg) => { - audioWarning = msg || "audio capture failed - audio will not be recorded" - }), - listen("audio-recovered", () => { audioWarning = null }), - ]) - unlistenOverlayClosed = overlayClosed - unlistenHotkey = hotkey - unlistenProgress = progress - unlistenAudio = audio - unlistenAudioRecovered = audioRecovered - try { config = await api.getConfig() format = config.export.default_format @@ -191,13 +187,8 @@ console.warn("failed to load config:", e) } })() - return () => { - unlistenHotkey?.() - unlistenProgress?.() - unlistenAudio?.() - unlistenAudioRecovered?.() - unlistenOverlayClosed?.() - } + + return () => { unlisten.forEach(fn => fn()) } }) // ---- Actions ---- diff --git a/src/lib/Picker.svelte b/src/lib/Picker.svelte index eb93797..bd18fe1 100644 --- a/src/lib/Picker.svelte +++ b/src/lib/Picker.svelte @@ -11,7 +11,15 @@ onMount(() => { const win = getCurrentWebviewWindow() - let unlisten: (() => void)[] = [] + const unlisten: (() => void)[] = [] + let hoverDebounce = 0 + + // A registration that lands after the window is gone still has to + // unregister, so a late unlisten runs immediately rather than being dropped. + const keep = (p: Promise<() => void>) => { + void p.then(fn => { if (mounted) unlisten.push(fn); else fn() }) + .catch(e => console.warn("could not register a listener:", e)) + } const refresh = async () => { scale = await win.scaleFactor() @@ -20,18 +28,21 @@ } void (async () => { - await refresh() - win.onMoved(refresh).then(fn => { if (mounted) unlisten.push(fn) }) - .catch(e => console.warn("could not watch the picker window position:", e)) - let hoverDebounce = 0 - listen("picker-hover", (e) => { + try { + await refresh() + } catch (e) { + console.warn("could not read the picker window geometry:", e) + } + keep(win.onMoved(refresh)) + keep(listen("picker-hover", (e) => { clearTimeout(hoverDebounce) hoverDebounce = window.setTimeout(() => { hover = e.payload }, 30) - }).then(fn => { if (mounted) unlisten.push(fn) }) + })) })() return () => { mounted = false + clearTimeout(hoverDebounce) unlisten.forEach(fn => fn()) emit("picker-cancel", {}).catch(() => {}) } diff --git a/src/lib/UpdateBanner.svelte b/src/lib/UpdateBanner.svelte index a505cec..310d942 100644 --- a/src/lib/UpdateBanner.svelte +++ b/src/lib/UpdateBanner.svelte @@ -9,14 +9,19 @@ let errMsg: string | null = $state(null) onMount(() => { - let unlistenInfo: (() => void) | null = null - let unlistenProg: (() => void) | null = null - void (async () => { - unlistenInfo = await api.onUpdateAvailable((i) => { info = i; phase = "info" }) - unlistenProg = await api.onUpdateDownloadProgress((p) => { progress = p }) - if (await api.pendingUpdate()) phase = "ready" - })() - return () => { unlistenInfo?.(); unlistenProg?.() } + const unlisten: (() => void)[] = [] + const keep = (p: Promise<() => void>) => { + void p.then(fn => unlisten.push(fn)) + .catch(e => console.warn("could not register an update listener:", e)) + } + + keep(api.onUpdateAvailable((i) => { info = i; phase = "info" })) + keep(api.onUpdateDownloadProgress((p) => { progress = p })) + void api.pendingUpdate() + .then(pending => { if (pending) phase = "ready" }) + .catch(e => console.warn("could not read the pending update state:", e)) + + return () => { unlisten.forEach(fn => fn()) } }) function dismiss() { info = null; errMsg = null; phase = "info" }