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
+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,