1430 lines
44 KiB
Rust
1430 lines
44 KiB
Rust
mod audio;
|
|
mod bootstrap;
|
|
mod capture;
|
|
mod clicks;
|
|
mod config;
|
|
mod encode;
|
|
mod updates;
|
|
mod window_picker;
|
|
mod windows_list;
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
|
|
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};
|
|
|
|
#[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<Config>,
|
|
pub capture: Mutex<Option<capture::CaptureSession>>,
|
|
pub audio: Mutex<Option<audio::AudioSession>>,
|
|
pub click_recorder: Mutex<Option<clicks::ClickRecorder>>,
|
|
pub last_clip: Mutex<Option<RecordedClip>>,
|
|
pub session: Mutex<Option<SessionState>>,
|
|
pub picker: Mutex<Option<window_picker::PickerSession>>,
|
|
}
|
|
|
|
pub struct SessionState {
|
|
pub segments: Vec<PathBuf>,
|
|
pub audio_segments: Vec<PathBuf>,
|
|
pub audio_sample_rate: Option<u32>,
|
|
pub audio_channels: Option<u16>,
|
|
pub total_recorded_secs: f64,
|
|
pub capture_cursor: bool,
|
|
pub audio: bool,
|
|
pub crop: Option<CaptureRect>,
|
|
pub width: u32,
|
|
pub height: u32,
|
|
pub monitor_width: u32,
|
|
pub monitor_height: u32,
|
|
pub clicks: Vec<clicks::Click>,
|
|
pub segment_start_offsets: Vec<f64>,
|
|
}
|
|
|
|
#[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<CaptureRect>,
|
|
pub clicks: Vec<clicks::Click>,
|
|
}
|
|
|
|
fn exe_dir() -> Result<PathBuf> {
|
|
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 {
|
|
use windows::Win32::System::SystemInformation::GetLocalTime;
|
|
let st = unsafe { GetLocalTime() };
|
|
format!(
|
|
"{:04}{:02}{:02}-{:02}{:02}{:02}",
|
|
st.wYear,
|
|
st.wMonth,
|
|
st.wDay,
|
|
st.wHour,
|
|
st.wMinute,
|
|
st.wSecond
|
|
)
|
|
}
|
|
|
|
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 = state.config.lock().expect("config mutex");
|
|
AppStatus {
|
|
ffmpeg: bootstrap::check(&state.app_dir),
|
|
needs_first_run: cfg.needs_first_run(),
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
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()
|
|
}
|
|
|
|
/// 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<bool>,
|
|
pub stop_ok: Option<bool>,
|
|
pub pause_ok: Option<bool>,
|
|
}
|
|
|
|
fn register_hotkeys(app: &AppHandle, cfg: &Config) -> HotkeyRegistrationResult {
|
|
let gs = app.global_shortcut();
|
|
let _ = 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,
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn save_config(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
config: Config,
|
|
) -> Result<SaveConfigResult, String> {
|
|
let path = config::config_path(&state.app_dir);
|
|
config.save(&path).map_err(|e| format!("{e:#}"))?;
|
|
*state.config.lock().expect("config mutex") = config.clone();
|
|
let hotkey_result = register_hotkeys(&app, &config);
|
|
Ok(SaveConfigResult { hotkey_result })
|
|
}
|
|
|
|
#[derive(Clone, Serialize)]
|
|
struct DownloadProgress {
|
|
downloaded: u64,
|
|
total: Option<u64>,
|
|
}
|
|
|
|
#[derive(Clone, Serialize)]
|
|
struct UpdateDownloadProgress {
|
|
downloaded: u64,
|
|
total: Option<u64>,
|
|
}
|
|
|
|
#[tauri::command]
|
|
async fn download_update(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
url: String,
|
|
) -> Result<(), String> {
|
|
let dest = updates::pending_update_path(&state.app_dir);
|
|
let app_handle = app.clone();
|
|
updates::download_to(&url, &dest, move |downloaded, total| {
|
|
let _ = app_handle.emit(
|
|
"update-download-progress",
|
|
UpdateDownloadProgress { downloaded, total },
|
|
);
|
|
})
|
|
.await
|
|
.map_err(|e| format!("{e:#}"))
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn apply_update(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
|
use std::os::windows::process::CommandExt;
|
|
use std::process::Command;
|
|
if !updates::has_pending_update(&state.app_dir) {
|
|
return Err("no pending update to apply".to_string());
|
|
}
|
|
let bat = updates::write_apply_script(&state.app_dir).map_err(|e| format!("{e:#}"))?;
|
|
Command::new("cmd")
|
|
.args(["/c", "start", "", ""])
|
|
.raw_arg(format!("\"{}\"", bat.to_string_lossy()))
|
|
.spawn()
|
|
.map_err(|e| format!("spawning apply script: {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| {
|
|
let _ = app_handle.emit(
|
|
"ffmpeg-progress",
|
|
DownloadProgress { downloaded, total },
|
|
);
|
|
})
|
|
.await
|
|
.map_err(|e| format!("{e:#}"))
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct StartCaptureRequest {
|
|
pub crop: Option<CaptureRect>,
|
|
}
|
|
|
|
fn segment_path(app_dir: &Path, idx: usize) -> PathBuf {
|
|
temp_dir(app_dir).join(format!("segment-{:03}.mp4", idx))
|
|
}
|
|
|
|
fn audio_segment_path(app_dir: &Path, idx: usize) -> PathBuf {
|
|
temp_dir(app_dir).join(format!("audio-{:03}.pcm", idx))
|
|
}
|
|
|
|
fn clear_temp_segments(app_dir: &Path) {
|
|
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() {
|
|
if (name.starts_with("segment-") && name.ends_with(".mp4"))
|
|
|| (name.starts_with("audio-") && name.ends_with(".pcm"))
|
|
{
|
|
let _ = std::fs::remove_file(entry.path());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let _ = std::fs::remove_file(temp.join("recording.mp4"));
|
|
let _ = std::fs::remove_file(temp.join("video-concat.mp4"));
|
|
let _ = std::fs::remove_file(temp.join("audio-concat.pcm"));
|
|
}
|
|
|
|
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
|
|
fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs: f64) -> Result<()> {
|
|
use std::io::Write;
|
|
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0;
|
|
let target_bytes = (target_secs * bytes_per_sec).round() as u64;
|
|
let current_bytes = std::fs::metadata(path)?.len();
|
|
if current_bytes == target_bytes {
|
|
return Ok(());
|
|
}
|
|
if current_bytes < target_bytes {
|
|
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
|
|
let zeros = vec![0u8; 64 * 1024];
|
|
let mut remaining = target_bytes - current_bytes;
|
|
while remaining > 0 {
|
|
let to_write = remaining.min(zeros.len() as u64) as usize;
|
|
file.write_all(&zeros[..to_write])?;
|
|
remaining -= to_write as u64;
|
|
}
|
|
} else {
|
|
let file = std::fs::OpenOptions::new().write(true).open(path)?;
|
|
file.set_len(target_bytes)?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
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> {
|
|
{
|
|
let slot = state.capture.lock().expect("capture mutex");
|
|
if slot.is_some() {
|
|
return Err("a capture is already running".to_string());
|
|
}
|
|
}
|
|
let cfg = state.config.lock().expect("config mutex").clone();
|
|
let temp = temp_dir(&state.app_dir);
|
|
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?;
|
|
clear_temp_segments(&state.app_dir);
|
|
|
|
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 (monitor_w, monitor_h) =
|
|
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
|
|
|
let session = capture::start(
|
|
output,
|
|
ffmpeg.clone(),
|
|
cfg.capture.capture_cursor,
|
|
cfg.capture.capture_audio,
|
|
crop,
|
|
cfg.capture.default_fps,
|
|
)
|
|
.map_err(|e| format!("{e:#}"))?;
|
|
|
|
let audio_session = if cfg.capture.capture_audio {
|
|
let audio_path = audio_segment_path(&state.app_dir, 1);
|
|
match audio::start(audio_path) {
|
|
Ok(s) => Some(s),
|
|
Err(e) => {
|
|
tracing::warn!("audio capture failed to start: {e:#}");
|
|
let _ = app.emit("audio-failed", e.to_string());
|
|
None
|
|
}
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
|
|
set_overlay_clickthrough(&app, true);
|
|
|
|
let (a_sr, a_ch) = audio_session
|
|
.as_ref()
|
|
.map(|s| (Some(s.sample_rate), Some(s.channels)))
|
|
.unwrap_or((None, None));
|
|
|
|
let session_state = SessionState {
|
|
segments: Vec::new(),
|
|
audio_segments: Vec::new(),
|
|
audio_sample_rate: a_sr,
|
|
audio_channels: a_ch,
|
|
total_recorded_secs: 0.0,
|
|
capture_cursor: cfg.capture.capture_cursor,
|
|
audio: cfg.capture.capture_audio,
|
|
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 = if cfg.capture.capture_cursor {
|
|
Some(clicks::start())
|
|
} else {
|
|
None
|
|
};
|
|
|
|
*state.session.lock().expect("session mutex") = Some(session_state);
|
|
*state.capture.lock().expect("capture mutex") = Some(session);
|
|
*state.audio.lock().expect("audio mutex") = audio_session;
|
|
*state.click_recorder.lock().expect("click mutex") = click_rec;
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
|
let session = state
|
|
.capture
|
|
.lock()
|
|
.expect("capture mutex")
|
|
.take()
|
|
.ok_or_else(|| "no capture in progress".to_string())?;
|
|
let elapsed = session.started_at.elapsed().as_secs_f64();
|
|
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
|
|
|
let audio_path = state
|
|
.audio
|
|
.lock()
|
|
.expect("audio mutex")
|
|
.take()
|
|
.and_then(|a| a.stop().ok());
|
|
|
|
let new_clicks: Vec<clicks::Click> = state
|
|
.click_recorder
|
|
.lock()
|
|
.expect("click mutex")
|
|
.take()
|
|
.map(|r| r.stop())
|
|
.unwrap_or_default();
|
|
|
|
let mut ss = state.session.lock().expect("session mutex");
|
|
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(ap) = audio_path {
|
|
ss.audio_segments.push(ap);
|
|
}
|
|
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 slot = state.capture.lock().expect("capture mutex");
|
|
if slot.is_some() {
|
|
return Err("a capture is already running".to_string());
|
|
}
|
|
}
|
|
let (capture_cursor, audio, crop, next_idx) = {
|
|
let ss = state.session.lock().expect("session mutex");
|
|
let ss = ss
|
|
.as_ref()
|
|
.ok_or_else(|| "no session to resume".to_string())?;
|
|
(
|
|
ss.capture_cursor,
|
|
ss.audio,
|
|
ss.crop,
|
|
ss.segments.len() + 1,
|
|
)
|
|
};
|
|
|
|
let fps = state.config.lock().expect("config mutex").capture.default_fps;
|
|
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, audio, crop, fps)
|
|
.map_err(|e| format!("{e:#}"))?;
|
|
|
|
let audio_session = if audio {
|
|
let audio_path = audio_segment_path(&state.app_dir, next_idx);
|
|
match audio::start(audio_path) {
|
|
Ok(s) => Some(s),
|
|
Err(e) => {
|
|
tracing::warn!("audio resume failed: {e:#}");
|
|
let _ = app.emit("audio-failed", e.to_string());
|
|
None
|
|
}
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
|
|
let click_rec = if capture_cursor {
|
|
Some(clicks::start())
|
|
} else {
|
|
None
|
|
};
|
|
|
|
*state.capture.lock().expect("capture mutex") = Some(session);
|
|
*state.audio.lock().expect("audio mutex") = audio_session;
|
|
*state.click_recorder.lock().expect("click mutex") = click_rec;
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
|
set_overlay_clickthrough(&app, false);
|
|
|
|
let mut ss = state
|
|
.session
|
|
.lock()
|
|
.expect("session mutex")
|
|
.take()
|
|
.ok_or_else(|| "no session to stop".to_string())?;
|
|
|
|
let live = state.capture.lock().expect("capture mutex").take();
|
|
if let Some(session) = live {
|
|
let elapsed = session.started_at.elapsed().as_secs_f64();
|
|
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
|
ss.segments.push(path);
|
|
ss.total_recorded_secs += elapsed;
|
|
}
|
|
|
|
let live_audio = state.audio.lock().expect("audio mutex").take();
|
|
if let Some(a) = live_audio {
|
|
if let Ok(p) = a.stop() {
|
|
ss.audio_segments.push(p);
|
|
}
|
|
}
|
|
|
|
let live_clicks = state
|
|
.click_recorder
|
|
.lock()
|
|
.expect("click mutex")
|
|
.take()
|
|
.map(|r| r.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("recording.mp4");
|
|
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 {
|
|
let _ = std::fs::remove_file(seg);
|
|
}
|
|
vc
|
|
};
|
|
|
|
let have_audio = !ss.audio_segments.is_empty()
|
|
&& ss.audio_sample_rate.is_some()
|
|
&& ss.audio_channels.is_some();
|
|
|
|
if have_audio {
|
|
if !ffmpeg.is_file() {
|
|
return Err("ffmpeg.exe not found for audio mux".to_string());
|
|
}
|
|
let audio_concat = temp.join("audio-concat.pcm");
|
|
encode::concat_pcm(&ss.audio_segments, &audio_concat)
|
|
.map_err(|e| format!("audio concat: {e:#}"))?;
|
|
adjust_audio_length(
|
|
&audio_concat,
|
|
ss.audio_sample_rate.unwrap(),
|
|
ss.audio_channels.unwrap(),
|
|
ss.total_recorded_secs,
|
|
)
|
|
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
|
|
encode::mux_with_audio(
|
|
&ffmpeg,
|
|
&video_concat,
|
|
&audio_concat,
|
|
ss.audio_sample_rate.unwrap(),
|
|
ss.audio_channels.unwrap(),
|
|
&final_path,
|
|
)
|
|
.map_err(|e| format!("mux: {e:#}"))?;
|
|
if video_concat != final_path {
|
|
let _ = std::fs::remove_file(&video_concat);
|
|
}
|
|
let _ = std::fs::remove_file(&audio_concat);
|
|
for ap in &ss.audio_segments {
|
|
let _ = std::fs::remove_file(ap);
|
|
}
|
|
} else if video_concat != final_path {
|
|
std::fs::rename(&video_concat, &final_path)
|
|
.or_else(|_| std::fs::copy(&video_concat, &final_path).map(|_| ()))
|
|
.map_err(|e| format!("finalizing: {e}"))?;
|
|
let _ = std::fs::remove_file(&video_concat);
|
|
}
|
|
|
|
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(),
|
|
};
|
|
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
|
|
Ok(clip)
|
|
}
|
|
|
|
#[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<u32>,
|
|
#[serde(default)]
|
|
pub trim_start_secs: Option<f64>,
|
|
#[serde(default)]
|
|
pub trim_end_secs: Option<f64>,
|
|
#[serde(default)]
|
|
pub output_path: Option<String>,
|
|
#[serde(default)]
|
|
pub crop: Option<CaptureRect>,
|
|
}
|
|
|
|
#[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()
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct PreviewRequest {
|
|
pub format: Format,
|
|
pub fps: u32,
|
|
pub target_bytes: u64,
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn render_preview(
|
|
state: State<'_, AppState>,
|
|
request: PreviewRequest,
|
|
) -> Result<PathBuf, String> {
|
|
let clip = state
|
|
.last_clip
|
|
.lock()
|
|
.expect("clip mutex")
|
|
.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 {
|
|
// For GIF, derive a width that fits the target byte budget.
|
|
let frames = (request.fps as f64 * clip.duration_secs).max(1.0);
|
|
let budget = (request.target_bytes as f64) / (frames * 0.5);
|
|
let aspect = if clip.height == 0 {
|
|
16.0 / 9.0
|
|
} else {
|
|
clip.width as f64 / clip.height as f64
|
|
};
|
|
let w = (budget * aspect).sqrt();
|
|
(w.clamp(120.0, clip.width as f64) as u32 / 2) * 2
|
|
} else {
|
|
// For video formats, scale to a reasonable preview size.
|
|
clip.width.min(1280).max(160)
|
|
};
|
|
|
|
let preview_path = temp_dir(&state.app_dir).join("preview.png");
|
|
let midpoint = (clip.duration_secs / 2.0).max(0.0);
|
|
encode::render_preview(&ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width)
|
|
.map_err(|e| format!("{e:#}"))?;
|
|
Ok(preview_path)
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn extract_thumbnails(
|
|
state: State<'_, AppState>,
|
|
fps: u32,
|
|
) -> Result<Vec<PathBuf>, String> {
|
|
let clip = state
|
|
.last_clip
|
|
.lock()
|
|
.expect("clip mutex")
|
|
.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:#}"))
|
|
}
|
|
|
|
#[derive(Debug, Serialize)]
|
|
pub struct ExportResult {
|
|
pub output_path: PathBuf,
|
|
pub size_bytes: u64,
|
|
}
|
|
|
|
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
|
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0;
|
|
|
|
fn apply_overlay_region(_win: &tauri::WebviewWindow) -> Result<(), String> {
|
|
Ok(())
|
|
}
|
|
|
|
fn start_overlay_clickthrough_poll(app: AppHandle) {
|
|
use std::time::Duration;
|
|
use windows::Win32::Foundation::{HWND, POINT, RECT};
|
|
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
|
use windows::Win32::UI::HiDpi::GetDpiForWindow;
|
|
use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect};
|
|
|
|
std::thread::spawn(move || {
|
|
let mut last_inner: Option<bool> = None;
|
|
loop {
|
|
std::thread::sleep(Duration::from_millis(30));
|
|
|
|
let overlay = match app.get_webview_window("overlay") {
|
|
Some(w) => w,
|
|
None => continue,
|
|
};
|
|
if !overlay.is_visible().unwrap_or(false) {
|
|
last_inner = None;
|
|
continue;
|
|
}
|
|
|
|
// During recording, the overlay should always be click-through.
|
|
// start_capture already sets ignore_cursor_events(true). Skip polling
|
|
// so we don't fight it.
|
|
let state = app.state::<AppState>();
|
|
let is_recording = state.capture.lock().expect("capture mutex").is_some();
|
|
if is_recording {
|
|
last_inner = Some(true);
|
|
continue;
|
|
}
|
|
|
|
let mut pt = POINT::default();
|
|
if unsafe { GetCursorPos(&mut pt) }.is_err() {
|
|
continue;
|
|
}
|
|
let raw = match overlay.hwnd() {
|
|
Ok(h) => h,
|
|
Err(_) => continue,
|
|
};
|
|
let hwnd = HWND(raw.0 as *mut _);
|
|
|
|
let mut dwm = RECT::default();
|
|
let dwm_ok = unsafe {
|
|
DwmGetWindowAttribute(
|
|
hwnd,
|
|
DWMWA_EXTENDED_FRAME_BOUNDS,
|
|
&mut dwm as *mut RECT as *mut std::ffi::c_void,
|
|
std::mem::size_of::<RECT>() as u32,
|
|
)
|
|
}
|
|
.is_ok()
|
|
&& dwm.right > dwm.left;
|
|
let visible = if dwm_ok {
|
|
dwm
|
|
} else {
|
|
let mut outer = RECT::default();
|
|
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() {
|
|
continue;
|
|
}
|
|
outer
|
|
};
|
|
|
|
let dpi = unsafe { GetDpiForWindow(hwnd) };
|
|
let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 };
|
|
let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
|
|
let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
|
|
|
|
let inner_left = visible.left + border;
|
|
let inner_top = visible.top + border + titlebar;
|
|
let inner_right = visible.right - border;
|
|
let inner_bottom = visible.bottom - border;
|
|
|
|
let in_inner = pt.x >= inner_left
|
|
&& pt.x < inner_right
|
|
&& pt.y >= inner_top
|
|
&& pt.y < inner_bottom;
|
|
|
|
if last_inner != Some(in_inner) {
|
|
let _ = overlay.set_ignore_cursor_events(in_inner);
|
|
last_inner = Some(in_inner);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
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);
|
|
let _ = apply_overlay_region(&win);
|
|
win.set_focus().map_err(|e| e.to_string())
|
|
}
|
|
|
|
#[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())?;
|
|
win.hide().map_err(|e| e.to_string())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn set_overlay_size(app: AppHandle, 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())?;
|
|
// Add the titlebar + border to the logical content size so the captured
|
|
// region matches the requested preset.
|
|
let final_w = width as f64 + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
|
let final_h =
|
|
height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
|
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
|
|
.map_err(|e| e.to_string())?;
|
|
let _ = apply_overlay_region(&win);
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn list_windows() -> Vec<windows_list::WindowInfo> {
|
|
windows_list::list_visible_windows()
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn open_window_picker(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
) -> Result<(), String> {
|
|
let (mw, mh) =
|
|
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
|
|
|
let mut exclude: Vec<isize> = 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::info!(
|
|
"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())?;
|
|
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
|
|
picker
|
|
.set_size(Size::Physical(PhysicalSize::new(mw, mh)))
|
|
.map_err(|e| e.to_string())?;
|
|
picker
|
|
.set_position(Position::Physical(PhysicalPosition::new(0, 0)))
|
|
.map_err(|e| e.to_string())?;
|
|
let _ = picker.set_ignore_cursor_events(false);
|
|
let _ = picker.set_always_on_top(true);
|
|
picker.show().map_err(|e| e.to_string())?;
|
|
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 as *mut _);
|
|
let mut gr = RECT::default();
|
|
let _ = unsafe { GetWindowRect(hwnd, &mut gr) };
|
|
let mut dr = RECT::default();
|
|
let _ = unsafe {
|
|
DwmGetWindowAttribute(
|
|
hwnd,
|
|
DWMWA_EXTENDED_FRAME_BOUNDS,
|
|
&mut dr as *mut RECT as *mut std::ffi::c_void,
|
|
std::mem::size_of::<RECT>() as u32,
|
|
)
|
|
};
|
|
tracing::info!(
|
|
"picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})",
|
|
gr.left, gr.top, gr.right, gr.bottom,
|
|
dr.left, dr.top, dr.right, dr.bottom
|
|
);
|
|
}
|
|
|
|
{
|
|
let mut slot = state.picker.lock().expect("picker mutex");
|
|
if let Some(existing) = slot.take() {
|
|
existing.stop();
|
|
}
|
|
*slot = Some(window_picker::start(app.clone(), exclude));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn close_window_picker(
|
|
app: AppHandle,
|
|
state: State<'_, AppState>,
|
|
) -> Result<(), String> {
|
|
if let Some(session) = state.picker.lock().expect("picker mutex").take() {
|
|
session.stop();
|
|
}
|
|
if let Some(picker) = app.get_webview_window("picker") {
|
|
let _ = picker.hide();
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
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 _);
|
|
let mut outer = RECT::default();
|
|
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() {
|
|
return (0, 0, 0, 0);
|
|
}
|
|
let mut dwm = RECT::default();
|
|
let r = unsafe {
|
|
DwmGetWindowAttribute(
|
|
hwnd,
|
|
DWMWA_EXTENDED_FRAME_BOUNDS,
|
|
&mut dwm as *mut RECT as *mut std::ffi::c_void,
|
|
std::mem::size_of::<RECT>() as u32,
|
|
)
|
|
};
|
|
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 };
|
|
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;
|
|
let hr = unsafe {
|
|
GetDpiForMonitor(
|
|
hmonitor,
|
|
MONITOR_DPI_TYPE(0), // MdtEffectiveDpi
|
|
&mut dpi_x,
|
|
&mut dpi_y,
|
|
)
|
|
};
|
|
if hr.is_ok() && dpi_x > 0 {
|
|
dpi_x as f64 / 96.0
|
|
} else {
|
|
1.0
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn set_overlay_to_window(
|
|
app: AppHandle,
|
|
x: i32,
|
|
y: i32,
|
|
width: u32,
|
|
height: u32,
|
|
) -> Result<(), String> {
|
|
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 as i32 / 2);
|
|
let cy = y.saturating_add(height as i32 / 2);
|
|
let scale = scale_factor_at_point(cx, cy);
|
|
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
|
|
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
|
|
|
|
// 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 as i32 + border_phys * 2;
|
|
let visible_h = height as i32 + 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(|h| dwm_insets(h.0 as isize))
|
|
.unwrap_or((0, 0, 0, 0));
|
|
|
|
let outer_x = visible_left - li;
|
|
let outer_y = visible_top - ti;
|
|
let outer_w = (visible_w + li + ri).max(2) as u32;
|
|
let outer_h = (visible_h + ti + bi).max(2) as u32;
|
|
|
|
// 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}"))?;
|
|
use windows::Win32::Foundation::HWND;
|
|
use windows::Win32::UI::WindowsAndMessaging::{
|
|
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOZORDER,
|
|
};
|
|
let hwnd = HWND(raw.0 as *mut _);
|
|
unsafe {
|
|
SetWindowPos(
|
|
hwnd,
|
|
Some(HWND_TOP),
|
|
outer_x,
|
|
outer_y,
|
|
outer_w as i32,
|
|
outer_h as i32,
|
|
SWP_NOACTIVATE | SWP_NOZORDER,
|
|
)
|
|
}
|
|
.map_err(|e| format!("SetWindowPos: {e}"))?;
|
|
|
|
let _ = apply_overlay_region(&win);
|
|
let _ = (visible_left, visible_top, visible_w, visible_h, scale, border_phys, titlebar_phys);
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
|
|
use windows::Win32::Foundation::{HWND, RECT};
|
|
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
|
use windows::Win32::UI::WindowsAndMessaging::GetWindowRect;
|
|
|
|
let win = app
|
|
.get_webview_window("overlay")
|
|
.ok_or_else(|| "overlay window not found".to_string())?;
|
|
let scale = win.scale_factor().map_err(|e| e.to_string())?;
|
|
let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
|
|
let hwnd = HWND(raw.0 as *mut _);
|
|
|
|
let mut dwm = RECT::default();
|
|
let dwm_ok = unsafe {
|
|
DwmGetWindowAttribute(
|
|
hwnd,
|
|
DWMWA_EXTENDED_FRAME_BOUNDS,
|
|
&mut dwm as *mut RECT as *mut std::ffi::c_void,
|
|
std::mem::size_of::<RECT>() as u32,
|
|
)
|
|
}
|
|
.is_ok();
|
|
let visible = if dwm_ok && dwm.right > dwm.left && dwm.bottom > dwm.top {
|
|
dwm
|
|
} else {
|
|
let mut r = RECT::default();
|
|
unsafe { GetWindowRect(hwnd, &mut r) }
|
|
.map_err(|e| format!("GetWindowRect: {e}"))?;
|
|
r
|
|
};
|
|
|
|
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
|
|
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
|
|
|
|
let inset_top = border_phys + titlebar_phys;
|
|
let inset_sides = border_phys;
|
|
|
|
let visible_w = visible.right - visible.left;
|
|
let visible_h = visible.bottom - visible.top;
|
|
|
|
let width = (visible_w - inset_sides * 2).max(2) as u32;
|
|
let height = (visible_h - inset_top - inset_sides).max(2) as u32;
|
|
let width = (width / 2) * 2;
|
|
let height = (height / 2) * 2;
|
|
|
|
Ok(CaptureRect {
|
|
x: visible.left + inset_sides,
|
|
y: visible.top + 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(|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(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn open_url(url: String) -> Result<(), String> {
|
|
use std::process::Command;
|
|
Command::new("cmd")
|
|
.args(["/C", "start", "", &url])
|
|
.spawn()
|
|
.map_err(|e| format!("opening url: {e}"))?;
|
|
Ok(())
|
|
}
|
|
|
|
#[tauri::command]
|
|
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
|
let cfg = state.config.lock().expect("config mutex").clone();
|
|
let clip = state
|
|
.last_clip
|
|
.lock()
|
|
.expect("clip mutex")
|
|
.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 - 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(&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
|
|
.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 = clip.width as f64 / src_w as f64;
|
|
let transformed_clicks: Vec<clicks::Click> = clip
|
|
.clicks
|
|
.iter()
|
|
.map(|c| clicks::Click {
|
|
time_secs: c.time_secs,
|
|
x: (((c.x - src_origin.0) as f64) * scale).round() as i32,
|
|
y: (((c.y - src_origin.1) as f64) * scale).round() as i32,
|
|
})
|
|
.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: cfg.export.gif_dither,
|
|
webm_codec: cfg.export.webm_codec,
|
|
mp4_codec: cfg.export.mp4_codec,
|
|
scratch_dir: temp_dir(&state.app_dir),
|
|
crop: request.crop,
|
|
deleted_frame_indices: request.deleted_frame_indices,
|
|
trim_start_secs: trim_start,
|
|
trim_end_secs: trim_end,
|
|
clicks: transformed_clicks,
|
|
progress_tx: None,
|
|
};
|
|
|
|
let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 };
|
|
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.
|
|
std::thread::spawn(move || {
|
|
while let Ok(progress) = rx.recv() {
|
|
let _ = app_handle.emit(
|
|
"encode-progress",
|
|
encode::EncodeProgress {
|
|
pass: progress.pass,
|
|
total_passes,
|
|
percent: progress.percent,
|
|
},
|
|
);
|
|
}
|
|
});
|
|
|
|
encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?;
|
|
|
|
let size_bytes = std::fs::metadata(&out_path)
|
|
.map(|m| m.len())
|
|
.unwrap_or(0);
|
|
Ok(ExportResult {
|
|
output_path: out_path,
|
|
size_bytes,
|
|
})
|
|
}
|
|
|
|
pub fn run() {
|
|
tracing_subscriber::fmt::init();
|
|
|
|
let app_dir = exe_dir().expect("resolve exe directory");
|
|
|
|
let webview_dir = app_dir.join("temp").join("webview");
|
|
if let Err(e) = std::fs::create_dir_all(&webview_dir) {
|
|
tracing::warn!("creating webview data dir failed: {e}");
|
|
} else {
|
|
// SAFETY: must be called before any other code accesses environment;
|
|
// here it's the first thing after dir resolution, before Tauri reads.
|
|
unsafe {
|
|
std::env::set_var("WEBVIEW2_USER_DATA_FOLDER", &webview_dir);
|
|
}
|
|
}
|
|
|
|
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),
|
|
session: Mutex::new(None),
|
|
picker: Mutex::new(None),
|
|
};
|
|
|
|
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, cfg) = {
|
|
let st = app.state::<AppState>();
|
|
let cfg = st.config.lock().expect("config mutex").clone();
|
|
(cfg.updates.check_on_launch, cfg)
|
|
};
|
|
let _ = register_hotkeys(app.handle(), &cfg);
|
|
start_overlay_clickthrough_poll(app.handle().clone());
|
|
if check_on_launch {
|
|
let handle = app.handle().clone();
|
|
tauri::async_runtime::spawn(async move {
|
|
match updates::check_for_update().await {
|
|
Ok(Some(info)) => {
|
|
tracing::info!(version = info.version, "update available");
|
|
let _ = handle.emit("update-available", &info);
|
|
}
|
|
Ok(None) => tracing::debug!("no update available"),
|
|
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,
|
|
stop_capture,
|
|
export,
|
|
default_output_path,
|
|
extract_thumbnails,
|
|
render_preview,
|
|
reveal_in_explorer,
|
|
open_url,
|
|
show_overlay,
|
|
hide_overlay,
|
|
set_overlay_size,
|
|
set_overlay_to_window,
|
|
list_windows,
|
|
open_window_picker,
|
|
close_window_picker,
|
|
get_overlay_rect,
|
|
])
|
|
.run(tauri::generate_context!())
|
|
.expect("error while running ByteSize")
|
|
}
|