format the rust sources and split the functions that pushed over the line
This commit is contained in:
+234
-140
@@ -30,9 +30,9 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{anyhow, Context as _, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::str::FromStr;
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
|
||||
use std::str::FromStr;
|
||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
|
||||
|
||||
use crate::bootstrap::FfmpegStatus;
|
||||
@@ -320,10 +320,7 @@ async fn download_ffmpeg(app: AppHandle, state: State<'_, AppState>) -> Result<(
|
||||
let app_dir = state.app_dir.clone();
|
||||
let app_handle = app.clone();
|
||||
bootstrap::download(&app_dir, move |downloaded, total| {
|
||||
drop(app_handle.emit(
|
||||
"ffmpeg-progress",
|
||||
DownloadProgress { downloaded, total },
|
||||
));
|
||||
drop(app_handle.emit("ffmpeg-progress", DownloadProgress { downloaded, total }));
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("{e:#}"))
|
||||
@@ -394,7 +391,12 @@ fn clear_temp_segments(app_dir: &Path, keep_previews: bool) {
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
fn adjust_audio_length(
|
||||
path: &Path,
|
||||
sample_rate: u32,
|
||||
channels: u16,
|
||||
target_secs: f64,
|
||||
) -> Result<()> {
|
||||
use std::io::Write;
|
||||
let bytes_per_sec = f64::from(sample_rate) * f64::from(channels) * 4.0;
|
||||
let target_bytes = encode::round_u64(target_secs * bytes_per_sec);
|
||||
@@ -469,7 +471,8 @@ fn pad_audio_head(path: &Path, sample_rate: u32, channels: u16, head_secs: f64)
|
||||
}
|
||||
tracing::debug!(
|
||||
"padded audio head with {:.1}ms ({} bytes) of silence",
|
||||
head_secs * 1000.0, pad_bytes
|
||||
head_secs * 1000.0,
|
||||
pad_bytes
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -566,7 +569,10 @@ fn start_capture(
|
||||
clear_temp_segments(&state.app_dir, true);
|
||||
|
||||
let crop = request.as_ref().and_then(|r| r.crop);
|
||||
let fps = request.as_ref().and_then(|r| r.fps).unwrap_or(cfg.capture.default_fps);
|
||||
let fps = request
|
||||
.as_ref()
|
||||
.and_then(|r| r.fps)
|
||||
.unwrap_or(cfg.capture.default_fps);
|
||||
let output = segment_path(&state.app_dir, 1);
|
||||
|
||||
let ffmpeg = bootstrap::ffmpeg_path(&state.app_dir);
|
||||
@@ -574,8 +580,7 @@ fn start_capture(
|
||||
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 (monitor_w, monitor_h) = capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let session = capture::start(
|
||||
output,
|
||||
@@ -639,7 +644,11 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
let fixed_path = raw_path.with_extension("fixed.mp4");
|
||||
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
||||
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
||||
let path = if fixed_path.exists() { fixed_path } else { raw_path };
|
||||
let path = if fixed_path.exists() {
|
||||
fixed_path
|
||||
} else {
|
||||
raw_path
|
||||
};
|
||||
|
||||
let audio_path = lock(&state.audio).take().map(audio::AudioSession::stop);
|
||||
|
||||
@@ -649,9 +658,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut ss = lock(&state.session);
|
||||
let ss = ss
|
||||
.as_mut()
|
||||
.ok_or_else(|| "no session state".to_string())?;
|
||||
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 {
|
||||
@@ -681,12 +688,7 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
||||
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,
|
||||
)
|
||||
(ss.capture_cursor, ss.audio, ss.crop, ss.segments.len() + 1)
|
||||
};
|
||||
|
||||
let (fps, quality) = {
|
||||
@@ -719,13 +721,12 @@ fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), Stri
|
||||
/// without ending the recording. Stops the current session, appends its
|
||||
/// pcm segment to the session, and starts a new one with a fresh file.
|
||||
#[tauri::command]
|
||||
fn restart_audio_capture(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
fn restart_audio_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
let audio_enabled = {
|
||||
let ss = lock(&state.session);
|
||||
let ss = ss.as_ref().ok_or_else(|| "no session in progress".to_string())?;
|
||||
let ss = ss
|
||||
.as_ref()
|
||||
.ok_or_else(|| "no session in progress".to_string())?;
|
||||
if !ss.audio {
|
||||
return Err("audio is not enabled for this recording".to_string());
|
||||
}
|
||||
@@ -736,7 +737,9 @@ fn restart_audio_capture(
|
||||
// or click recording - they keep running.
|
||||
let next_idx = {
|
||||
let mut ss = lock(&state.session);
|
||||
let ss = ss.as_mut().ok_or_else(|| "no session in progress".to_string())?;
|
||||
let ss = ss
|
||||
.as_mut()
|
||||
.ok_or_else(|| "no session in progress".to_string())?;
|
||||
if let Some(a) = lock(&state.audio).take() {
|
||||
ss.audio_segments.push(a.stop());
|
||||
}
|
||||
@@ -780,7 +783,11 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
let fixed_path = raw_path.with_extension("fixed.mp4");
|
||||
capture::fix_intermediate_fps(&ffmpeg, &raw_path, &fixed_path, elapsed, frames, pipe_fps)
|
||||
.map_err(|e| format!("fixing fps: {e:#}"))?;
|
||||
let final_path = if fixed_path.exists() { fixed_path } else { raw_path };
|
||||
let final_path = if fixed_path.exists() {
|
||||
fixed_path
|
||||
} else {
|
||||
raw_path
|
||||
};
|
||||
ss.segments.push(final_path);
|
||||
ss.total_recorded_secs += elapsed;
|
||||
}
|
||||
@@ -845,23 +852,13 @@ fn stop_capture(state: State<'_, AppState>) -> Result<RecordedClip, String> {
|
||||
if audio_start > video_start {
|
||||
let head_offset_secs = audio_start.duration_since(video_start).as_secs_f64();
|
||||
if head_offset_secs > 0.001 {
|
||||
pad_audio_head(
|
||||
&audio_concat,
|
||||
sample_rate,
|
||||
channels,
|
||||
head_offset_secs,
|
||||
)
|
||||
.map_err(|e| format!("padding audio head: {e:#}"))?;
|
||||
pad_audio_head(&audio_concat, sample_rate, channels, head_offset_secs)
|
||||
.map_err(|e| format!("padding audio head: {e:#}"))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
adjust_audio_length(
|
||||
&audio_concat,
|
||||
sample_rate,
|
||||
channels,
|
||||
ss.total_recorded_secs,
|
||||
)
|
||||
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
|
||||
adjust_audio_length(&audio_concat, sample_rate, channels, ss.total_recorded_secs)
|
||||
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
|
||||
encode::mux_with_audio(
|
||||
&ffmpeg,
|
||||
&video_concat,
|
||||
@@ -929,13 +926,9 @@ pub struct ExportRequest {
|
||||
#[tauri::command]
|
||||
fn default_output_path(state: State<'_, AppState>, format: Format) -> String {
|
||||
let dir = output_dir(&state.app_dir, &lock(&state.config));
|
||||
dir.join(format!(
|
||||
"bytesize-{}.{}",
|
||||
timestamp_slug(),
|
||||
ext_for(format)
|
||||
))
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
dir.join(format!("bytesize-{}.{}", timestamp_slug(), ext_for(format)))
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -960,10 +953,7 @@ pub struct PreviewRequest {
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
fn render_preview(
|
||||
state: State<'_, AppState>,
|
||||
request: PreviewRequest,
|
||||
) -> Result<PathBuf, String> {
|
||||
fn render_preview(state: State<'_, AppState>, request: PreviewRequest) -> Result<PathBuf, String> {
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||
@@ -995,12 +985,25 @@ fn render_preview(
|
||||
GifDither::None => "none",
|
||||
};
|
||||
encode::render_gif_preview(
|
||||
&ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width,
|
||||
request.gif_colors.unwrap_or(256), dither_str, clip.duration_secs,
|
||||
).map_err(|e| format!("{e:#}"))?;
|
||||
&ffmpeg,
|
||||
&clip.temp_path,
|
||||
&preview_path,
|
||||
midpoint,
|
||||
target_width,
|
||||
request.gif_colors.unwrap_or(256),
|
||||
dither_str,
|
||||
clip.duration_secs,
|
||||
)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
} else {
|
||||
encode::render_preview(&ffmpeg, &clip.temp_path, &preview_path, midpoint, target_width)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
encode::render_preview(
|
||||
&ffmpeg,
|
||||
&clip.temp_path,
|
||||
&preview_path,
|
||||
midpoint,
|
||||
target_width,
|
||||
)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
}
|
||||
Ok(preview_path)
|
||||
}
|
||||
@@ -1040,16 +1043,28 @@ fn estimate_gif_params(request: PreviewRequest) -> GifEstimate {
|
||||
let height = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
||||
let dims_label = format!("{w}x{height} @ {fps}fps");
|
||||
|
||||
GifEstimate { width: w, fps, height, dims_label }
|
||||
GifEstimate {
|
||||
width: w,
|
||||
fps,
|
||||
height,
|
||||
dims_label,
|
||||
}
|
||||
}
|
||||
|
||||
/// Geometric grid from 100KB to 200MB, used to sample the GIF size estimator
|
||||
/// across a range of targets so the frontend can interpolate locally.
|
||||
const GIF_ESTIMATE_GRID: &[u64] = &[
|
||||
100_000, 200_000, 500_000,
|
||||
1_048_576, 2_097_152, 5_242_880,
|
||||
10_485_760, 20_971_520, 52_428_800,
|
||||
104_857_600, 209_715_200,
|
||||
100_000,
|
||||
200_000,
|
||||
500_000,
|
||||
1_048_576,
|
||||
2_097_152,
|
||||
5_242_880,
|
||||
10_485_760,
|
||||
20_971_520,
|
||||
52_428_800,
|
||||
104_857_600,
|
||||
209_715_200,
|
||||
];
|
||||
|
||||
/// The size-table scan sweeps target sizes itself, so it needs only the inputs
|
||||
@@ -1091,7 +1106,12 @@ fn estimate_gif_params_table(request: GifTableRequest) -> GifEstimateTable {
|
||||
};
|
||||
let (w, f) = encode::gif_params(&budget, request.clip_width, request.clip_height);
|
||||
let h = encode::gif_height_for_width(w, request.clip_width, request.clip_height);
|
||||
points.push(GifEstimatePoint { target_bytes: target, width: w, fps: f, height: h });
|
||||
points.push(GifEstimatePoint {
|
||||
target_bytes: target,
|
||||
width: w,
|
||||
fps: f,
|
||||
height: h,
|
||||
});
|
||||
}
|
||||
GifEstimateTable { points }
|
||||
}
|
||||
@@ -1150,12 +1170,21 @@ mod tests {
|
||||
|
||||
// Mid-session: drop the recording artifacts, keep the live previews.
|
||||
clear_temp_segments(&dir, true);
|
||||
assert!(!temp.join("audio-concat.pcm.padtmp").exists(), "padtmp should be swept");
|
||||
assert!(
|
||||
!temp.join("audio-concat.pcm.padtmp").exists(),
|
||||
"padtmp should be swept"
|
||||
);
|
||||
assert!(!temp.join("segment-001.mp4").exists());
|
||||
assert!(!temp.join("audio-001.pcm").exists());
|
||||
assert!(!temp.join("ffmpeg2pass-0.log").exists(), "pass stats should be swept");
|
||||
assert!(
|
||||
!temp.join("ffmpeg2pass-0.log").exists(),
|
||||
"pass stats should be swept"
|
||||
);
|
||||
assert!(!temp.join("ffmpeg2pass-0.log.mbtree").exists());
|
||||
assert!(temp.join("preview.png").exists(), "preview must survive a new capture");
|
||||
assert!(
|
||||
temp.join("preview.png").exists(),
|
||||
"preview must survive a new capture"
|
||||
);
|
||||
assert!(temp.join("raw-preview.png").exists());
|
||||
|
||||
// Exit/startup: everything goes.
|
||||
@@ -1167,7 +1196,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn estimate_balanced_matches_gif_params() { // The frontend uses estimate_gif_params for the on-screen dims label.
|
||||
fn estimate_balanced_matches_gif_params() {
|
||||
// The frontend uses estimate_gif_params for the on-screen dims label.
|
||||
// The backend uses gif_params for the actual encode. The two must agree.
|
||||
let req = make_request(8 * 1024 * 1024, 30, GifBudgetMode::Balanced);
|
||||
let est = estimate_gif_params(req);
|
||||
@@ -1187,7 +1217,10 @@ mod tests {
|
||||
let expected_height = encode::gif_height_for_width(encode_w, 1920, 1080);
|
||||
assert_eq!(est.height, expected_height);
|
||||
// dims_label should be "{w}x{h} @ {fps}fps"
|
||||
assert_eq!(est.dims_label, format!("{}x{} @ {}fps", encode_w, est.height, encode_fps));
|
||||
assert_eq!(
|
||||
est.dims_label,
|
||||
format!("{}x{} @ {}fps", encode_w, est.height, encode_fps)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1201,10 +1234,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
fn extract_thumbnails(
|
||||
state: State<'_, AppState>,
|
||||
fps: u32,
|
||||
) -> Result<Vec<PathBuf>, String> {
|
||||
fn extract_thumbnails(state: State<'_, AppState>, fps: u32) -> Result<Vec<PathBuf>, String> {
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||
@@ -1218,10 +1248,7 @@ fn extract_thumbnails(
|
||||
}
|
||||
|
||||
#[tauri::command(async)]
|
||||
fn render_raw_preview(
|
||||
state: State<'_, AppState>,
|
||||
timestamp: f64,
|
||||
) -> Result<PathBuf, String> {
|
||||
fn render_raw_preview(state: State<'_, AppState>, timestamp: f64) -> Result<PathBuf, String> {
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||
@@ -1230,8 +1257,14 @@ fn render_raw_preview(
|
||||
return Err("ffmpeg.exe not found".to_string());
|
||||
}
|
||||
let out_path = temp_dir(&state.app_dir).join("raw-preview.png");
|
||||
encode::render_preview(&ffmpeg, &clip.temp_path, &out_path, timestamp, clip.width.min(1280))
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
encode::render_preview(
|
||||
&ffmpeg,
|
||||
&clip.temp_path,
|
||||
&out_path,
|
||||
timestamp,
|
||||
clip.width.min(1280),
|
||||
)
|
||||
.map_err(|e| format!("{e:#}"))?;
|
||||
Ok(out_path)
|
||||
}
|
||||
|
||||
@@ -1246,7 +1279,6 @@ pub struct ExportResult {
|
||||
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
|
||||
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 24.0;
|
||||
|
||||
|
||||
/// Remove temporary recording artifacts (segments, previews, thumbs).
|
||||
/// Called on app exit so a discarded clip doesn't linger in `temp/`.
|
||||
fn cleanup_temp_on_exit(app: &AppHandle) {
|
||||
@@ -1299,12 +1331,7 @@ fn overlay_should_ignore_cursor(app: &AppHandle) -> Option<bool> {
|
||||
let inner_right = vr - border;
|
||||
let inner_bottom = vb - border;
|
||||
|
||||
Some(
|
||||
pt.x >= inner_left
|
||||
&& pt.x < inner_right
|
||||
&& pt.y >= inner_top
|
||||
&& pt.y < inner_bottom,
|
||||
)
|
||||
Some(pt.x >= inner_left && pt.x < inner_right && pt.y >= inner_top && pt.y < inner_bottom)
|
||||
}
|
||||
|
||||
fn start_overlay_clickthrough_poll(
|
||||
@@ -1323,7 +1350,9 @@ fn start_overlay_clickthrough_poll(
|
||||
// flips the flag and notifies.
|
||||
{
|
||||
let (lock, cvar) = &*live;
|
||||
let mut active = lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let mut active = lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
while !*active && !shutdown.load(Ordering::Relaxed) {
|
||||
let (g, _timeout) = cvar
|
||||
.wait_timeout(active, Duration::from_secs(1))
|
||||
@@ -1334,8 +1363,7 @@ fn start_overlay_clickthrough_poll(
|
||||
|
||||
let target = overlay_should_ignore_cursor(&app);
|
||||
if target != last {
|
||||
if let (Some(overlay), Some(value)) = (app.get_webview_window("overlay"), target)
|
||||
{
|
||||
if let (Some(overlay), Some(value)) = (app.get_webview_window("overlay"), target) {
|
||||
drop(overlay.set_ignore_cursor_events(value));
|
||||
}
|
||||
last = target;
|
||||
@@ -1369,9 +1397,12 @@ fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(),
|
||||
fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
use windows::Win32::Foundation::{HWND, POINT};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
GetMonitorInfoW, MonitorFromPoint, MONITOR_DEFAULTTOPRIMARY, MONITOR_DEFAULTTONULL, MONITORINFO,
|
||||
GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONULL,
|
||||
MONITOR_DEFAULTTOPRIMARY,
|
||||
};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER,
|
||||
};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER};
|
||||
|
||||
let win = app
|
||||
.get_webview_window("overlay")
|
||||
@@ -1383,14 +1414,19 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
{
|
||||
let st = app.state::<AppState>();
|
||||
let (lock, cvar) = &*st.overlay_poll_live;
|
||||
*lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true;
|
||||
*lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = true;
|
||||
cvar.notify_one();
|
||||
}
|
||||
|
||||
// If the overlay is off-screen (monitor disconnected), center on primary
|
||||
if let Ok(raw) = win.hwnd() {
|
||||
if let Some((vl, vt, vr, vb)) = visible_window_bounds(raw.0 as isize) {
|
||||
let center = POINT { x: i32::midpoint(vl, vr), y: i32::midpoint(vt, vb) };
|
||||
let center = POINT {
|
||||
x: i32::midpoint(vl, vr),
|
||||
y: i32::midpoint(vt, vb),
|
||||
};
|
||||
// MonitorFromPoint only reads the POINT by value and returns null
|
||||
// for "no monitor", which the next branch handles.
|
||||
//
|
||||
@@ -1400,10 +1436,14 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
let hwnd = HWND(raw.0.cast::<std::ffi::c_void>());
|
||||
// SAFETY: same value-only call; MONITOR_DEFAULTTOPRIMARY cannot
|
||||
// fail on a running desktop.
|
||||
let primary = unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
|
||||
let primary =
|
||||
unsafe { MonitorFromPoint(POINT { x: 0, y: 0 }, MONITOR_DEFAULTTOPRIMARY) };
|
||||
// cbSize is required by GetMonitorInfoW and is set from the
|
||||
// actual struct size, so the write below stays in bounds.
|
||||
let mut mi = MONITORINFO { cbSize: u32::try_from(size_of::<MONITORINFO>()).unwrap_or(0), ..Default::default() };
|
||||
let mut mi = MONITORINFO {
|
||||
cbSize: u32::try_from(size_of::<MONITORINFO>()).unwrap_or(0),
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `mi` is a live local of the declared size, and the
|
||||
// result is checked with as_bool() before mi is read.
|
||||
if unsafe { GetMonitorInfoW(primary, &raw mut mi) }.as_bool() {
|
||||
@@ -1415,7 +1455,17 @@ fn show_overlay(app: AppHandle) -> Result<(), String> {
|
||||
drop(
|
||||
// SAFETY: `hwnd` is the overlay's live handle; the flags
|
||||
// keep this a size-only, non-activating move.
|
||||
unsafe { SetWindowPos(hwnd, Some(HWND_TOP), cx, cy, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE) },
|
||||
unsafe {
|
||||
SetWindowPos(
|
||||
hwnd,
|
||||
Some(HWND_TOP),
|
||||
cx,
|
||||
cy,
|
||||
0,
|
||||
0,
|
||||
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE,
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1435,14 +1485,21 @@ fn hide_overlay(app: AppHandle) -> Result<(), String> {
|
||||
{
|
||||
let st = app.state::<AppState>();
|
||||
let (lock, cvar) = &*st.overlay_poll_live;
|
||||
*lock.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = false;
|
||||
*lock
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = false;
|
||||
cvar.notify_one();
|
||||
}
|
||||
win.hide().map_err(|e| format!("hiding overlay: {e:#}"))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, height: u32) -> Result<(), String> {
|
||||
fn set_overlay_size(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Result<(), String> {
|
||||
use tauri::{LogicalSize, Size};
|
||||
let win = app
|
||||
.get_webview_window("overlay")
|
||||
@@ -1460,7 +1517,11 @@ fn set_overlay_size(app: AppHandle, state: State<'_, AppState>, width: u32, heig
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<f64>) -> Result<(), String> {
|
||||
fn set_overlay_aspect(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
ratio: Option<f64>,
|
||||
) -> Result<(), String> {
|
||||
*lock(&state.overlay_aspect_ratio) = ratio;
|
||||
if let Some(r) = ratio {
|
||||
// Enforce on current size
|
||||
@@ -1468,14 +1529,17 @@ fn set_overlay_aspect(app: AppHandle, state: State<'_, AppState>, ratio: Option<
|
||||
.get_webview_window("overlay")
|
||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||
let scale = win.scale_factor().unwrap_or(1.0);
|
||||
let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
|
||||
let sz = win
|
||||
.inner_size()
|
||||
.map_err(|e| format!("getting window size: {e:#}"))?;
|
||||
let cur_w = f64::from(sz.width) / scale;
|
||||
let cur_h = f64::from(sz.height) / scale;
|
||||
let target_h = cur_w / r;
|
||||
if (target_h - cur_h).abs() > 1.0 {
|
||||
use tauri::{LogicalSize, Size};
|
||||
let final_w = cur_w + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
||||
let final_h = target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
||||
let final_h =
|
||||
target_h + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
|
||||
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
|
||||
.map_err(|e| format!("setting overlay size: {e:#}"))?;
|
||||
}
|
||||
@@ -1491,7 +1555,9 @@ fn get_overlay_aspect(state: State<'_, AppState>) -> Option<f64> {
|
||||
#[tauri::command]
|
||||
fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
use windows::Win32::Foundation::HWND;
|
||||
use windows::Win32::UI::WindowsAndMessaging::{SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
SetWindowPos, HWND_TOP, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOZORDER,
|
||||
};
|
||||
|
||||
let Some(ratio) = *lock(&state.overlay_aspect_ratio) else {
|
||||
return Ok(());
|
||||
@@ -1500,7 +1566,9 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
|
||||
.get_webview_window("overlay")
|
||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||
let scale = win.scale_factor().unwrap_or(1.0);
|
||||
let sz = win.inner_size().map_err(|e| format!("getting window size: {e:#}"))?;
|
||||
let sz = win
|
||||
.inner_size()
|
||||
.map_err(|e| format!("getting window size: {e:#}"))?;
|
||||
let cur_w = f64::from(sz.width) / scale;
|
||||
let cur_h = f64::from(sz.height) / scale;
|
||||
let target_h = (cur_w / ratio).round();
|
||||
@@ -1514,13 +1582,22 @@ fn enforce_overlay_aspect(app: AppHandle, state: State<'_, AppState>) -> Result<
|
||||
let border = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
||||
let titlebar = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||
let outer_w = sz.width.cast_signed().max(2);
|
||||
let outer_h = encode::round_i32(target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0);
|
||||
let outer_h =
|
||||
encode::round_i32(target_h * scale + f64::from(titlebar) + f64::from(border) * 2.0);
|
||||
// SAFETY: `hwnd` is the overlay's live handle; the flags keep the resize
|
||||
// non-activating and non-reordering, and no pointers are involved.
|
||||
unsafe {
|
||||
SetWindowPos(hwnd, Some(HWND_TOP), 0, 0, outer_w, outer_h,
|
||||
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE)
|
||||
}.map_err(|e| format!("SetWindowPos: {e}"))?;
|
||||
SetWindowPos(
|
||||
hwnd,
|
||||
Some(HWND_TOP),
|
||||
0,
|
||||
0,
|
||||
outer_w,
|
||||
outer_h,
|
||||
SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("SetWindowPos: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1530,14 +1607,10 @@ fn list_windows() -> Vec<windows_list::WindowInfo> {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_window_picker(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
fn open_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
use tauri::{PhysicalPosition, PhysicalSize, Position, Size};
|
||||
|
||||
let (mw, mh) =
|
||||
capture::primary_monitor_dims().map_err(|e| format!("{e:#}"))?;
|
||||
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"] {
|
||||
@@ -1565,7 +1638,9 @@ fn open_window_picker(
|
||||
.map_err(|e| format!("setting picker position: {e:#}"))?;
|
||||
drop(picker.set_ignore_cursor_events(false));
|
||||
drop(picker.set_always_on_top(true));
|
||||
picker.show().map_err(|e| format!("showing picker: {e:#}"))?;
|
||||
picker
|
||||
.show()
|
||||
.map_err(|e| format!("showing picker: {e:#}"))?;
|
||||
if let Ok(h) = picker.hwnd() {
|
||||
use windows::Win32::Foundation::{HWND, RECT};
|
||||
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
|
||||
@@ -1587,8 +1662,14 @@ fn open_window_picker(
|
||||
});
|
||||
tracing::debug!(
|
||||
"picker window: GetWindowRect=({},{},{},{}) DwmBounds=({},{},{},{})",
|
||||
gr.left, gr.top, gr.right, gr.bottom,
|
||||
dr.left, dr.top, dr.right, dr.bottom
|
||||
gr.left,
|
||||
gr.top,
|
||||
gr.right,
|
||||
gr.bottom,
|
||||
dr.left,
|
||||
dr.top,
|
||||
dr.right,
|
||||
dr.bottom
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1609,10 +1690,7 @@ fn open_window_picker(
|
||||
clippy::unnecessary_wraps,
|
||||
reason = "Result is part of the tauri::command contract the frontend invokes"
|
||||
)]
|
||||
fn close_window_picker(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), String> {
|
||||
fn close_window_picker(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||
if let Some(session) = lock(&state.picker).take() {
|
||||
session.stop();
|
||||
}
|
||||
@@ -1786,11 +1864,13 @@ fn get_overlay_rect(app: AppHandle) -> Result<CaptureRect, String> {
|
||||
let win = app
|
||||
.get_webview_window("overlay")
|
||||
.ok_or_else(|| "overlay window not found".to_string())?;
|
||||
let scale = win.scale_factor().map_err(|e| format!("getting scale factor: {e:#}"))?;
|
||||
let scale = win
|
||||
.scale_factor()
|
||||
.map_err(|e| format!("getting scale factor: {e:#}"))?;
|
||||
let raw = win.hwnd().map_err(|e| format!("hwnd: {e}"))?;
|
||||
|
||||
let (vl, vt, vr, vb) = visible_window_bounds(raw.0 as isize)
|
||||
.ok_or_else(|| "GetWindowRect failed".to_string())?;
|
||||
let (vl, vt, vr, vb) =
|
||||
visible_window_bounds(raw.0 as isize).ok_or_else(|| "GetWindowRect failed".to_string())?;
|
||||
|
||||
let border_phys = encode::round_i32(OVERLAY_BORDER_LOGICAL_PX * scale);
|
||||
let titlebar_phys = encode::round_i32(OVERLAY_TITLEBAR_LOGICAL_PX * scale);
|
||||
@@ -1821,7 +1901,8 @@ fn reveal_in_explorer(path: String) -> Result<(), String> {
|
||||
|
||||
let canonical = std::fs::canonicalize(&path).ok();
|
||||
let normalized = canonical
|
||||
.as_ref().map_or_else(|| path.clone(), |p| p.to_string_lossy().into_owned());
|
||||
.as_ref()
|
||||
.map_or_else(|| path.clone(), |p| p.to_string_lossy().into_owned());
|
||||
let stripped = normalized
|
||||
.strip_prefix(r"\\?\")
|
||||
.unwrap_or(&normalized)
|
||||
@@ -1889,8 +1970,12 @@ fn read_log_tail(log_dir: &Path) -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((_, path)) = newest else { return String::new() };
|
||||
let Ok(data) = std::fs::read(&path) else { return String::new() };
|
||||
let Some((_, path)) = newest else {
|
||||
return String::new();
|
||||
};
|
||||
let Ok(data) = std::fs::read(&path) else {
|
||||
return String::new();
|
||||
};
|
||||
// saturating_sub keeps start at or below data.len(), so the tail slice
|
||||
// always exists; get() just makes that explicit.
|
||||
let start = data.len().saturating_sub(TAIL_BYTES);
|
||||
@@ -1976,7 +2061,11 @@ impl Drop for ExportGuard {
|
||||
reason = "one export transaction; the request translation feeds directly into the encode call"
|
||||
)]
|
||||
#[tauri::command]
|
||||
async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result<ExportResult, String> {
|
||||
async fn export(
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
request: ExportRequest,
|
||||
) -> Result<ExportResult, String> {
|
||||
if state.exporting.swap(true, Ordering::SeqCst) {
|
||||
return Err("an export is already running".to_string());
|
||||
}
|
||||
@@ -1987,7 +2076,12 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
||||
let clip = lock(&state.last_clip)
|
||||
.clone()
|
||||
.ok_or_else(|| "no recorded clip available".to_string())?;
|
||||
(cfg, clip, state.app_dir.clone(), state.export_cancel.clone())
|
||||
(
|
||||
cfg,
|
||||
clip,
|
||||
state.app_dir.clone(),
|
||||
state.export_cancel.clone(),
|
||||
)
|
||||
};
|
||||
|
||||
let ffmpeg = bootstrap::ffmpeg_path(&app_dir);
|
||||
@@ -2007,8 +2101,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
||||
}
|
||||
};
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("creating output dir: {e:#}"))?;
|
||||
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);
|
||||
@@ -2025,12 +2118,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
||||
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),
|
||||
)
|
||||
(clip.monitor_width.max(1), (0, 0))
|
||||
};
|
||||
let scale = f64::from(clip.width) / f64::from(src_w);
|
||||
let transformed_clicks: Vec<clicks::Click> = clip
|
||||
@@ -2103,8 +2191,7 @@ async fn export(app: AppHandle, state: State<'_, AppState>, request: ExportReque
|
||||
.map_err(|e| format!("encode task panicked: {e:#}"))?;
|
||||
result.map_err(|e| format!("{e:#}"))?;
|
||||
|
||||
let size_bytes = std::fs::metadata(&out_path)
|
||||
.map_or(0, |m| m.len());
|
||||
let size_bytes = std::fs::metadata(&out_path).map_or(0, |m| m.len());
|
||||
Ok(ExportResult {
|
||||
met_target: size_bytes <= request.target_bytes,
|
||||
target_bytes: request.target_bytes,
|
||||
@@ -2148,7 +2235,9 @@ pub fn run() {
|
||||
let file_layer = tracing_subscriber::fmt::layer()
|
||||
.with_writer(file_writer)
|
||||
.with_ansi(false);
|
||||
let registry = tracing_subscriber::registry().with(env_filter).with(file_layer);
|
||||
let registry = tracing_subscriber::registry()
|
||||
.with(env_filter)
|
||||
.with(file_layer);
|
||||
#[cfg(debug_assertions)]
|
||||
let registry = registry.with(tracing_subscriber::fmt::layer().with_writer(std::io::stdout));
|
||||
#[cfg(test)]
|
||||
@@ -2166,8 +2255,13 @@ pub fn run() {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("could not create webview data dir at {}: {e}", webview_dir.display());
|
||||
tracing::error!("WebView2 will fall back to the system default - portability may be broken");
|
||||
tracing::error!(
|
||||
"could not create webview data dir at {}: {e}",
|
||||
webview_dir.display()
|
||||
);
|
||||
tracing::error!(
|
||||
"WebView2 will fall back to the system default - portability may be broken"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user