From 2882e7879544c8fab2728c32f6c0777351c83b55 Mon Sep 17 00:00:00 2001 From: lashman Date: Tue, 12 May 2026 01:33:47 +0300 Subject: [PATCH] global hotkeys wired up --- src-tauri/Cargo.lock | 68 ++++++++++ src-tauri/Cargo.toml | 2 + src-tauri/capabilities/default.json | 4 +- src-tauri/src/bootstrap.rs | 80 +++++++---- src-tauri/src/capture.rs | 154 +++++++++++++++++----- src-tauri/src/encode.rs | 101 ++++++++++++-- src-tauri/src/lib.rs | 198 +++++++++++++++++++++++++--- src/lib/Main.svelte | 110 ++++++++++++++-- src/lib/Overlay.svelte | 22 +++- src/lib/api.ts | 5 + 10 files changed, 637 insertions(+), 107 deletions(-) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 34af4ce..08a8772 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -367,11 +367,13 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-dialog", + "tauri-plugin-global-shortcut", "thiserror 2.0.18", "tokio", "toml 0.9.12+spec-1.1.0", "tracing", "tracing-subscriber", + "windows 0.62.2", "windows-capture", "zip", ] @@ -1356,6 +1358,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link 0.2.1", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1487,6 +1499,24 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" +[[package]] +name = "global-hotkey" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9247516746aa8e53411a0db9b62b0e24efbcf6a76e0ba73e5a91b512ddabed7" +dependencies = [ + "crossbeam-channel", + "keyboard-types", + "objc2", + "objc2-app-kit", + "once_cell", + "serde", + "thiserror 2.0.18", + "windows-sys 0.59.0", + "x11rb", + "xkeysym", +] + [[package]] name = "gobject-sys" version = "0.18.0" @@ -4149,6 +4179,21 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-global-shortcut" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "424af23c7e88d05e4a1a6fc2c7be077912f8c76bd7900fd50aa2b7cbf5a2c405" +dependencies = [ + "global-hotkey", + "log", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.18", +] + [[package]] name = "tauri-runtime" version = "2.11.1" @@ -5808,6 +5853,29 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + [[package]] name = "y4m" version = "0.8.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b232dfd..cd4ce29 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -16,7 +16,9 @@ tauri-build = { version = "2", features = [] } [dependencies] tauri = { version = "2.11", features = ["protocol-asset"] } tauri-plugin-dialog = "2" +tauri-plugin-global-shortcut = "2" windows-capture = "2.0" +windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation"] } tokio = { version = "1.47", features = ["full"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index cb3cd2b..3fd530d 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -6,7 +6,9 @@ "permissions": [ "core:default", "core:window:default", + "core:window:allow-start-dragging", "core:webview:default", - "dialog:default" + "dialog:default", + "global-shortcut:default" ] } diff --git a/src-tauri/src/bootstrap.rs b/src-tauri/src/bootstrap.rs index ed9ebb1..cb1b794 100644 --- a/src-tauri/src/bootstrap.rs +++ b/src-tauri/src/bootstrap.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; use anyhow::{anyhow, bail, Context, Result}; use futures_util::StreamExt; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] @@ -30,6 +30,7 @@ pub fn check(app_dir: &Path) -> FfmpegStatus { } } +#[derive(Clone, Copy)] enum ArchiveKind { SevenZ, Zip, @@ -37,26 +38,39 @@ enum ArchiveKind { struct Source { name: &'static str, - archive_url: &'static str, - checksum_url: &'static str, + release_api_url: &'static str, + asset_name_suffix: &'static str, kind: ArchiveKind, } const SOURCES: &[Source] = &[ Source { name: "GyanD", - archive_url: "https://github.com/GyanD/codexffmpeg/releases/download/8.1.1/ffmpeg-8.1.1-essentials_build.7z", - checksum_url: "https://github.com/GyanD/codexffmpeg/releases/download/8.1.1/ffmpeg-8.1.1-essentials_build.7z.sha256", + release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/tags/8.1.1", + asset_name_suffix: "full_build.7z", kind: ArchiveKind::SevenZ, }, Source { name: "BtbN", - archive_url: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip", - checksum_url: "https://github.com/BtbN/FFmpeg-Builds/releases/download/latest/ffmpeg-master-latest-win64-gpl.zip.sha256", + release_api_url: "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/tags/latest", + asset_name_suffix: "win64-gpl.zip", kind: ArchiveKind::Zip, }, ]; +#[derive(Debug, Deserialize)] +struct GithubRelease { + assets: Vec, +} + +#[derive(Debug, Deserialize)] +struct GithubAsset { + name: String, + browser_download_url: String, + #[serde(default)] + digest: Option, +} + pub async fn download(app_dir: &Path, mut on_progress: F) -> Result<()> where F: FnMut(u64, Option) + Send, @@ -89,13 +103,14 @@ where .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; - let expected = fetch_sha256(&client, source.checksum_url) - .await - .with_context(|| format!("fetching checksum from {}", source.checksum_url))?; + let asset = pick_asset(&client, source).await?; - let archive = download_verified(&client, source.archive_url, &expected, on_progress) + let expected = parse_sha256_digest(&asset.digest) + .with_context(|| format!("parsing digest for {}", asset.name))?; + + let archive = download_verified(&client, &asset.browser_download_url, &expected, on_progress) .await - .with_context(|| format!("downloading archive from {}", source.archive_url))?; + .with_context(|| format!("downloading {}", asset.browser_download_url))?; match source.kind { ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?, @@ -104,21 +119,38 @@ where Ok(()) } -async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> { - let body = client - .get(url) +async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result { + let resp = client + .get(source.release_api_url) + .header("Accept", "application/vnd.github+json") .send() .await? - .error_for_status()? - .text() - .await?; - let hex_str = body - .split_whitespace() - .next() - .ok_or_else(|| anyhow!("empty checksum file"))?; - let bytes = hex::decode(hex_str).context("checksum is not valid hex")?; + .error_for_status()?; + let body = resp.text().await?; + let release: GithubRelease = + serde_json::from_str(&body).context("parsing release metadata")?; + release + .assets + .into_iter() + .find(|a| a.name.ends_with(source.asset_name_suffix)) + .ok_or_else(|| { + anyhow!( + "no asset matching '*{}' in release", + source.asset_name_suffix + ) + }) +} + +fn parse_sha256_digest(digest: &Option) -> Result<[u8; 32]> { + let raw = digest + .as_deref() + .ok_or_else(|| anyhow!("release asset has no digest"))?; + let hex_str = raw + .strip_prefix("sha256:") + .ok_or_else(|| anyhow!("digest is not sha256: '{raw}'"))?; + let bytes = hex::decode(hex_str).context("digest is not valid hex")?; if bytes.len() != 32 { - bail!("checksum length is {} bytes, expected 32", bytes.len()); + bail!("digest length is {} bytes, expected 32", bytes.len()); } let mut sha = [0u8; 32]; sha.copy_from_slice(&bytes); diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 7d6ed40..9ce5a14 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -1,15 +1,12 @@ +use std::io::Write; use std::path::PathBuf; +use std::process::{Child, ChildStdin, Command, Stdio}; use std::time::Instant; use anyhow::{anyhow, Result}; use windows_capture::capture::{ CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler, }; - -use crate::CaptureRect; -use windows_capture::encoder::{ - AudioSettingsBuilder, ContainerSettingsBuilder, VideoEncoder, VideoSettingsBuilder, -}; use windows_capture::frame::Frame; use windows_capture::graphics_capture_api::InternalCaptureControl; use windows_capture::monitor::Monitor; @@ -18,16 +15,27 @@ use windows_capture::settings::{ MinimumUpdateIntervalSettings, SecondaryWindowSettings, Settings, }; +use crate::CaptureRect; + +const TARGET_FPS: u32 = 30; +const MAX_ENCODE_WIDTH: u32 = 1920; + #[derive(Debug, Clone)] pub struct CaptureSetup { pub output_path: PathBuf, + pub ffmpeg_path: PathBuf, pub width: u32, pub height: u32, - pub audio: bool, + pub fps: u32, + pub crop: Option, } pub struct CaptureHandler { - encoder: Option, + stdin: Option, + child: Option, + width: u32, + height: u32, + scratch: Vec, } impl GraphicsCaptureApiHandler for CaptureHandler { @@ -36,15 +44,60 @@ impl GraphicsCaptureApiHandler for CaptureHandler { fn new(ctx: CaptureContext) -> Result { let setup = ctx.flags; - let audio = AudioSettingsBuilder::new().disabled(!setup.audio); - let encoder = VideoEncoder::new( - VideoSettingsBuilder::new(setup.width, setup.height), - audio, - ContainerSettingsBuilder::new(), - &setup.output_path, - ) - .map_err(|e| anyhow!("video encoder init: {e}"))?; - Ok(Self { encoder: Some(encoder) }) + + let mut filter_parts: Vec = Vec::new(); + let working_width = if let Some(c) = setup.crop { + let x = c.x.max(0); + let y = c.y.max(0); + let w = c.width.min(setup.width.saturating_sub(x as u32)); + let h = c.height.min(setup.height.saturating_sub(y as u32)); + filter_parts.push(format!("crop={}:{}:{}:{}", w, h, x, y)); + w + } else { + setup.width + }; + + if working_width > MAX_ENCODE_WIDTH { + filter_parts.push(format!("scale={}:-2", MAX_ENCODE_WIDTH)); + } else { + filter_parts.push("scale=trunc(iw/2)*2:trunc(ih/2)*2".to_string()); + } + let filter = filter_parts.join(","); + + let mut cmd = Command::new(&setup.ffmpeg_path); + cmd.arg("-y") + .arg("-hide_banner") + .args(["-loglevel", "error"]) + .args(["-f", "rawvideo"]) + .args(["-pixel_format", "bgra"]) + .args(["-video_size", &format!("{}x{}", setup.width, setup.height)]) + .args(["-framerate", &setup.fps.to_string()]) + .args(["-i", "-"]) + .args(["-vf", &filter]) + .args(["-c:v", "libx264"]) + .args(["-preset", "ultrafast"]) + .args(["-tune", "zerolatency"]) + .args(["-pix_fmt", "yuv420p"]) + .args(["-movflags", "+faststart"]) + .arg(&setup.output_path) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + + let mut child = cmd.spawn().map_err(|e| anyhow!("spawning ffmpeg: {e}"))?; + let stdin = child + .stdin + .take() + .ok_or_else(|| anyhow!("ffmpeg stdin not captured"))?; + + let frame_size = (setup.width as usize) * (setup.height as usize) * 4; + Ok(Self { + stdin: Some(stdin), + child: Some(child), + width: setup.width, + height: setup.height, + scratch: Vec::with_capacity(frame_size), + }) } fn on_frame_arrived( @@ -52,20 +105,31 @@ impl GraphicsCaptureApiHandler for CaptureHandler { frame: &mut Frame<'_>, _capture_control: InternalCaptureControl, ) -> Result<(), Self::Error> { - if let Some(enc) = self.encoder.as_mut() { - enc.send_frame(frame) - .map_err(|e| anyhow!("send frame: {e}"))?; - } + let Some(stdin) = self.stdin.as_mut() else { + return Ok(()); + }; + + let buf = frame + .buffer() + .map_err(|e| anyhow!("frame buffer: {e:?}"))?; + self.scratch.clear(); + let bytes = buf.as_nopadding_buffer(&mut self.scratch); + let expected = (self.width as usize) * (self.height as usize) * 4; + let slice = if bytes.len() >= expected { + &bytes[..expected] + } else { + bytes + }; + let _ = stdin.write_all(slice); Ok(()) } } impl Drop for CaptureHandler { fn drop(&mut self) { - if let Some(enc) = self.encoder.take() { - if let Err(e) = enc.finish() { - tracing::error!("encoder finish failed: {e}"); - } + drop(self.stdin.take()); + if let Some(mut child) = self.child.take() { + let _ = child.wait(); } } } @@ -81,23 +145,30 @@ pub struct CaptureSession { pub fn start( output_path: PathBuf, + ffmpeg_path: PathBuf, capture_cursor: bool, - audio: bool, + _audio: bool, crop: Option, ) -> Result { let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?; - let width = monitor + let raw_width = monitor .width() .map_err(|e| anyhow!("monitor width: {e:?}"))?; - let height = monitor + let raw_height = monitor .height() .map_err(|e| anyhow!("monitor height: {e:?}"))?; + let width = raw_width & !1; + let height = raw_height & !1; + + let (out_w, out_h) = compute_output_dims(width, height, crop); let setup = CaptureSetup { output_path: output_path.clone(), + ffmpeg_path, width, height, - audio, + fps: TARGET_FPS, + crop, }; let cursor_setting = if capture_cursor { @@ -113,7 +184,7 @@ pub fn start( SecondaryWindowSettings::Default, MinimumUpdateIntervalSettings::Default, DirtyRegionSettings::Default, - ColorFormat::Rgba8, + ColorFormat::Bgra8, setup, ); @@ -123,13 +194,34 @@ pub fn start( Ok(CaptureSession { output_path, started_at: Instant::now(), - width, - height, + width: out_w, + height: out_h, crop, control, }) } +fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option) -> (u32, u32) { + let (raw_w, raw_h) = match crop { + Some(c) => { + let x = c.x.max(0) as u32; + let y = c.y.max(0) as u32; + ( + c.width.min(monitor_w.saturating_sub(x)), + c.height.min(monitor_h.saturating_sub(y)), + ) + } + None => (monitor_w, monitor_h), + }; + if raw_w > MAX_ENCODE_WIDTH { + let scale = MAX_ENCODE_WIDTH as f64 / raw_w as f64; + let nh = (raw_h as f64 * scale).round() as u32; + (MAX_ENCODE_WIDTH, (nh / 2) * 2) + } else { + ((raw_w / 2) * 2, (raw_h / 2) * 2) + } +} + impl CaptureSession { pub fn stop(self) -> Result { self.control diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 93715a1..94cddd0 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -69,19 +70,83 @@ pub fn transcode(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { std::fs::create_dir_all(parent).context("creating output dir")?; } + let encoders = list_encoders(ffmpeg)?; + match req.format { - Format::Mp4 => two_pass_video(ffmpeg, req, mp4_video_codec(req.mp4_codec), "aac", "mp4"), - Format::Webm => two_pass_video( - ffmpeg, - req, - webm_video_codec(req.webm_codec), - "libopus", - "webm", - ), + Format::Mp4 => { + let codec = pick_video_codec( + &encoders, + &[mp4_video_codec(req.mp4_codec), "libx264"], + )?; + let audio = pick_audio_codec(&encoders, &["aac", "libfdk_aac"])?; + two_pass_video(ffmpeg, req, codec, audio, "mp4") + } + Format::Webm => { + let codec = pick_video_codec( + &encoders, + &[webm_video_codec(req.webm_codec), "libvpx-vp9", "libvpx"], + )?; + let audio = pick_audio_codec(&encoders, &["libopus", "libvorbis"])?; + two_pass_video(ffmpeg, req, codec, audio, "webm") + } Format::Gif => encode_gif(ffmpeg, req), } } +fn list_encoders(ffmpeg: &Path) -> Result> { + let out = Command::new(ffmpeg) + .args(["-hide_banner", "-encoders"]) + .output() + .context("listing ffmpeg encoders")?; + let text = String::from_utf8_lossy(&out.stdout); + let mut set: HashSet = HashSet::new(); + for line in text.lines() { + let trimmed = line.trim_start(); + let mut iter = trimmed.split_whitespace(); + let (Some(flags), Some(name)) = (iter.next(), iter.next()) else { + continue; + }; + if flags.len() != 6 { + continue; + } + if !matches!(flags.chars().next(), Some('V' | 'A' | 'S')) { + continue; + } + set.insert(name.to_string()); + } + Ok(set) +} + +fn pick_video_codec<'a>( + encoders: &HashSet, + candidates: &[&'a str], +) -> Result<&'a str> { + for c in candidates { + if encoders.contains(*c) { + return Ok(c); + } + } + bail!( + "no video encoder available - tried {}", + candidates.join(", ") + ) +} + +fn pick_audio_codec<'a>( + encoders: &HashSet, + candidates: &[&'a str], +) -> Result<&'a str> { + for c in candidates { + if encoders.contains(*c) { + return Ok(c); + } + } + bail!( + "no audio encoder available - tried {}", + candidates.join(", ") + ) +} + fn mp4_video_codec(c: Mp4Codec) -> &'static str { match c { Mp4Codec::H264 => "libx264", @@ -97,7 +162,7 @@ fn webm_video_codec(c: WebmCodec) -> &'static str { } fn video_bitrate_kbps(req: &TranscodeRequest) -> Result { - let target_bits = req.target_bytes.saturating_mul(8) as f64; + let target_bits = (req.target_bytes as f64) * 8.0 * 0.95; let audio_bits = if req.keep_audio { AUDIO_BITRATE_KBPS as f64 * 1000.0 * req.duration_secs } else { @@ -118,10 +183,11 @@ fn two_pass_video( audio_codec: &str, container: &str, ) -> Result<()> { + let _ = container; let bitrate_kbps = video_bitrate_kbps(req)?; let bitrate = format!("{bitrate_kbps}k"); - let log_stem = req.scratch_dir.join(format!("ffmpeg2pass-{container}")); + let log_stem = req.scratch_dir.join("ffmpeg2pass"); let log_stem_str = log_stem .to_str() .ok_or_else(|| anyhow!("scratch dir contains non-UTF8"))?; @@ -145,7 +211,7 @@ fn two_pass_video( .args(["-pass", "1"]) .args(["-passlogfile", log_stem_str]) .arg("-an") - .args(["-f", container]) + .args(["-f", "null"]) .arg(null_target); run(&mut pass1, "pass 1")?; @@ -355,6 +421,8 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re } fn run(cmd: &mut Command, label: &str) -> Result<()> { + use std::process::Stdio; + let mut printable = OsString::from(label); printable.push(": "); printable.push(cmd.get_program()); @@ -364,9 +432,14 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> { } tracing::debug!("{}", printable.to_string_lossy()); - let status = cmd.status().with_context(|| format!("spawning ffmpeg for {label}"))?; - if !status.success() { - bail!("ffmpeg {label} exited with {status}"); + cmd.stdout(Stdio::null()).stderr(Stdio::piped()); + let output = cmd + .output() + .with_context(|| format!("spawning ffmpeg for {label}"))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let tail: String = stderr.lines().rev().take(12).collect::>().into_iter().rev().collect::>().join("\n"); + bail!("ffmpeg {label} exited with {}: {}", output.status, tail); } Ok(()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fbbc770..77e2afe 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -11,6 +11,8 @@ use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, Manager, State}; +use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState}; +use std::str::FromStr; use crate::bootstrap::FfmpegStatus; use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec}; @@ -167,11 +169,40 @@ fn get_config(state: State<'_, AppState>) -> Config { state.config.lock().expect("config mutex").clone() } +fn parse_shortcut(s: &str) -> Option { + Shortcut::from_str(s).ok() +} + +fn register_hotkeys(app: &AppHandle, cfg: &Config) { + let gs = app.global_shortcut(); + let _ = gs.unregister_all(); + let mut registered: Vec<(Shortcut, &'static str)> = Vec::new(); + if let Some(s) = cfg.hotkeys.start.as_deref().and_then(parse_shortcut) { + registered.push((s, "start")); + } + if let Some(s) = cfg.hotkeys.stop.as_deref().and_then(parse_shortcut) { + registered.push((s, "stop")); + } + if let Some(s) = cfg.hotkeys.pause.as_deref().and_then(parse_shortcut) { + registered.push((s, "pause")); + } + for (sc, _) in ®istered { + if let Err(e) = gs.register(*sc) { + tracing::warn!("registering shortcut failed: {e}"); + } + } +} + #[tauri::command] -fn save_config(state: State<'_, AppState>, config: Config) -> Result<(), String> { +fn save_config( + app: AppHandle, + state: State<'_, AppState>, + config: Config, +) -> Result<(), String> { let path = config::config_path(&state.app_dir); config.save(&path).map_err(|e| format!("{e:#}"))?; - *state.config.lock().expect("config mutex") = config; + *state.config.lock().expect("config mutex") = config.clone(); + register_hotkeys(&app, &config); Ok(()) } @@ -218,8 +249,15 @@ fn clear_temp_segments(app_dir: &Path) { let _ = std::fs::remove_file(temp.join("recording.mp4")); } +fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) { + if let Some(win) = app.get_webview_window("overlay") { + let _ = win.set_ignore_cursor_events(enabled); + } +} + #[tauri::command] fn start_capture( + app: AppHandle, state: State<'_, AppState>, request: Option, ) -> Result<(), String> { @@ -237,14 +275,22 @@ fn start_capture( let crop = request.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 session = capture::start( output, + ffmpeg.clone(), cfg.capture.capture_cursor, cfg.capture.capture_audio, crop, ) .map_err(|e| format!("{e:#}"))?; + set_overlay_clickthrough(&app, true); + let session_state = SessionState { segments: Vec::new(), total_recorded_secs: 0.0, @@ -302,14 +348,20 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> { }; let output = segment_path(&state.app_dir, next_idx); - let session = capture::start(output, capture_cursor, audio, crop) + 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, audio, crop) .map_err(|e| format!("{e:#}"))?; *state.capture.lock().expect("capture mutex") = Some(session); Ok(()) } #[tauri::command] -fn stop_capture(state: State<'_, AppState>) -> Result { +fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result { + set_overlay_clickthrough(&app, false); + let mut ss = state .session .lock() @@ -373,6 +425,21 @@ pub struct ExportRequest { pub trim_start_secs: Option, #[serde(default)] pub trim_end_secs: Option, + #[serde(default)] + pub output_path: Option, +} + +#[tauri::command] +fn default_output_path(state: State<'_, AppState>, format: Format) -> String { + let cfg = state.config.lock().expect("config mutex").clone(); + let dir = output_dir(&state.app_dir, &cfg); + dir.join(format!( + "bytesize-{}.{}", + timestamp_slug(), + ext_for(format) + )) + .to_string_lossy() + .into_owned() } #[tauri::command] @@ -404,12 +471,27 @@ pub struct ExportResult { const OVERLAY_BORDER_LOGICAL_PX: f64 = 2.0; const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0; +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 as *mut _); + unsafe { + SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE) + .map_err(|e| format!("SetWindowDisplayAffinity: {e}"))?; + } + Ok(()) +} + #[tauri::command] 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())?; + let _ = mark_overlay_excluded_from_capture(&win); win.set_focus().map_err(|e| e.to_string()) } @@ -452,11 +534,32 @@ fn get_overlay_rect(app: AppHandle) -> Result { #[tauri::command] fn reveal_in_explorer(path: String) -> Result<(), String> { + use std::os::windows::process::CommandExt; use std::process::Command; - Command::new("explorer.exe") - .arg(format!("/select,{path}")) - .spawn() - .map_err(|e| format!("opening explorer: {e}"))?; + + let canonical = std::fs::canonicalize(&path).ok(); + let normalized = canonical + .as_ref() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.clone()); + 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(()) } @@ -485,13 +588,21 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result PathBuf::from(p), + _ => { + let out_dir = output_dir(&state.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 @@ -516,7 +627,7 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result(); + let guard = st.config.lock().expect("config mutex"); + guard.clone() + }; + 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 { + let _ = app.emit("hotkey", k); + } + }) + .build(), + ) .manage(state) .setup(|app| { - let check_on_launch = { + let (check_on_launch, cfg) = { let st = app.state::(); - let cfg = st.config.lock().expect("config mutex"); - cfg.updates.check_on_launch + let cfg = st.config.lock().expect("config mutex").clone(); + (cfg.updates.check_on_launch, cfg) }; + register_hotkeys(app.handle(), &cfg); if check_on_launch { let handle = app.handle().clone(); tauri::async_runtime::spawn(async move { @@ -590,6 +749,7 @@ pub fn run() { resume_capture, stop_capture, export, + default_output_path, extract_thumbnails, reveal_in_explorer, open_url, diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index eed049f..4dcfe51 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -9,6 +9,7 @@ type RecordedClip, type ExportResult, } from "./api" + import { save } from "@tauri-apps/plugin-dialog" type Phase = "idle" | "recording" | "paused" | "editing" | "exporting" | "done" @@ -32,12 +33,31 @@ let loadingThumbs: boolean = $state(false) let trimStart: number = $state(0) let trimEnd: number = $state(0) + let outputPath: string = $state("") + let pathOverridden: boolean = $state(false) - onMount(async () => { - config = await api.getConfig() - format = config.export.default_format - fps = config.capture.default_fps - keepAudio = config.capture.capture_audio + onMount(() => { + let unlisten: (() => void) | null = null + void (async () => { + config = await api.getConfig() + format = config.export.default_format + fps = config.capture.default_fps + keepAudio = config.capture.capture_audio + + unlisten = await 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() + } + }) + })() + return () => { + unlisten?.() + } }) function tick() { @@ -71,7 +91,6 @@ if (useFrame) { try { crop = await api.getOverlayRect() - await api.hideOverlay() } catch (e) { errMsg = String(e) return @@ -83,9 +102,6 @@ tick() } catch (e) { errMsg = String(e) - if (useFrame) { - await api.showOverlay().catch(() => {}) - } } } @@ -99,12 +115,35 @@ targetMB = Math.min(50, Math.max(minMB(c.duration_secs), sensible)) trimStart = 0 trimEnd = c.duration_secs + pathOverridden = false + outputPath = await api.defaultOutputPath(format) } catch (e) { errMsg = String(e) phase = "idle" } } + async function browseOutput() { + const filters = format === "gif" + ? [{ name: "GIF", extensions: ["gif"] }] + : format === "webm" + ? [{ name: "WebM", extensions: ["webm"] }] + : [{ name: "MP4", extensions: ["mp4"] }] + const picked = await save({ defaultPath: outputPath, filters }) + if (picked) { + outputPath = picked + pathOverridden = true + } + } + + $effect(() => { + if (phase === "editing" && !pathOverridden && format) { + void api.defaultOutputPath(format).then((p) => { + if (!pathOverridden) outputPath = p + }) + } + }) + async function pauseRec() { clearTick() try { @@ -180,6 +219,7 @@ deleted_frame_indices: format === "gif" ? Array.from(deletedFrames) : [], trim_start_secs: tsStart, trim_end_secs: tsEnd, + output_path: outputPath.trim() || null, }) exportResult = result phase = "done" @@ -228,16 +268,16 @@

