global hotkeys wired up

This commit is contained in:
2026-05-12 01:33:47 +03:00
parent 72e7a0d33b
commit 2882e78795
10 changed files with 637 additions and 107 deletions
+56 -24
View File
@@ -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<GithubAsset>,
}
#[derive(Debug, Deserialize)]
struct GithubAsset {
name: String,
browser_download_url: String,
#[serde(default)]
digest: Option<String>,
}
pub async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()>
where
F: FnMut(u64, Option<u64>) + 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<GithubAsset> {
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<String>) -> 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);
+123 -31
View File
@@ -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<CaptureRect>,
}
pub struct CaptureHandler {
encoder: Option<VideoEncoder>,
stdin: Option<ChildStdin>,
child: Option<Child>,
width: u32,
height: u32,
scratch: Vec<u8>,
}
impl GraphicsCaptureApiHandler for CaptureHandler {
@@ -36,15 +44,60 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
fn new(ctx: CaptureContext<Self::Flags>) -> Result<Self, Self::Error> {
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<String> = 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<CaptureRect>,
) -> Result<CaptureSession> {
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<CaptureRect>) -> (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<PathBuf> {
self.control
+87 -14
View File
@@ -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<HashSet<String>> {
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<String> = 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<String>,
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<String>,
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<u64> {
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::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n");
bail!("ffmpeg {label} exited with {}: {}", output.status, tail);
}
Ok(())
}
+179 -19
View File
@@ -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> {
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 &registered {
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<StartCaptureRequest>,
) -> 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<RecordedClip, String> {
fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedClip, String> {
set_overlay_clickthrough(&app, false);
let mut ss = state
.session
.lock()
@@ -373,6 +425,21 @@ pub struct ExportRequest {
pub trim_start_secs: Option<f64>,
#[serde(default)]
pub trim_end_secs: Option<f64>,
#[serde(default)]
pub output_path: Option<String>,
}
#[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<CaptureRect, String> {
#[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<ExportRe
return Err("ffmpeg.exe not found - run the encoder setup first".to_string());
}
let out_dir = output_dir(&state.app_dir, &cfg);
std::fs::create_dir_all(&out_dir).map_err(|e| format!("creating output dir: {e}"))?;
let out_path = out_dir.join(format!(
"bytesize-{}.{}",
timestamp_slug(),
ext_for(request.format)
));
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(&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<ExportRe
webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&state.app_dir),
crop: clip.crop,
crop: None,
deleted_frame_indices: request.deleted_frame_indices,
trim_start_secs: trim_start,
trim_end_secs: trim_end,
@@ -558,13 +669,61 @@ pub fn run() {
tauri::Builder::default()
.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::<AppState>();
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::<AppState>();
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,