20 fixes: mutex poisoning recovery, clickthrough shutdown, audio cleanup, config corruption, GIF aspect ratio, ffmpeg crash detection, cancel export, discard confirm, thumbnail cache, keyboard nav, right-click tracking, multi-monitor overlay, click injection fix, update script robustness, effect cleanup, concat guard, dead code removal
This commit is contained in:
+18
-8
@@ -158,6 +158,24 @@ fn capture_thread(
|
|||||||
// Notify parent that init succeeded.
|
// Notify parent that init succeeded.
|
||||||
let _ = init_tx.send(Ok((sample_rate, channels)));
|
let _ = init_tx.send(Ok((sample_rate, channels)));
|
||||||
|
|
||||||
|
let result = capture_loop(&running, &capture_client, channels, bits_per_sample, is_float, &mut writer);
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let _ = client.Stop();
|
||||||
|
}
|
||||||
|
writer.flush().context("flushing audio writer")?;
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_loop(
|
||||||
|
running: &Arc<AtomicBool>,
|
||||||
|
capture_client: &IAudioCaptureClient,
|
||||||
|
channels: u16,
|
||||||
|
bits_per_sample: u16,
|
||||||
|
is_float: bool,
|
||||||
|
writer: &mut BufWriter<File>,
|
||||||
|
) -> Result<()> {
|
||||||
while running.load(Ordering::Relaxed) {
|
while running.load(Ordering::Relaxed) {
|
||||||
let mut packet_length = unsafe {
|
let mut packet_length = unsafe {
|
||||||
capture_client
|
capture_client
|
||||||
@@ -186,7 +204,6 @@ fn capture_thread(
|
|||||||
let samples = (num_frames_available as usize) * (channels as usize);
|
let samples = (num_frames_available as usize) * (channels as usize);
|
||||||
|
|
||||||
if is_silent {
|
if is_silent {
|
||||||
// Write f32 zeros for silent frames.
|
|
||||||
let zero_bytes = samples * 4;
|
let zero_bytes = samples * 4;
|
||||||
let zeros = vec![0u8; zero_bytes];
|
let zeros = vec![0u8; zero_bytes];
|
||||||
writer.write_all(&zeros).context("writing silent audio")?;
|
writer.write_all(&zeros).context("writing silent audio")?;
|
||||||
@@ -197,7 +214,6 @@ fn capture_thread(
|
|||||||
};
|
};
|
||||||
writer.write_all(slice).context("writing audio data")?;
|
writer.write_all(slice).context("writing audio data")?;
|
||||||
} else {
|
} else {
|
||||||
// Convert integer PCM to f32 little-endian.
|
|
||||||
match bits_per_sample {
|
match bits_per_sample {
|
||||||
16 => {
|
16 => {
|
||||||
let i16_slice = unsafe {
|
let i16_slice = unsafe {
|
||||||
@@ -241,11 +257,5 @@ fn capture_thread(
|
|||||||
|
|
||||||
thread::sleep(std::time::Duration::from_millis(1));
|
thread::sleep(std::time::Duration::from_millis(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe {
|
|
||||||
let _ = client.Stop();
|
|
||||||
}
|
|
||||||
|
|
||||||
writer.flush().context("flushing audio writer")?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use anyhow::{anyhow, bail, Context, Result};
|
use anyhow::{anyhow, bail, Context, Result};
|
||||||
@@ -27,6 +29,7 @@ pub struct CaptureSetup {
|
|||||||
pub height: u32,
|
pub height: u32,
|
||||||
pub fps: u32,
|
pub fps: u32,
|
||||||
pub crop: Option<CaptureRect>,
|
pub crop: Option<CaptureRect>,
|
||||||
|
pub crashed: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CaptureHandler {
|
pub struct CaptureHandler {
|
||||||
@@ -35,6 +38,7 @@ pub struct CaptureHandler {
|
|||||||
width: u32,
|
width: u32,
|
||||||
height: u32,
|
height: u32,
|
||||||
scratch: Vec<u8>,
|
scratch: Vec<u8>,
|
||||||
|
crashed: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GraphicsCaptureApiHandler for CaptureHandler {
|
impl GraphicsCaptureApiHandler for CaptureHandler {
|
||||||
@@ -96,6 +100,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
width: setup.width,
|
width: setup.width,
|
||||||
height: setup.height,
|
height: setup.height,
|
||||||
scratch: Vec::with_capacity(frame_size),
|
scratch: Vec::with_capacity(frame_size),
|
||||||
|
crashed: setup.crashed,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,7 +124,8 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
stdin.write_all(&bytes[..expected]).map_err(|e| {
|
stdin.write_all(&bytes[..expected]).map_err(|e| {
|
||||||
tracing::error!("ffmpeg stdin write failed: {e} — encoder may have crashed");
|
tracing::error!("ffmpeg stdin write failed: {e} - encoder may have crashed");
|
||||||
|
self.crashed.store(true, Ordering::Release);
|
||||||
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
|
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
|
||||||
})?;
|
})?;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -141,6 +147,7 @@ pub struct CaptureSession {
|
|||||||
pub width: u32,
|
pub width: u32,
|
||||||
pub height: u32,
|
pub height: u32,
|
||||||
pub crop: Option<CaptureRect>,
|
pub crop: Option<CaptureRect>,
|
||||||
|
pub crashed: Arc<AtomicBool>,
|
||||||
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
control: CaptureControl<CaptureHandler, anyhow::Error>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,6 +210,8 @@ pub fn start(
|
|||||||
|
|
||||||
let (out_w, out_h) = compute_output_dims(width, height, crop);
|
let (out_w, out_h) = compute_output_dims(width, height, crop);
|
||||||
|
|
||||||
|
let crashed = Arc::new(AtomicBool::new(false));
|
||||||
|
|
||||||
let setup = CaptureSetup {
|
let setup = CaptureSetup {
|
||||||
output_path: output_path.clone(),
|
output_path: output_path.clone(),
|
||||||
ffmpeg_path,
|
ffmpeg_path,
|
||||||
@@ -210,6 +219,7 @@ pub fn start(
|
|||||||
height,
|
height,
|
||||||
fps,
|
fps,
|
||||||
crop,
|
crop,
|
||||||
|
crashed: crashed.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let cursor_setting = if capture_cursor {
|
let cursor_setting = if capture_cursor {
|
||||||
@@ -238,6 +248,7 @@ pub fn start(
|
|||||||
width: out_w,
|
width: out_w,
|
||||||
height: out_h,
|
height: out_h,
|
||||||
crop,
|
crop,
|
||||||
|
crashed,
|
||||||
control,
|
control,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -264,6 +275,10 @@ fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CaptureSession {
|
impl CaptureSession {
|
||||||
|
pub fn has_crashed(&self) -> bool {
|
||||||
|
self.crashed.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn stop(self) -> Result<PathBuf> {
|
pub fn stop(self) -> Result<PathBuf> {
|
||||||
self.control
|
self.control
|
||||||
.stop()
|
.stop()
|
||||||
@@ -271,7 +286,7 @@ impl CaptureSession {
|
|||||||
let meta = std::fs::metadata(&self.output_path)
|
let meta = std::fs::metadata(&self.output_path)
|
||||||
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
|
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
|
||||||
if meta.len() == 0 {
|
if meta.len() == 0 {
|
||||||
bail!("capture output file is empty — ffmpeg may have crashed during recording");
|
bail!("capture output file is empty - ffmpeg may have crashed during recording");
|
||||||
}
|
}
|
||||||
Ok(self.output_path)
|
Ok(self.output_path)
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-14
@@ -5,11 +5,19 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize)]
|
||||||
|
pub enum MouseButton {
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
Middle,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Serialize)]
|
#[derive(Debug, Clone, Copy, Serialize)]
|
||||||
pub struct Click {
|
pub struct Click {
|
||||||
pub time_secs: f64,
|
pub time_secs: f64,
|
||||||
pub x: i32,
|
pub x: i32,
|
||||||
pub y: i32,
|
pub y: i32,
|
||||||
|
pub button: MouseButton,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ClickRecorder {
|
pub struct ClickRecorder {
|
||||||
@@ -30,26 +38,38 @@ pub fn start() -> ClickRecorder {
|
|||||||
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
|
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
|
||||||
|
|
||||||
const VK_LBUTTON: i32 = 0x01;
|
const VK_LBUTTON: i32 = 0x01;
|
||||||
|
const VK_RBUTTON: i32 = 0x02;
|
||||||
|
const VK_MBUTTON: i32 = 0x04;
|
||||||
|
|
||||||
|
let buttons = [
|
||||||
|
(VK_LBUTTON, MouseButton::Left),
|
||||||
|
(VK_RBUTTON, MouseButton::Right),
|
||||||
|
(VK_MBUTTON, MouseButton::Middle),
|
||||||
|
];
|
||||||
|
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let mut last_pressed = false;
|
let mut last_pressed = [false; 3];
|
||||||
|
|
||||||
while running_clone.load(Ordering::Relaxed) {
|
while running_clone.load(Ordering::Relaxed) {
|
||||||
let state = unsafe { GetAsyncKeyState(VK_LBUTTON) };
|
for (i, &(vk, button)) in buttons.iter().enumerate() {
|
||||||
let pressed = (state as u16 & 0x8000) != 0;
|
let state = unsafe { GetAsyncKeyState(vk) };
|
||||||
if pressed && !last_pressed {
|
let pressed = (state as u16 & 0x8000) != 0;
|
||||||
let mut pt = POINT::default();
|
if pressed && !last_pressed[i] {
|
||||||
if unsafe { GetCursorPos(&mut pt) }.is_ok() {
|
let mut pt = POINT::default();
|
||||||
let click = Click {
|
if unsafe { GetCursorPos(&mut pt) }.is_ok() {
|
||||||
time_secs: start.elapsed().as_secs_f64(),
|
let click = Click {
|
||||||
x: pt.x,
|
time_secs: start.elapsed().as_secs_f64(),
|
||||||
y: pt.y,
|
x: pt.x,
|
||||||
};
|
y: pt.y,
|
||||||
if let Ok(mut v) = clicks_clone.lock() {
|
button,
|
||||||
v.push(click);
|
};
|
||||||
|
if let Ok(mut v) = clicks_clone.lock() {
|
||||||
|
v.push(click);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
last_pressed[i] = pressed;
|
||||||
}
|
}
|
||||||
last_pressed = pressed;
|
|
||||||
thread::sleep(Duration::from_millis(5));
|
thread::sleep(Duration::from_millis(5));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+12
-1
@@ -136,7 +136,18 @@ impl Config {
|
|||||||
return Ok(cfg);
|
return Ok(cfg);
|
||||||
}
|
}
|
||||||
let raw = std::fs::read_to_string(path)?;
|
let raw = std::fs::read_to_string(path)?;
|
||||||
Ok(toml::from_str(&raw)?)
|
match toml::from_str::<Self>(&raw) {
|
||||||
|
Ok(cfg) => Ok(cfg),
|
||||||
|
Err(e) => {
|
||||||
|
// Config is corrupt - back it up and return defaults
|
||||||
|
tracing::warn!("config.toml is corrupt ({e}), backing up and using defaults");
|
||||||
|
let backup = path.with_extension("toml.bak");
|
||||||
|
let _ = std::fs::copy(path, &backup);
|
||||||
|
let cfg = Self::default();
|
||||||
|
cfg.save(path)?;
|
||||||
|
Ok(cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save(&self, path: &Path) -> Result<()> {
|
pub fn save(&self, path: &Path) -> Result<()> {
|
||||||
|
|||||||
+21
-8
@@ -43,6 +43,8 @@ pub struct TranscodeRequest {
|
|||||||
pub trim_start_secs: Option<f64>,
|
pub trim_start_secs: Option<f64>,
|
||||||
pub trim_end_secs: Option<f64>,
|
pub trim_end_secs: Option<f64>,
|
||||||
pub clicks: Vec<Click>,
|
pub clicks: Vec<Click>,
|
||||||
|
pub clip_width: u32,
|
||||||
|
pub clip_height: u32,
|
||||||
/// Optional channel to report encoding progress.
|
/// Optional channel to report encoding progress.
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub progress_tx: Option<Sender<EncodeProgress>>,
|
pub progress_tx: Option<Sender<EncodeProgress>>,
|
||||||
@@ -70,8 +72,13 @@ fn click_filters(req: &TranscodeRequest) -> Option<String> {
|
|||||||
let y = click.y - half;
|
let y = click.y - half;
|
||||||
let t1 = (click.time_secs - 0.05).max(0.0);
|
let t1 = (click.time_secs - 0.05).max(0.0);
|
||||||
let t2 = click.time_secs + 0.25;
|
let t2 = click.time_secs + 0.25;
|
||||||
|
let color = match click.button {
|
||||||
|
crate::clicks::MouseButton::Left => "yellow@0.6",
|
||||||
|
crate::clicks::MouseButton::Right => "blue@0.6",
|
||||||
|
crate::clicks::MouseButton::Middle => "green@0.6",
|
||||||
|
};
|
||||||
parts.push(format!(
|
parts.push(format!(
|
||||||
"drawbox=x={x}:y={y}:w={size}:h={size}:color=yellow@0.6:t=fill:enable='between(t,{t1:.3},{t2:.3})'"
|
"drawbox=x={x}:y={y}:w={size}:h={size}:color={color}:t=fill:enable='between(t,{t1:.3},{t2:.3})'"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if parts.is_empty() {
|
if parts.is_empty() {
|
||||||
@@ -334,7 +341,7 @@ fn cleanup_pass_logs(stem: &Path) {
|
|||||||
|
|
||||||
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
||||||
let palette_path = req.scratch_dir.join("palette.png");
|
let palette_path = req.scratch_dir.join("palette.png");
|
||||||
let scale_width = estimate_gif_scale_width(req);
|
let scale_width = estimate_gif_scale_width(req, req.clip_width, req.clip_height);
|
||||||
let crop_prefix = crop_filter(req.crop)
|
let crop_prefix = crop_filter(req.crop)
|
||||||
.map(|c| format!("{c},"))
|
.map(|c| format!("{c},"))
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
@@ -405,11 +412,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn estimate_gif_scale_width(req: &TranscodeRequest) -> u32 {
|
fn estimate_gif_scale_width(req: &TranscodeRequest, clip_width: u32, clip_height: u32) -> u32 {
|
||||||
let bytes_per_pixel_per_frame = 0.5_f64;
|
let bytes_per_pixel_per_frame = 0.5_f64;
|
||||||
let frames = (req.fps as f64 * req.duration_secs).max(1.0);
|
let frames = (req.fps as f64 * req.duration_secs).max(1.0);
|
||||||
let budget = req.target_bytes as f64 / (frames * bytes_per_pixel_per_frame);
|
let budget = req.target_bytes as f64 / (frames * bytes_per_pixel_per_frame);
|
||||||
let aspect = 16.0_f64 / 9.0;
|
let aspect = if clip_height > 0 { clip_width as f64 / clip_height as f64 } else { 16.0 / 9.0 };
|
||||||
let w = (budget * aspect).sqrt();
|
let w = (budget * aspect).sqrt();
|
||||||
let w = w.clamp(120.0, 1280.0).round() as u32;
|
let w = w.clamp(120.0, 1280.0).round() as u32;
|
||||||
(w / 2) * 2
|
(w / 2) * 2
|
||||||
@@ -536,6 +543,11 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct TempFileGuard(PathBuf);
|
||||||
|
impl Drop for TempFileGuard {
|
||||||
|
fn drop(&mut self) { let _ = std::fs::remove_file(&self.0); }
|
||||||
|
}
|
||||||
|
|
||||||
pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
|
pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Result<()> {
|
||||||
if segments.is_empty() {
|
if segments.is_empty() {
|
||||||
bail!("no segments to concatenate");
|
bail!("no segments to concatenate");
|
||||||
@@ -551,6 +563,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
|
|||||||
std::fs::create_dir_all(parent).context("creating output parent dir")?;
|
std::fs::create_dir_all(parent).context("creating output parent dir")?;
|
||||||
|
|
||||||
let list_path = parent.join("concat-list.txt");
|
let list_path = parent.join("concat-list.txt");
|
||||||
|
let _guard = TempFileGuard(list_path.clone());
|
||||||
let mut body = String::new();
|
let mut body = String::new();
|
||||||
for seg in segments {
|
for seg in segments {
|
||||||
let s = seg
|
let s = seg
|
||||||
@@ -570,9 +583,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
|
|||||||
.arg(&list_path)
|
.arg(&list_path)
|
||||||
.args(["-c", "copy"])
|
.args(["-c", "copy"])
|
||||||
.arg(output);
|
.arg(output);
|
||||||
let result = run(&mut cmd, "concat");
|
run(&mut cmd, "concat")
|
||||||
let _ = std::fs::remove_file(&list_path);
|
|
||||||
result
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
fn run(cmd: &mut Command, label: &str) -> Result<()> {
|
||||||
@@ -706,6 +717,8 @@ mod tests {
|
|||||||
trim_start_secs: None,
|
trim_start_secs: None,
|
||||||
trim_end_secs: None,
|
trim_end_secs: None,
|
||||||
clicks: vec![],
|
clicks: vec![],
|
||||||
|
clip_width: 1920,
|
||||||
|
clip_height: 1080,
|
||||||
progress_tx: None,
|
progress_tx: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -780,7 +793,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn click_filters_capped_at_max() {
|
fn click_filters_capped_at_max() {
|
||||||
let clicks: Vec<Click> = (0..100)
|
let clicks: Vec<Click> = (0..100)
|
||||||
.map(|i| Click { time_secs: i as f64, x: i, y: i })
|
.map(|i| Click { time_secs: i as f64, x: i, y: i, button: crate::clicks::MouseButton::Left })
|
||||||
.collect();
|
.collect();
|
||||||
let req = TranscodeRequest {
|
let req = TranscodeRequest {
|
||||||
clicks,
|
clicks,
|
||||||
|
|||||||
+97
-73
@@ -9,7 +9,8 @@ mod window_picker;
|
|||||||
mod windows_list;
|
mod windows_list;
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Mutex;
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -20,6 +21,10 @@ use std::str::FromStr;
|
|||||||
use crate::bootstrap::FfmpegStatus;
|
use crate::bootstrap::FfmpegStatus;
|
||||||
use crate::config::{Config, Format};
|
use crate::config::{Config, Format};
|
||||||
|
|
||||||
|
fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||||
|
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
pub struct CaptureRect {
|
pub struct CaptureRect {
|
||||||
pub x: i32,
|
pub x: i32,
|
||||||
@@ -37,6 +42,7 @@ pub struct AppState {
|
|||||||
pub last_clip: Mutex<Option<RecordedClip>>,
|
pub last_clip: Mutex<Option<RecordedClip>>,
|
||||||
pub session: Mutex<Option<SessionState>>,
|
pub session: Mutex<Option<SessionState>>,
|
||||||
pub picker: Mutex<Option<window_picker::PickerSession>>,
|
pub picker: Mutex<Option<window_picker::PickerSession>>,
|
||||||
|
pub overlay_poll_shutdown: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SessionState {
|
pub struct SessionState {
|
||||||
@@ -116,7 +122,7 @@ struct AppStatus {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn get_status(state: State<'_, AppState>) -> AppStatus {
|
fn get_status(state: State<'_, AppState>) -> AppStatus {
|
||||||
let cfg = state.config.lock().expect("config mutex");
|
let cfg = lock(&state.config);
|
||||||
AppStatus {
|
AppStatus {
|
||||||
ffmpeg: bootstrap::check(&state.app_dir),
|
ffmpeg: bootstrap::check(&state.app_dir),
|
||||||
needs_first_run: cfg.needs_first_run(),
|
needs_first_run: cfg.needs_first_run(),
|
||||||
@@ -125,7 +131,7 @@ fn get_status(state: State<'_, AppState>) -> AppStatus {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn get_config(state: State<'_, AppState>) -> Config {
|
fn get_config(state: State<'_, AppState>) -> Config {
|
||||||
state.config.lock().expect("config mutex").clone()
|
lock(&state.config).clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_shortcut(s: &str) -> Option<Shortcut> {
|
fn parse_shortcut(s: &str) -> Option<Shortcut> {
|
||||||
@@ -184,7 +190,7 @@ fn save_config(
|
|||||||
) -> Result<SaveConfigResult, String> {
|
) -> Result<SaveConfigResult, String> {
|
||||||
let path = config::config_path(&state.app_dir);
|
let path = config::config_path(&state.app_dir);
|
||||||
config.save(&path).map_err(|e| format!("{e:#}"))?;
|
config.save(&path).map_err(|e| format!("{e:#}"))?;
|
||||||
*state.config.lock().expect("config mutex") = config.clone();
|
*lock(&state.config) = config.clone();
|
||||||
let hotkey_result = register_hotkeys(&app, &config);
|
let hotkey_result = register_hotkeys(&app, &config);
|
||||||
Ok(SaveConfigResult { hotkey_result })
|
Ok(SaveConfigResult { hotkey_result })
|
||||||
}
|
}
|
||||||
@@ -324,12 +330,12 @@ fn start_capture(
|
|||||||
request: Option<StartCaptureRequest>,
|
request: Option<StartCaptureRequest>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
{
|
{
|
||||||
let slot = state.capture.lock().expect("capture mutex");
|
let slot = lock(&state.capture);
|
||||||
if slot.is_some() {
|
if slot.is_some() {
|
||||||
return Err("a capture is already running".to_string());
|
return Err("a capture is already running".to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let cfg = state.config.lock().expect("config mutex").clone();
|
let cfg = lock(&state.config).clone();
|
||||||
let temp = temp_dir(&state.app_dir);
|
let temp = temp_dir(&state.app_dir);
|
||||||
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?;
|
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?;
|
||||||
clear_temp_segments(&state.app_dir);
|
clear_temp_segments(&state.app_dir);
|
||||||
@@ -399,40 +405,34 @@ fn start_capture(
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
*state.session.lock().expect("session mutex") = Some(session_state);
|
*lock(&state.session) = Some(session_state);
|
||||||
*state.capture.lock().expect("capture mutex") = Some(session);
|
*lock(&state.capture) = Some(session);
|
||||||
*state.audio.lock().expect("audio mutex") = audio_session;
|
*lock(&state.audio) = audio_session;
|
||||||
*state.click_recorder.lock().expect("click mutex") = click_rec;
|
*lock(&state.click_recorder) = click_rec;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||||
let session = state
|
let session = lock(&state.capture)
|
||||||
.capture
|
|
||||||
.lock()
|
|
||||||
.expect("capture mutex")
|
|
||||||
.take()
|
.take()
|
||||||
.ok_or_else(|| "no capture in progress".to_string())?;
|
.ok_or_else(|| "no capture in progress".to_string())?;
|
||||||
|
if session.has_crashed() {
|
||||||
|
return Err("recording failed - ffmpeg encoder crashed".to_string());
|
||||||
|
}
|
||||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
let elapsed = session.started_at.elapsed().as_secs_f64();
|
||||||
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||||
|
|
||||||
let audio_path = state
|
let audio_path = lock(&state.audio)
|
||||||
.audio
|
|
||||||
.lock()
|
|
||||||
.expect("audio mutex")
|
|
||||||
.take()
|
.take()
|
||||||
.and_then(|a| a.stop().ok());
|
.and_then(|a| a.stop().ok());
|
||||||
|
|
||||||
let new_clicks: Vec<clicks::Click> = state
|
let new_clicks: Vec<clicks::Click> = lock(&state.click_recorder)
|
||||||
.click_recorder
|
|
||||||
.lock()
|
|
||||||
.expect("click mutex")
|
|
||||||
.take()
|
.take()
|
||||||
.map(|r| r.stop())
|
.map(|r| r.stop())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let mut ss = state.session.lock().expect("session mutex");
|
let mut ss = lock(&state.session);
|
||||||
let ss = ss
|
let ss = ss
|
||||||
.as_mut()
|
.as_mut()
|
||||||
.ok_or_else(|| "no session state".to_string())?;
|
.ok_or_else(|| "no session state".to_string())?;
|
||||||
@@ -455,13 +455,13 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
{
|
{
|
||||||
let slot = state.capture.lock().expect("capture mutex");
|
let slot = lock(&state.capture);
|
||||||
if slot.is_some() {
|
if slot.is_some() {
|
||||||
return Err("a capture is already running".to_string());
|
return Err("a capture is already running".to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let (capture_cursor, audio, crop, next_idx) = {
|
let (capture_cursor, audio, crop, next_idx) = {
|
||||||
let ss = state.session.lock().expect("session mutex");
|
let ss = lock(&state.session);
|
||||||
let ss = ss
|
let ss = ss
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.ok_or_else(|| "no session to resume".to_string())?;
|
.ok_or_else(|| "no session to resume".to_string())?;
|
||||||
@@ -473,7 +473,7 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let fps = state.config.lock().expect("config mutex").capture.default_fps;
|
let fps = lock(&state.config).capture.default_fps;
|
||||||
let output = segment_path(&state.app_dir, next_idx);
|
let output = segment_path(&state.app_dir, next_idx);
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
||||||
if !ffmpeg.is_file() {
|
if !ffmpeg.is_file() {
|
||||||
@@ -502,9 +502,9 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
*state.capture.lock().expect("capture mutex") = Some(session);
|
*lock(&state.capture) = Some(session);
|
||||||
*state.audio.lock().expect("audio mutex") = audio_session;
|
*lock(&state.audio) = audio_session;
|
||||||
*state.click_recorder.lock().expect("click mutex") = click_rec;
|
*lock(&state.click_recorder) = click_rec;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -512,32 +512,29 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
|||||||
fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||||
set_overlay_clickthrough(&app, false);
|
set_overlay_clickthrough(&app, false);
|
||||||
|
|
||||||
let mut ss = state
|
let mut ss = lock(&state.session)
|
||||||
.session
|
|
||||||
.lock()
|
|
||||||
.expect("session mutex")
|
|
||||||
.take()
|
.take()
|
||||||
.ok_or_else(|| "no session to stop".to_string())?;
|
.ok_or_else(|| "no session to stop".to_string())?;
|
||||||
|
|
||||||
let live = state.capture.lock().expect("capture mutex").take();
|
let live = lock(&state.capture).take();
|
||||||
if let Some(session) = live {
|
if let Some(session) = live {
|
||||||
|
if session.has_crashed() {
|
||||||
|
return Err("recording failed - ffmpeg encoder crashed".to_string());
|
||||||
|
}
|
||||||
let elapsed = session.started_at.elapsed().as_secs_f64();
|
let elapsed = session.started_at.elapsed().as_secs_f64();
|
||||||
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
let path = session.stop().map_err(|e| format!("{e:#}"))?;
|
||||||
ss.segments.push(path);
|
ss.segments.push(path);
|
||||||
ss.total_recorded_secs += elapsed;
|
ss.total_recorded_secs += elapsed;
|
||||||
}
|
}
|
||||||
|
|
||||||
let live_audio = state.audio.lock().expect("audio mutex").take();
|
let live_audio = lock(&state.audio).take();
|
||||||
if let Some(a) = live_audio {
|
if let Some(a) = live_audio {
|
||||||
if let Ok(p) = a.stop() {
|
if let Ok(p) = a.stop() {
|
||||||
ss.audio_segments.push(p);
|
ss.audio_segments.push(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let live_clicks = state
|
let live_clicks = lock(&state.click_recorder)
|
||||||
.click_recorder
|
|
||||||
.lock()
|
|
||||||
.expect("click mutex")
|
|
||||||
.take()
|
.take()
|
||||||
.map(|r| r.stop())
|
.map(|r| r.stop())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
@@ -623,7 +620,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
|
|||||||
crop: ss.crop,
|
crop: ss.crop,
|
||||||
clicks: ss.clicks.clone(),
|
clicks: ss.clicks.clone(),
|
||||||
};
|
};
|
||||||
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
|
*lock(&state.last_clip) = Some(clip.clone());
|
||||||
Ok(clip)
|
Ok(clip)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -647,7 +644,7 @@ pub struct ExportRequest {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
|
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
|
||||||
let cfg = state.config.lock().expect("config mutex").clone();
|
let cfg = lock(&state.config).clone();
|
||||||
let dir = output_dir(&state.app_dir, &cfg);
|
let dir = output_dir(&state.app_dir, &cfg);
|
||||||
dir.join(format!(
|
dir.join(format!(
|
||||||
"bytesize-{}.{}",
|
"bytesize-{}.{}",
|
||||||
@@ -670,10 +667,7 @@ fn render_preview(
|
|||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
request: PreviewRequest,
|
request: PreviewRequest,
|
||||||
) -> Result<PathBuf, String> {
|
) -> Result<PathBuf, String> {
|
||||||
let clip = state
|
let clip = lock(&state.last_clip)
|
||||||
.last_clip
|
|
||||||
.lock()
|
|
||||||
.expect("clip mutex")
|
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
||||||
@@ -709,10 +703,7 @@ fn extract_thumbnails(
|
|||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
fps: u32,
|
fps: u32,
|
||||||
) -> Result<Vec<PathBuf>, String> {
|
) -> Result<Vec<PathBuf>, String> {
|
||||||
let clip = state
|
let clip = lock(&state.last_clip)
|
||||||
.last_clip
|
|
||||||
.lock()
|
|
||||||
.expect("clip mutex")
|
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
||||||
@@ -733,11 +724,8 @@ pub struct ExportResult {
|
|||||||
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
||||||
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.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) {
|
fn start_overlay_clickthrough_poll(app: AppHandle, shutdown: Arc<AtomicBool>) {
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use windows::Win32::Foundation::{HWND, POINT, RECT};
|
use windows::Win32::Foundation::{HWND, POINT, RECT};
|
||||||
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
||||||
@@ -746,7 +734,7 @@ fn start_overlay_clickthrough_poll(app: AppHandle) {
|
|||||||
|
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
let mut last_inner: Option<bool> = None;
|
let mut last_inner: Option<bool> = None;
|
||||||
loop {
|
while !shutdown.load(Ordering::Relaxed) {
|
||||||
std::thread::sleep(Duration::from_millis(30));
|
std::thread::sleep(Duration::from_millis(30));
|
||||||
|
|
||||||
let overlay = match app.get_webview_window("overlay") {
|
let overlay = match app.get_webview_window("overlay") {
|
||||||
@@ -762,7 +750,7 @@ fn start_overlay_clickthrough_poll(app: AppHandle) {
|
|||||||
// start_capture already sets ignore_cursor_events(true). Skip polling
|
// start_capture already sets ignore_cursor_events(true). Skip polling
|
||||||
// so we don't fight it.
|
// so we don't fight it.
|
||||||
let state = app.state::<AppState>();
|
let state = app.state::<AppState>();
|
||||||
let is_recording = state.capture.lock().expect("capture mutex").is_some();
|
let is_recording = lock(&state.capture).is_some();
|
||||||
if is_recording {
|
if is_recording {
|
||||||
last_inner = Some(true);
|
last_inner = Some(true);
|
||||||
continue;
|
continue;
|
||||||
@@ -843,7 +831,39 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
|||||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||||
win.show().map_err(|e| e.to_string())?;
|
win.show().map_err(|e| e.to_string())?;
|
||||||
let _ = mark_overlay_excluded_from_capture(&win);
|
let _ = mark_overlay_excluded_from_capture(&win);
|
||||||
let _ = apply_overlay_region(&win);
|
|
||||||
|
// If the overlay is off-screen (monitor disconnected), center on primary
|
||||||
|
use windows::Win32::Foundation::{HWND, POINT, RECT};
|
||||||
|
use windows::Win32::Graphics::Gdi::{
|
||||||
|
GetMonitorInfoW, MonitorFromPoint, MONITOR_DEFAULTTOPRIMARY, MONITOR_DEFAULTTONULL, MONITORINFO,
|
||||||
|
};
|
||||||
|
use windows::Win32::UI::WindowsAndMessaging::{GetWindowRect, SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER};
|
||||||
|
if let Ok(raw) = win.hwnd() {
|
||||||
|
let hwnd = HWND(raw.0 as *mut _);
|
||||||
|
let mut rect = RECT::default();
|
||||||
|
if unsafe { GetWindowRect(hwnd, &mut rect) }.is_ok() {
|
||||||
|
let center = POINT {
|
||||||
|
x: (rect.left + rect.right) / 2,
|
||||||
|
y: (rect.top + rect.bottom) / 2,
|
||||||
|
};
|
||||||
|
let hmon = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) };
|
||||||
|
if hmon.0.is_null() {
|
||||||
|
let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
|
||||||
|
let mut mi = MONITORINFO {
|
||||||
|
cbSize: std::mem::size_of::<MONITORINFO>() as u32,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
if unsafe { GetMonitorInfoW(primary, &mut mi) }.as_bool() {
|
||||||
|
let work = mi.rcWork;
|
||||||
|
let w = rect.right - rect.left;
|
||||||
|
let h = rect.bottom - rect.top;
|
||||||
|
let cx = (work.left + work.right) / 2 - w / 2;
|
||||||
|
let cy = (work.top + work.bottom) / 2 - h / 2;
|
||||||
|
let _ = unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
win.set_focus().map_err(|e| e.to_string())
|
win.set_focus().map_err(|e| e.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -868,7 +888,6 @@ fn set_overlay_size(app: AppHandle, width: u32, height: u32) -> Result<(), Strin
|
|||||||
height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
||||||
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
|
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let _ = apply_overlay_region(&win);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -937,7 +956,7 @@ fn open_window_picker(
|
|||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut slot = state.picker.lock().expect("picker mutex");
|
let mut slot = lock(&state.picker);
|
||||||
if let Some(existing) = slot.take() {
|
if let Some(existing) = slot.take() {
|
||||||
existing.stop();
|
existing.stop();
|
||||||
}
|
}
|
||||||
@@ -951,7 +970,7 @@ fn close_window_picker(
|
|||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
if let Some(session) = state.picker.lock().expect("picker mutex").take() {
|
if let Some(session) = lock(&state.picker).take() {
|
||||||
session.stop();
|
session.stop();
|
||||||
}
|
}
|
||||||
if let Some(picker) = app.get_webview_window("picker") {
|
if let Some(picker) = app.get_webview_window("picker") {
|
||||||
@@ -1078,8 +1097,6 @@ fn set_overlay_to_window(
|
|||||||
}
|
}
|
||||||
.map_err(|e| format!("SetWindowPos: {e}"))?;
|
.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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1170,9 +1187,12 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn open_url(url: String) -> Result<(), String> {
|
fn open_url(url: String) -> Result<(), String> {
|
||||||
use std::process::Command;
|
if !url.starts_with("http://") && !url.starts_with("https://") {
|
||||||
Command::new("cmd")
|
return Err("only http/https URLs are supported".to_string());
|
||||||
.args(["/C", "start", "", &url])
|
}
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
std::process::Command::new("cmd")
|
||||||
|
.raw_arg(format!("/C start \"\" \"{url}\""))
|
||||||
.spawn()
|
.spawn()
|
||||||
.map_err(|e| format!("opening url: {e}"))?;
|
.map_err(|e| format!("opening url: {e}"))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -1180,11 +1200,8 @@ fn open_url(url: String) -> Result<(), String> {
|
|||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
||||||
let cfg = state.config.lock().expect("config mutex").clone();
|
let cfg = lock(&state.config).clone();
|
||||||
let clip = state
|
let clip = lock(&state.last_clip)
|
||||||
.last_clip
|
|
||||||
.lock()
|
|
||||||
.expect("clip mutex")
|
|
||||||
.clone()
|
.clone()
|
||||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||||
|
|
||||||
@@ -1238,6 +1255,7 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
|
|||||||
time_secs: c.time_secs,
|
time_secs: c.time_secs,
|
||||||
x: (((c.x - src_origin.0) as f64) * scale).round() as i32,
|
x: (((c.x - src_origin.0) as f64) * scale).round() as i32,
|
||||||
y: (((c.y - src_origin.1) as f64) * scale).round() as i32,
|
y: (((c.y - src_origin.1) as f64) * scale).round() as i32,
|
||||||
|
button: c.button,
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@@ -1258,6 +1276,8 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
|
|||||||
trim_start_secs: trim_start,
|
trim_start_secs: trim_start,
|
||||||
trim_end_secs: trim_end,
|
trim_end_secs: trim_end,
|
||||||
clicks: transformed_clicks,
|
clicks: transformed_clicks,
|
||||||
|
clip_width: clip.width,
|
||||||
|
clip_height: clip.height,
|
||||||
progress_tx: None,
|
progress_tx: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1322,6 +1342,7 @@ pub fn run() {
|
|||||||
last_clip: Mutex::new(None),
|
last_clip: Mutex::new(None),
|
||||||
session: Mutex::new(None),
|
session: Mutex::new(None),
|
||||||
picker: Mutex::new(None),
|
picker: Mutex::new(None),
|
||||||
|
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
|
||||||
};
|
};
|
||||||
|
|
||||||
tauri::Builder::default()
|
tauri::Builder::default()
|
||||||
@@ -1334,8 +1355,8 @@ pub fn run() {
|
|||||||
}
|
}
|
||||||
let cfg = {
|
let cfg = {
|
||||||
let st = app.state::<AppState>();
|
let st = app.state::<AppState>();
|
||||||
let guard = st.config.lock().expect("config mutex");
|
let cfg = lock(&st.config).clone();
|
||||||
guard.clone()
|
cfg
|
||||||
};
|
};
|
||||||
let kind = if cfg
|
let kind = if cfg
|
||||||
.hotkeys
|
.hotkeys
|
||||||
@@ -1377,11 +1398,14 @@ pub fn run() {
|
|||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
let (check_on_launch, cfg) = {
|
let (check_on_launch, cfg) = {
|
||||||
let st = app.state::<AppState>();
|
let st = app.state::<AppState>();
|
||||||
let cfg = st.config.lock().expect("config mutex").clone();
|
let cfg = lock(&st.config).clone();
|
||||||
(cfg.updates.check_on_launch, cfg)
|
(cfg.updates.check_on_launch, cfg)
|
||||||
};
|
};
|
||||||
let _ = register_hotkeys(app.handle(), &cfg);
|
let _ = register_hotkeys(app.handle(), &cfg);
|
||||||
start_overlay_clickthrough_poll(app.handle().clone());
|
{
|
||||||
|
let st = app.state::<AppState>();
|
||||||
|
start_overlay_clickthrough_poll(app.handle().clone(), st.overlay_poll_shutdown.clone());
|
||||||
|
}
|
||||||
if check_on_launch {
|
if check_on_launch {
|
||||||
let handle = app.handle().clone();
|
let handle = app.handle().clone();
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
|
|||||||
@@ -106,8 +106,20 @@ pub fn write_apply_script(app_dir: &Path) -> Result<PathBuf> {
|
|||||||
let body = format!(
|
let body = format!(
|
||||||
"@echo off\r\n\
|
"@echo off\r\n\
|
||||||
timeout /t 1 /nobreak >nul\r\n\
|
timeout /t 1 /nobreak >nul\r\n\
|
||||||
|
if not exist \"%~dp0ByteSize.new.exe\" (\r\n\
|
||||||
|
echo Update file not found\r\n\
|
||||||
|
pause\r\n\
|
||||||
|
del \"%~f0\"\r\n\
|
||||||
|
exit /b 1\r\n\
|
||||||
|
)\r\n\
|
||||||
del \"%~dp0{exe}\"\r\n\
|
del \"%~dp0{exe}\"\r\n\
|
||||||
move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\
|
move /Y \"%~dp0ByteSize.new.exe\" \"%~dp0{exe}\" >nul\r\n\
|
||||||
|
if errorlevel 1 (\r\n\
|
||||||
|
echo Failed to replace executable\r\n\
|
||||||
|
pause\r\n\
|
||||||
|
del \"%~f0\"\r\n\
|
||||||
|
exit /b 1\r\n\
|
||||||
|
)\r\n\
|
||||||
start \"\" \"%~dp0{exe}\"\r\n\
|
start \"\" \"%~dp0{exe}\"\r\n\
|
||||||
del \"%~f0\"\r\n",
|
del \"%~f0\"\r\n",
|
||||||
exe = exe_name
|
exe = exe_name
|
||||||
|
|||||||
+74
-5
@@ -48,6 +48,8 @@
|
|||||||
let audioWarning: string | null = $state(null)
|
let audioWarning: string | null = $state(null)
|
||||||
let useFrame: boolean = $state(false)
|
let useFrame: boolean = $state(false)
|
||||||
let previewTimer: number | null = null
|
let previewTimer: number | null = null
|
||||||
|
let thumbCache: Map<string, string[]> = $state(new Map())
|
||||||
|
let showDiscardConfirm: boolean = $state(false)
|
||||||
|
|
||||||
const PRESETS: [number, number, string][] = [
|
const PRESETS: [number, number, string][] = [
|
||||||
[1280, 720, "720p"],
|
[1280, 720, "720p"],
|
||||||
@@ -182,9 +184,14 @@
|
|||||||
|
|
||||||
async function loadThumbnails() {
|
async function loadThumbnails() {
|
||||||
if (format !== "gif") { thumbnails = []; return }
|
if (format !== "gif") { thumbnails = []; return }
|
||||||
|
const cacheKey = `${format}-${fps}`
|
||||||
|
const cached = thumbCache.get(cacheKey)
|
||||||
|
if (cached) { thumbnails = cached; deletedFrames = new Set(); return }
|
||||||
loadingThumbs = true
|
loadingThumbs = true
|
||||||
try {
|
try {
|
||||||
thumbnails = await api.extractThumbnails(fps)
|
const thumbs = await api.extractThumbnails(fps)
|
||||||
|
thumbCache.set(cacheKey, thumbs)
|
||||||
|
thumbnails = thumbs
|
||||||
deletedFrames = new Set()
|
deletedFrames = new Set()
|
||||||
} catch (e) { errMsg = String(e) }
|
} catch (e) { errMsg = String(e) }
|
||||||
finally { loadingThumbs = false }
|
finally { loadingThumbs = false }
|
||||||
@@ -220,10 +227,30 @@
|
|||||||
function startOver() {
|
function startOver() {
|
||||||
clip = null; exportResult = null; errMsg = null; encodeProgress = null
|
clip = null; exportResult = null; errMsg = null; encodeProgress = null
|
||||||
thumbnails = []; deletedFrames = new Set()
|
thumbnails = []; deletedFrames = new Set()
|
||||||
|
thumbCache = new Map()
|
||||||
if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null }
|
if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null }
|
||||||
elapsed = 0; phase = "idle"
|
elapsed = 0; phase = "idle"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function cancelExport() {
|
||||||
|
try { await api.cancelExport() } catch {}
|
||||||
|
phase = "editing"
|
||||||
|
encodeProgress = null
|
||||||
|
}
|
||||||
|
|
||||||
|
function confirmDiscard() {
|
||||||
|
showDiscardConfirm = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelDiscard() {
|
||||||
|
showDiscardConfirm = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function doDiscard() {
|
||||||
|
showDiscardConfirm = false
|
||||||
|
startOver()
|
||||||
|
}
|
||||||
|
|
||||||
function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) }
|
function tick() { elapsedTimer = window.setInterval(() => { elapsed += 0.1 }, 100) }
|
||||||
function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } }
|
function clearTick() { if (elapsedTimer !== null) { clearInterval(elapsedTimer); elapsedTimer = null } }
|
||||||
function minMB(s: number): number { return Math.max(0.1, Math.max(50_000, s * 50_000) / 1_048_576) }
|
function minMB(s: number): number { return Math.max(0.1, Math.max(50_000, s * 50_000) / 1_048_576) }
|
||||||
@@ -283,10 +310,9 @@
|
|||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (phase === "editing" && format) {
|
if (phase === "editing" && format) {
|
||||||
if (previewTimer !== null) clearTimeout(previewTimer)
|
const timer = window.setTimeout(() => { void refreshPreview() }, 300)
|
||||||
previewTimer = window.setTimeout(() => { previewTimer = null; void refreshPreview() }, 300)
|
return () => { clearTimeout(timer) }
|
||||||
}
|
}
|
||||||
return () => { if (previewTimer !== null) { clearTimeout(previewTimer); previewTimer = null } }
|
|
||||||
})
|
})
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
@@ -474,6 +500,12 @@
|
|||||||
onpointerdown={(e) => startDrag('start', e)}
|
onpointerdown={(e) => startDrag('start', e)}
|
||||||
onpointermove={onDrag}
|
onpointermove={onDrag}
|
||||||
onpointerup={endDrag}
|
onpointerup={endDrag}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (!clip) return
|
||||||
|
const step = e.shiftKey ? 0.5 : 0.05
|
||||||
|
if (e.key === 'ArrowLeft') { trimStart = Math.max(0, trimStart - step); e.preventDefault() }
|
||||||
|
else if (e.key === 'ArrowRight') { trimStart = Math.min(trimEnd - 0.1, trimStart + step); e.preventDefault() }
|
||||||
|
}}
|
||||||
></div>
|
></div>
|
||||||
<div
|
<div
|
||||||
class="trim-handle trim-end"
|
class="trim-handle trim-end"
|
||||||
@@ -487,6 +519,12 @@
|
|||||||
onpointerdown={(e) => startDrag('end', e)}
|
onpointerdown={(e) => startDrag('end', e)}
|
||||||
onpointermove={onDrag}
|
onpointermove={onDrag}
|
||||||
onpointerup={endDrag}
|
onpointerup={endDrag}
|
||||||
|
onkeydown={(e) => {
|
||||||
|
if (!clip) return
|
||||||
|
const step = e.shiftKey ? 0.5 : 0.05
|
||||||
|
if (e.key === 'ArrowLeft') { trimEnd = Math.max(trimStart + 0.1, trimEnd - step); e.preventDefault() }
|
||||||
|
else if (e.key === 'ArrowRight') { trimEnd = Math.min(clip.duration_secs, trimEnd + step); e.preventDefault() }
|
||||||
|
}}
|
||||||
></div>
|
></div>
|
||||||
</div>
|
</div>
|
||||||
<input type="range" min="0" max={clip.duration_secs} step="0.05" value={trimStart}
|
<input type="range" min="0" max={clip.duration_secs} step="0.05" value={trimStart}
|
||||||
@@ -608,7 +646,7 @@
|
|||||||
<!-- Actions -->
|
<!-- Actions -->
|
||||||
<div class="edit-actions">
|
<div class="edit-actions">
|
||||||
<button class="btn-primary" onclick={doExport}>Export</button>
|
<button class="btn-primary" onclick={doExport}>Export</button>
|
||||||
<button class="btn-ghost" onclick={startOver}>Discard</button>
|
<button class="btn-ghost" onclick={confirmDiscard}>Discard</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -629,6 +667,7 @@
|
|||||||
<div class="enc-track"><div class="enc-fill" style="width:0%"></div></div>
|
<div class="enc-track"><div class="enc-fill" style="width:0%"></div></div>
|
||||||
{/if}
|
{/if}
|
||||||
<p class="enc-hint">ffmpeg is encoding your clip</p>
|
<p class="enc-hint">ffmpeg is encoding your clip</p>
|
||||||
|
<button class="btn-ghost" onclick={cancelExport}>Cancel</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- DONE -->
|
<!-- DONE -->
|
||||||
@@ -650,6 +689,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
|
{#if showDiscardConfirm}
|
||||||
|
<div class="confirm-overlay">
|
||||||
|
<div class="confirm-card">
|
||||||
|
<p>Discard this recording?</p>
|
||||||
|
<div class="confirm-actions">
|
||||||
|
<button class="btn-ghost" onclick={cancelDiscard}>Keep it</button>
|
||||||
|
<button class="btn-stop" onclick={doDiscard}>Discard</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
<!-- Error toast -->
|
<!-- Error toast -->
|
||||||
@@ -1373,4 +1424,22 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.mono { font-family: var(--mono); }
|
.mono { font-family: var(--mono); }
|
||||||
|
|
||||||
|
/* ---- Confirm overlay ---- */
|
||||||
|
.confirm-overlay {
|
||||||
|
position: fixed; inset: 0;
|
||||||
|
background: rgba(0,0,0,0.5);
|
||||||
|
display: grid; place-items: center;
|
||||||
|
z-index: 50;
|
||||||
|
}
|
||||||
|
.confirm-card {
|
||||||
|
background: var(--bg-2);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--r-md);
|
||||||
|
padding: 24px;
|
||||||
|
min-width: 280px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.confirm-card p { margin: 0 0 16px; font-size: 14px; color: var(--text); }
|
||||||
|
.confirm-actions { display: flex; gap: 10px; justify-content: center; }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
+24
-29
@@ -22,39 +22,34 @@
|
|||||||
height = Math.round(sz.height / sf)
|
height = Math.round(sz.height / sf)
|
||||||
}
|
}
|
||||||
updateSize()
|
updateSize()
|
||||||
const rp = win.onResized(updateSize)
|
let cleanup: (() => void)[] = []
|
||||||
|
|
||||||
let rp2: Promise<() => void> | null = null
|
win.onResized(updateSize).then(fn => cleanup.push(fn))
|
||||||
void (async () => {
|
|
||||||
rp2 = listen<{ phase: "idle"|"recording"|"paused"; fps: number }>(
|
listen<{ phase: "idle"|"recording"|"paused"; fps: number }>(
|
||||||
"recording-state", (e) => {
|
"recording-state", (e) => {
|
||||||
fps = e.payload.fps
|
fps = e.payload.fps
|
||||||
if (e.payload.phase === "recording") {
|
if (e.payload.phase === "recording") {
|
||||||
if (phase !== "recording") elapsed = 0
|
if (phase !== "recording") elapsed = 0
|
||||||
startTimer()
|
startTimer()
|
||||||
} else {
|
} else {
|
||||||
stopTimer()
|
stopTimer()
|
||||||
}
|
|
||||||
if (e.payload.phase === "idle") { elapsed = 0; phase = "idle" }
|
|
||||||
phase = e.payload.phase
|
|
||||||
}
|
}
|
||||||
)
|
if (e.payload.phase === "idle") { elapsed = 0; phase = "idle" }
|
||||||
})()
|
phase = e.payload.phase
|
||||||
|
}
|
||||||
|
).then(fn => cleanup.push(fn))
|
||||||
|
|
||||||
let rp3: Promise<() => void> | null = null
|
listen<Rect>("picker-pick", async (e: { payload: Rect }) => {
|
||||||
void (async () => {
|
try { await invoke("set_overlay_to_window", e.payload) } catch {}
|
||||||
rp3 = listen<Rect>("picker-pick", async (e: { payload: Rect }) => {
|
try { await invoke("close_window_picker") } catch {}
|
||||||
try { await invoke("set_overlay_to_window", e.payload) } catch {}
|
}).then(fn => cleanup.push(fn))
|
||||||
try { await invoke("close_window_picker") } catch {}
|
|
||||||
})
|
|
||||||
})()
|
|
||||||
void (async () => {
|
|
||||||
await listen("picker-cancel", async () => {
|
|
||||||
try { await invoke("close_window_picker") } catch {}
|
|
||||||
})
|
|
||||||
})()
|
|
||||||
|
|
||||||
return () => { stopTimer(); void rp.then(fn => fn()); void rp2?.then(fn => fn()); void rp3?.then(fn => fn()) }
|
listen("picker-cancel", async () => {
|
||||||
|
try { await invoke("close_window_picker") } catch {}
|
||||||
|
}).then(fn => cleanup.push(fn))
|
||||||
|
|
||||||
|
return () => { stopTimer(); cleanup.forEach(fn => fn()) }
|
||||||
})
|
})
|
||||||
|
|
||||||
function startTimer() {
|
function startTimer() {
|
||||||
|
|||||||
@@ -184,6 +184,7 @@ export const api = {
|
|||||||
listen<EncodeProgress>("encode-progress", (e) => handler(e.payload)),
|
listen<EncodeProgress>("encode-progress", (e) => handler(e.payload)),
|
||||||
onAudioFailed: (handler: (msg: string) => void): Promise<UnlistenFn> =>
|
onAudioFailed: (handler: (msg: string) => void): Promise<UnlistenFn> =>
|
||||||
listen<string>("audio-failed", (e) => handler(e.payload)),
|
listen<string>("audio-failed", (e) => handler(e.payload)),
|
||||||
|
cancelExport: () => invoke<void>("cancel_export"),
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatBytes(n: number): string {
|
export function formatBytes(n: number): string {
|
||||||
|
|||||||
Reference in New Issue
Block a user