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:
2026-05-27 19:14:33 +03:00
parent f0775b8ff0
commit e4141f8be8
10 changed files with 310 additions and 140 deletions
+18 -8
View File
@@ -158,6 +158,24 @@ fn capture_thread(
// Notify parent that init succeeded.
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) {
let mut packet_length = unsafe {
capture_client
@@ -186,7 +204,6 @@ fn capture_thread(
let samples = (num_frames_available as usize) * (channels as usize);
if is_silent {
// Write f32 zeros for silent frames.
let zero_bytes = samples * 4;
let zeros = vec![0u8; zero_bytes];
writer.write_all(&zeros).context("writing silent audio")?;
@@ -197,7 +214,6 @@ fn capture_thread(
};
writer.write_all(slice).context("writing audio data")?;
} else {
// Convert integer PCM to f32 little-endian.
match bits_per_sample {
16 => {
let i16_slice = unsafe {
@@ -241,11 +257,5 @@ fn capture_thread(
thread::sleep(std::time::Duration::from_millis(1));
}
unsafe {
let _ = client.Stop();
}
writer.flush().context("flushing audio writer")?;
Ok(())
}
+17 -2
View File
@@ -1,6 +1,8 @@
use std::io::Write;
use std::path::PathBuf;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use anyhow::{anyhow, bail, Context, Result};
@@ -27,6 +29,7 @@ pub struct CaptureSetup {
pub height: u32,
pub fps: u32,
pub crop: Option<CaptureRect>,
pub crashed: Arc<AtomicBool>,
}
pub struct CaptureHandler {
@@ -35,6 +38,7 @@ pub struct CaptureHandler {
width: u32,
height: u32,
scratch: Vec<u8>,
crashed: Arc<AtomicBool>,
}
impl GraphicsCaptureApiHandler for CaptureHandler {
@@ -96,6 +100,7 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
width: setup.width,
height: setup.height,
scratch: Vec::with_capacity(frame_size),
crashed: setup.crashed,
})
}
@@ -119,7 +124,8 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
return Ok(());
}
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}")
})?;
Ok(())
@@ -141,6 +147,7 @@ pub struct CaptureSession {
pub width: u32,
pub height: u32,
pub crop: Option<CaptureRect>,
pub crashed: Arc<AtomicBool>,
control: CaptureControl<CaptureHandler, anyhow::Error>,
}
@@ -203,6 +210,8 @@ pub fn start(
let (out_w, out_h) = compute_output_dims(width, height, crop);
let crashed = Arc::new(AtomicBool::new(false));
let setup = CaptureSetup {
output_path: output_path.clone(),
ffmpeg_path,
@@ -210,6 +219,7 @@ pub fn start(
height,
fps,
crop,
crashed: crashed.clone(),
};
let cursor_setting = if capture_cursor {
@@ -238,6 +248,7 @@ pub fn start(
width: out_w,
height: out_h,
crop,
crashed,
control,
})
}
@@ -264,6 +275,10 @@ fn compute_output_dims(monitor_w: u32, monitor_h: u32, crop: Option<CaptureRect>
}
impl CaptureSession {
pub fn has_crashed(&self) -> bool {
self.crashed.load(Ordering::Acquire)
}
pub fn stop(self) -> Result<PathBuf> {
self.control
.stop()
@@ -271,7 +286,7 @@ impl CaptureSession {
let meta = std::fs::metadata(&self.output_path)
.with_context(|| format!("checking output file {}", self.output_path.display()))?;
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)
}
+34 -14
View File
@@ -5,11 +5,19 @@ use std::time::{Duration, Instant};
use serde::Serialize;
#[derive(Debug, Clone, Copy, Serialize)]
pub enum MouseButton {
Left,
Right,
Middle,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub struct Click {
pub time_secs: f64,
pub x: i32,
pub y: i32,
pub button: MouseButton,
}
pub struct ClickRecorder {
@@ -30,26 +38,38 @@ pub fn start() -> ClickRecorder {
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
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 mut last_pressed = false;
let mut last_pressed = [false; 3];
while running_clone.load(Ordering::Relaxed) {
let state = unsafe { GetAsyncKeyState(VK_LBUTTON) };
let pressed = (state as u16 & 0x8000) != 0;
if pressed && !last_pressed {
let mut pt = POINT::default();
if unsafe { GetCursorPos(&mut pt) }.is_ok() {
let click = Click {
time_secs: start.elapsed().as_secs_f64(),
x: pt.x,
y: pt.y,
};
if let Ok(mut v) = clicks_clone.lock() {
v.push(click);
for (i, &(vk, button)) in buttons.iter().enumerate() {
let state = unsafe { GetAsyncKeyState(vk) };
let pressed = (state as u16 & 0x8000) != 0;
if pressed && !last_pressed[i] {
let mut pt = POINT::default();
if unsafe { GetCursorPos(&mut pt) }.is_ok() {
let click = Click {
time_secs: start.elapsed().as_secs_f64(),
x: pt.x,
y: pt.y,
button,
};
if let Ok(mut v) = clicks_clone.lock() {
v.push(click);
}
}
}
last_pressed[i] = pressed;
}
last_pressed = pressed;
thread::sleep(Duration::from_millis(5));
}
});
+12 -1
View File
@@ -136,7 +136,18 @@ impl Config {
return Ok(cfg);
}
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<()> {
+21 -8
View File
@@ -43,6 +43,8 @@ pub struct TranscodeRequest {
pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
pub clip_width: u32,
pub clip_height: u32,
/// Optional channel to report encoding progress.
#[doc(hidden)]
pub progress_tx: Option<Sender<EncodeProgress>>,
@@ -70,8 +72,13 @@ fn click_filters(req: &TranscodeRequest) -> Option<String> {
let y = click.y - half;
let t1 = (click.time_secs - 0.05).max(0.0);
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!(
"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() {
@@ -334,7 +341,7 @@ fn cleanup_pass_logs(stem: &Path) {
fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
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)
.map(|c| format!("{c},"))
.unwrap_or_default();
@@ -405,11 +412,11 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
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 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 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 = w.clamp(120.0, 1280.0).round() as u32;
(w / 2) * 2
@@ -536,6 +543,11 @@ pub fn concat_pcm(segments: &[PathBuf], output: &Path) -> Result<()> {
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<()> {
if segments.is_empty() {
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")?;
let list_path = parent.join("concat-list.txt");
let _guard = TempFileGuard(list_path.clone());
let mut body = String::new();
for seg in segments {
let s = seg
@@ -570,9 +583,7 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
.arg(&list_path)
.args(["-c", "copy"])
.arg(output);
let result = run(&mut cmd, "concat");
let _ = std::fs::remove_file(&list_path);
result
run(&mut cmd, "concat")
}
fn run(cmd: &mut Command, label: &str) -> Result<()> {
@@ -706,6 +717,8 @@ mod tests {
trim_start_secs: None,
trim_end_secs: None,
clicks: vec![],
clip_width: 1920,
clip_height: 1080,
progress_tx: None,
}
}
@@ -780,7 +793,7 @@ mod tests {
#[test]
fn click_filters_capped_at_max() {
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();
let req = TranscodeRequest {
clicks,
+97 -73
View File
@@ -9,7 +9,8 @@ mod window_picker;
mod windows_list;
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 serde::{Deserialize, Serialize};
@@ -20,6 +21,10 @@ use std::str::FromStr;
use crate::bootstrap::FfmpegStatus;
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)]
pub struct CaptureRect {
pub x: i32,
@@ -37,6 +42,7 @@ pub struct AppState {
pub last_clip: Mutex<Option<RecordedClip>>,
pub session: Mutex<Option<SessionState>>,
pub picker: Mutex<Option<window_picker::PickerSession>>,
pub overlay_poll_shutdown: Arc<AtomicBool>,
}
pub struct SessionState {
@@ -116,7 +122,7 @@ struct AppStatus {
#[tauri::command]
fn get_status(state: State<'_, AppState>) -> AppStatus {
let cfg = state.config.lock().expect("config mutex");
let cfg = lock(&state.config);
AppStatus {
ffmpeg: bootstrap::check(&state.app_dir),
needs_first_run: cfg.needs_first_run(),
@@ -125,7 +131,7 @@ fn get_status(state: State<'_, AppState>) -> AppStatus {
#[tauri::command]
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> {
@@ -184,7 +190,7 @@ fn save_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();
*lock(&state.config) = config.clone();
let hotkey_result = register_hotkeys(&app, &config);
Ok(SaveConfigResult { hotkey_result })
}
@@ -324,12 +330,12 @@ fn start_capture(
request: Option<StartCaptureRequest>,
) -> Result<(), String> {
{
let slot = state.capture.lock().expect("capture mutex");
let slot = lock(&state.capture);
if slot.is_some() {
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);
std::fs::create_dir_all(&temp).map_err(|e| format!("creating temp dir: {e}"))?;
clear_temp_segments(&state.app_dir);
@@ -399,40 +405,34 @@ fn start_capture(
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;
*lock(&state.session) = Some(session_state);
*lock(&state.capture) = Some(session);
*lock(&state.audio) = audio_session;
*lock(&state.click_recorder) = click_rec;
Ok(())
}
#[tauri::command]
fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
let session = state
.capture
.lock()
.expect("capture mutex")
let session = lock(&state.capture)
.take()
.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 path = session.stop().map_err(|e| format!("{e:#}"))?;
let audio_path = state
.audio
.lock()
.expect("audio mutex")
let audio_path = lock(&state.audio)
.take()
.and_then(|a| a.stop().ok());
let new_clicks: Vec<clicks::Click> = state
.click_recorder
.lock()
.expect("click mutex")
let new_clicks: Vec<clicks::Click> = lock(&state.click_recorder)
.take()
.map(|r| r.stop())
.unwrap_or_default();
let mut ss = state.session.lock().expect("session mutex");
let mut ss = lock(&state.session);
let ss = ss
.as_mut()
.ok_or_else(|| "no session state".to_string())?;
@@ -455,13 +455,13 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
#[tauri::command]
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() {
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 = lock(&state.session);
let ss = ss
.as_ref()
.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 ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
if !ffmpeg.is_file() {
@@ -502,9 +502,9 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
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;
*lock(&state.capture) = Some(session);
*lock(&state.audio) = audio_session;
*lock(&state.click_recorder) = click_rec;
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> {
set_overlay_clickthrough(&app, false);
let mut ss = state
.session
.lock()
.expect("session mutex")
let mut ss = lock(&state.session)
.take()
.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 session.has_crashed() {
return Err("recording failed - ffmpeg encoder crashed".to_string());
}
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();
let live_audio = lock(&state.audio).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")
let live_clicks = lock(&state.click_recorder)
.take()
.map(|r| r.stop())
.unwrap_or_default();
@@ -623,7 +620,7 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
crop: ss.crop,
clicks: ss.clicks.clone(),
};
*state.last_clip.lock().expect("clip mutex") = Some(clip.clone());
*lock(&state.last_clip) = Some(clip.clone());
Ok(clip)
}
@@ -647,7 +644,7 @@ pub struct ExportRequest {
#[tauri::command]
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);
dir.join(format!(
"bytesize-{}.{}",
@@ -670,10 +667,7 @@ fn render_preview(
state: State<'_, AppState>,
request: PreviewRequest,
) -> Result<PathBuf, String> {
let clip = state
.last_clip
.lock()
.expect("clip mutex")
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
@@ -709,10 +703,7 @@ fn extract_thumbnails(
state: State<'_, AppState>,
fps: u32,
) -> Result<Vec<PathBuf>, String> {
let clip = state
.last_clip
.lock()
.expect("clip mutex")
let clip = lock(&state.last_clip)
.clone()
.ok_or_else(|| "no recorded clip available".to_string())?;
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_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 windows::Win32::Foundation::{HWND, POINT, RECT};
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 || {
let mut last_inner: Option<bool> = None;
loop {
while !shutdown.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(30));
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
// so we don't fight it.
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 {
last_inner = Some(true);
continue;
@@ -843,7 +831,39 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
.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);
// 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())
}
@@ -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);
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
.map_err(|e| e.to_string())?;
let _ = apply_overlay_region(&win);
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() {
existing.stop();
}
@@ -951,7 +970,7 @@ fn close_window_picker(
app: AppHandle,
state: State<'_, AppState>,
) -> Result<(), String> {
if let Some(session) = state.picker.lock().expect("picker mutex").take() {
if let Some(session) = lock(&state.picker).take() {
session.stop();
}
if let Some(picker) = app.get_webview_window("picker") {
@@ -1078,8 +1097,6 @@ fn set_overlay_to_window(
}
.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(())
}
@@ -1170,9 +1187,12 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
#[tauri::command]
fn open_url(url: String) -> Result<(), String> {
use std::process::Command;
Command::new("cmd")
.args(["/C", "start", "", &url])
if !url.starts_with("http://") && !url.starts_with("https://") {
return Err("only http/https URLs are supported".to_string());
}
use std::os::windows::process::CommandExt;
std::process::Command::new("cmd")
.raw_arg(format!("/C start \"\" \"{url}\""))
.spawn()
.map_err(|e| format!("opening url: {e}"))?;
Ok(())
@@ -1180,11 +1200,8 @@ fn open_url(url: String) -> Result<(), String> {
#[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")
let cfg = lock(&state.config).clone();
let clip = lock(&state.last_clip)
.clone()
.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,
x: (((c.x - src_origin.0) as f64) * scale).round() as i32,
y: (((c.y - src_origin.1) as f64) * scale).round() as i32,
button: c.button,
})
.collect();
@@ -1258,6 +1276,8 @@ fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) ->
trim_start_secs: trim_start,
trim_end_secs: trim_end,
clicks: transformed_clicks,
clip_width: clip.width,
clip_height: clip.height,
progress_tx: None,
};
@@ -1322,6 +1342,7 @@ pub fn run() {
last_clip: Mutex::new(None),
session: Mutex::new(None),
picker: Mutex::new(None),
overlay_poll_shutdown: Arc::new(AtomicBool::new(false)),
};
tauri::Builder::default()
@@ -1334,8 +1355,8 @@ pub fn run() {
}
let cfg = {
let st = app.state::<AppState>();
let guard = st.config.lock().expect("config mutex");
guard.clone()
let cfg = lock(&st.config).clone();
cfg
};
let kind = if cfg
.hotkeys
@@ -1377,11 +1398,14 @@ pub fn run() {
.setup(|app| {
let (check_on_launch, cfg) = {
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)
};
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 {
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {
+12
View File
@@ -106,8 +106,20 @@ pub fn write_apply_script(app_dir: &Path) -> Result<PathBuf> {
let body = format!(
"@echo off\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\
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\
del \"%~f0\"\r\n",
exe = exe_name