{#if useFrame} - Drag the green frame on screen to position the region you want to - capture. The frame hides automatically while recording. + The green frame stays visible during recording but is excluded from + the capture itself. Drag it to position the region. {:else} - Captures your full primary monitor. Click "show capture frame" to draw - a region instead. + Captures your full primary monitor. Toggle the capture frame on to + record a region instead. {/if}

{:else if phase === "recording" || phase === "paused"} @@ -398,6 +438,20 @@ {/if} +
+ +
+
@@ -666,6 +720,34 @@ color: #888; font-size: 0.85rem; } + .path-row { + margin: 1rem 0; + } + .path-row label { + display: grid; + gap: 0.4rem; + color: #aaa; + font-size: 0.85rem; + } + .path-input { + display: grid; + grid-template-columns: 1fr auto; + gap: 0.4rem; + } + .path-input input { + font: inherit; + font-family: ui-monospace, monospace; + font-size: 0.85rem; + padding: 0.45rem 0.6rem; + border: 1px solid #444; + background: #222; + color: inherit; + border-radius: 4px; + } + .path-input input:focus { + outline: none; + border-color: #4a8; + } .trim { margin: 0.5rem 0 1.5rem; } diff --git a/src/lib/Overlay.svelte b/src/lib/Overlay.svelte index e51f610..3f80b43 100644 --- a/src/lib/Overlay.svelte +++ b/src/lib/Overlay.svelte @@ -2,11 +2,12 @@ import { onMount } from "svelte" import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow" + const win = getCurrentWebviewWindow() + let width: number = $state(0) let height: number = $state(0) onMount(() => { - const win = getCurrentWebviewWindow() const updateSize = async () => { const size = await win.innerSize() const scale = await win.scaleFactor() @@ -14,15 +15,27 @@ height = Math.round(size.height / scale) } updateSize() - const unlisten = win.onResized(updateSize) + const unlistenPromise = win.onResized(updateSize) return () => { - unlisten.then((fn) => fn()) + unlistenPromise.then((fn) => fn()) } }) + + function startDrag(e: MouseEvent) { + if (e.button === 0) { + e.preventDefault() + void win.startDragging().catch((err) => console.error("startDragging", err)) + } + }
-
+ @@ -59,6 +72,7 @@ font: 11px ui-monospace, monospace; cursor: grab; flex-shrink: 0; + user-select: none; } .titlebar:active { cursor: grabbing; diff --git a/src/lib/api.ts b/src/lib/api.ts index 43434e7..76c639d 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -85,6 +85,7 @@ export type ExportRequest = { deleted_frame_indices: number[] trim_start_secs?: number | null trim_end_secs?: number | null + output_path?: string | null } export type ExportResult = { @@ -111,9 +112,13 @@ export const api = { getOverlayRect: () => invoke("get_overlay_rect"), extractThumbnails: (fps: number) => invoke("extract_thumbnails", { fps }), + defaultOutputPath: (format: Format) => + invoke("default_output_path", { format }), openUrl: (url: string) => invoke("open_url", { url }), onUpdateAvailable: (handler: (info: UpdateInfo) => void): Promise => listen("update-available", (e) => handler(e.payload)), + onHotkey: (handler: (kind: "start" | "stop" | "pause") => void): Promise => + listen<"start" | "stop" | "pause">("hotkey", (e) => handler(e.payload)), } export function formatBytes(n: number): string {