current state before improvement pass

This commit is contained in:
2026-05-27 18:56:36 +03:00
parent 5eb27ab779
commit f0775b8ff0
23 changed files with 3563 additions and 1853 deletions
+257 -113
View File
@@ -10,7 +10,6 @@ mod windows_list;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
@@ -19,7 +18,7 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
use std::str::FromStr;
use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec};
use crate::config::{Config, Format};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CaptureRect {
@@ -88,76 +87,19 @@ fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf {
}
fn timestamp_slug() -> String {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let local = chrono_like(now);
use windows::Win32::System::SystemInformation::GetLocalTime;
let st = unsafe { GetLocalTime() };
format!(
"{:04}{:02}{:02}-{:02}{:02}{:02}",
local.year, local.month, local.day, local.hour, local.minute, local.second
st.wYear,
st.wMonth,
st.wDay,
st.wHour,
st.wMinute,
st.wSecond
)
}
struct LocalTime {
year: u32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
}
fn chrono_like(epoch_secs: u64) -> LocalTime {
let seconds_per_day = 86400u64;
let days = epoch_secs / seconds_per_day;
let secs_in_day = epoch_secs % seconds_per_day;
let hour = (secs_in_day / 3600) as u32;
let minute = ((secs_in_day % 3600) / 60) as u32;
let second = (secs_in_day % 60) as u32;
let mut year = 1970u32;
let mut remaining = days as i64;
loop {
let leap = is_leap(year);
let days_in_year = if leap { 366 } else { 365 };
if remaining < days_in_year {
break;
}
remaining -= days_in_year;
year += 1;
}
let leap = is_leap(year);
let month_days: [i64; 12] = [
31,
if leap { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
let mut month = 1u32;
for d in month_days {
if remaining < d {
break;
}
remaining -= d;
month += 1;
}
let day = remaining as u32 + 1;
LocalTime { year, month, day, hour, minute, second }
}
fn is_leap(year: u32) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
fn ext_for(format: Format) -> &'static str {
match format {
Format::Gif => "gif",
@@ -190,37 +132,61 @@ fn parse_shortcut(s: &str) -> Option<Shortcut> {
Shortcut::from_str(s).ok()
}
fn register_hotkeys(app: &AppHandle, cfg: &Config) {
/// Result of attempting to register all hotkeys.
/// Each field is None if the hotkey was not set, or Some(true/false) for success/failure.
#[derive(Debug, Clone, Serialize)]
pub struct HotkeyRegistrationResult {
pub start_ok: Option<bool>,
pub stop_ok: Option<bool>,
pub pause_ok: Option<bool>,
}
fn register_hotkeys(app: &AppHandle, cfg: &Config) -> HotkeyRegistrationResult {
let gs = app.global_shortcut();
let _ = gs.unregister_all();
let mut registered: Vec<(Shortcut, &'static str)> = Vec::new();
if let Some(s) = cfg.hotkeys.start.as_deref().and_then(parse_shortcut) {
registered.push((s, "start"));
}
if let Some(s) = cfg.hotkeys.stop.as_deref().and_then(parse_shortcut) {
registered.push((s, "stop"));
}
if let Some(s) = cfg.hotkeys.pause.as_deref().and_then(parse_shortcut) {
registered.push((s, "pause"));
}
for (sc, _) in &registered {
if let Err(e) = gs.register(*sc) {
tracing::warn!("registering shortcut failed: {e}");
}
let start_ok = cfg
.hotkeys
.start
.as_deref()
.and_then(parse_shortcut)
.map(|sc| gs.register(sc).is_ok());
let stop_ok = cfg
.hotkeys
.stop
.as_deref()
.and_then(parse_shortcut)
.map(|sc| gs.register(sc).is_ok());
let pause_ok = cfg
.hotkeys
.pause
.as_deref()
.and_then(parse_shortcut)
.map(|sc| gs.register(sc).is_ok());
HotkeyRegistrationResult {
start_ok,
stop_ok,
pause_ok,
}
}
#[derive(Serialize)]
struct SaveConfigResult {
hotkey_result: HotkeyRegistrationResult,
}
#[tauri::command]
fn save_config(
app: AppHandle,
state: State<'_, AppState>,
config: Config,
) -> Result<(), String> {
) -> 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();
register_hotkeys(&app, &config);
Ok(())
let hotkey_result = register_hotkeys(&app, &config);
Ok(SaveConfigResult { hotkey_result })
}
#[derive(Clone, Serialize)]
@@ -320,6 +286,31 @@ fn clear_temp_segments(app_dir: &Path) {
let _ = std::fs::remove_file(temp.join("audio-concat.pcm"));
}
/// Pad or trim a raw f32le PCM file so its duration matches `target_secs`.
fn adjust_audio_length(path: &Path, sample_rate: u32, channels: u16, target_secs: f64) -> Result<()> {
use std::io::Write;
let bytes_per_sec = sample_rate as f64 * channels as f64 * 4.0;
let target_bytes = (target_secs * bytes_per_sec).round() as u64;
let current_bytes = std::fs::metadata(path)?.len();
if current_bytes == target_bytes {
return Ok(());
}
if current_bytes < target_bytes {
let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
let zeros = vec![0u8; 64 * 1024];
let mut remaining = target_bytes - current_bytes;
while remaining > 0 {
let to_write = remaining.min(zeros.len() as u64) as usize;
file.write_all(&zeros[..to_write])?;
remaining -= to_write as u64;
}
} else {
let file = std::fs::OpenOptions::new().write(true).open(path)?;
file.set_len(target_bytes)?;
}
Ok(())
}
fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
if let Some(win) = app.get_webview_window("overlay") {
let _ = win.set_ignore_cursor_events(enabled);
@@ -370,6 +361,7 @@ fn start_capture(
Ok(s) => Some(s),
Err(e) => {
tracing::warn!("audio capture failed to start: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
@@ -461,7 +453,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
}
#[tauri::command]
fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
fn resume_capture(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
{
let slot = state.capture.lock().expect("capture mutex");
if slot.is_some() {
@@ -496,6 +488,7 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
Ok(s) => Some(s),
Err(e) => {
tracing::warn!("audio resume failed: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None
}
}
@@ -590,6 +583,13 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
let audio_concat = temp.join("audio-concat.pcm");
encode::concat_pcm(&ss.audio_segments, &audio_concat)
.map_err(|e| format!("audio concat: {e:#}"))?;
adjust_audio_length(
&audio_concat,
ss.audio_sample_rate.unwrap(),
ss.audio_channels.unwrap(),
ss.total_recorded_secs,
)
.map_err(|e| format!("adjusting audio length: {e:#}"))?;
encode::mux_with_audio(
&ffmpeg,
&video_concat,
@@ -641,6 +641,8 @@ pub struct ExportRequest {
pub trim_end_secs: Option<f64>,
#[serde(default)]
pub output_path: Option<String>,
#[serde(default)]
pub crop: Option<CaptureRect>,
}
#[tauri::command]
@@ -679,19 +681,20 @@ fn render_preview(
return Err("ffmpeg.exe not found".to_string());
}
let target_width: u32 = match request.format {
Format::Gif => {
let frames = (request.fps as f64 * clip.duration_secs).max(1.0);
let budget = (request.target_bytes as f64) / (frames * 0.5);
let aspect = if clip.height == 0 {
16.0 / 9.0
} else {
clip.width as f64 / clip.height as f64
};
let w = (budget * aspect).sqrt();
(w.clamp(120.0, clip.width as f64) as u32 / 2) * 2
}
_ => clip.width,
let target_width: u32 = if request.format == Format::Gif {
// For GIF, derive a width that fits the target byte budget.
let frames = (request.fps as f64 * clip.duration_secs).max(1.0);
let budget = (request.target_bytes as f64) / (frames * 0.5);
let aspect = if clip.height == 0 {
16.0 / 9.0
} else {
clip.width as f64 / clip.height as f64
};
let w = (budget * aspect).sqrt();
(w.clamp(120.0, clip.width as f64) as u32 / 2) * 2
} else {
// For video formats, scale to a reasonable preview size.
clip.width.min(1280).max(160)
};
let preview_path = temp_dir(&state.app_dir).join("preview.png");
@@ -727,9 +730,98 @@ pub struct ExportResult {
pub size_bytes: u64,
}
const OVERLAY_BORDER_LOGICAL_PX: f64 = 2.0;
const OVERLAY_BORDER_LOGICAL_PX: f64 = 4.0;
const OVERLAY_TITLEBAR_LOGICAL_PX: f64 = 22.0;
fn apply_overlay_region(_win: &tauri::WebviewWindow) -> Result<(), String> {
Ok(())
}
fn start_overlay_clickthrough_poll(app: AppHandle) {
use std::time::Duration;
use windows::Win32::Foundation::{HWND, POINT, RECT};
use windows::Win32::Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_EXTENDED_FRAME_BOUNDS};
use windows::Win32::UI::HiDpi::GetDpiForWindow;
use windows::Win32::UI::WindowsAndMessaging::{GetCursorPos, GetWindowRect};
std::thread::spawn(move || {
let mut last_inner: Option<bool> = None;
loop {
std::thread::sleep(Duration::from_millis(30));
let overlay = match app.get_webview_window("overlay") {
Some(w) => w,
None => continue,
};
if !overlay.is_visible().unwrap_or(false) {
last_inner = None;
continue;
}
// During recording, the overlay should always be click-through.
// start_capture already sets ignore_cursor_events(true). Skip polling
// so we don't fight it.
let state = app.state::<AppState>();
let is_recording = state.capture.lock().expect("capture mutex").is_some();
if is_recording {
last_inner = Some(true);
continue;
}
let mut pt = POINT::default();
if unsafe { GetCursorPos(&mut pt) }.is_err() {
continue;
}
let raw = match overlay.hwnd() {
Ok(h) => h,
Err(_) => continue,
};
let hwnd = HWND(raw.0 as *mut _);
let mut dwm = RECT::default();
let dwm_ok = unsafe {
DwmGetWindowAttribute(
hwnd,
DWMWA_EXTENDED_FRAME_BOUNDS,
&mut dwm as *mut RECT as *mut std::ffi::c_void,
std::mem::size_of::<RECT>() as u32,
)
}
.is_ok()
&& dwm.right > dwm.left;
let visible = if dwm_ok {
dwm
} else {
let mut outer = RECT::default();
if unsafe { GetWindowRect(hwnd, &mut outer) }.is_err() {
continue;
}
outer
};
let dpi = unsafe { GetDpiForWindow(hwnd) };
let scale = if dpi > 0 { dpi as f64 / 96.0 } else { 1.0 };
let border = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
let inner_left = visible.left + border;
let inner_top = visible.top + border + titlebar;
let inner_right = visible.right - border;
let inner_bottom = visible.bottom - border;
let in_inner = pt.x >= inner_left
&& pt.x < inner_right
&& pt.y >= inner_top
&& pt.y < inner_bottom;
if last_inner != Some(in_inner) {
let _ = overlay.set_ignore_cursor_events(in_inner);
last_inner = Some(in_inner);
}
}
});
}
fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(), String> {
use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{
@@ -751,6 +843,7 @@ 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);
win.set_focus().map_err(|e| e.to_string())
}
@@ -774,7 +867,9 @@ fn set_overlay_size(app: AppHandle, width: u32, height: u32) -> Result<(), Strin
let final_h =
height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h)))
.map_err(|e| e.to_string())
.map_err(|e| e.to_string())?;
let _ = apply_overlay_region(&win);
Ok(())
}
#[tauri::command]
@@ -815,7 +910,7 @@ fn open_window_picker(
picker
.set_position(Position::Physical(PhysicalPosition::new(0, 0)))
.map_err(|e| e.to_string())?;
let _ = picker.set_ignore_cursor_events(true);
let _ = picker.set_ignore_cursor_events(false);
let _ = picker.set_always_on_top(true);
picker.show().map_err(|e| e.to_string())?;
if let Ok(h) = picker.hwnd() {
@@ -895,6 +990,34 @@ fn dwm_insets(hwnd_raw: isize) -> (i32, i32, i32, i32) {
)
}
/// Get the DPI scale factor for the monitor containing a given point.
fn scale_factor_at_point(x: i32, y: i32) -> f64 {
use windows::Win32::Foundation::POINT;
use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST};
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, MONITOR_DPI_TYPE};
let pt = POINT { x, y };
let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
if hmonitor.0.is_null() {
return 1.0;
}
let mut dpi_x = 0u32;
let mut dpi_y = 0u32;
let hr = unsafe {
GetDpiForMonitor(
hmonitor,
MONITOR_DPI_TYPE(0), // MdtEffectiveDpi
&mut dpi_x,
&mut dpi_y,
)
};
if hr.is_ok() && dpi_x > 0 {
dpi_x as f64 / 96.0
} else {
1.0
}
}
#[tauri::command]
fn set_overlay_to_window(
app: AppHandle,
@@ -906,7 +1029,11 @@ fn set_overlay_to_window(
let win = app
.get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?;
let scale = win.scale_factor().map_err(|e| e.to_string())?;
// Use the target monitor's scale factor, not the overlay's current one,
// so border/titlebar compensation is correct when snapping across monitors.
let cx = x.saturating_add(width as i32 / 2);
let cy = y.saturating_add(height as i32 / 2);
let scale = scale_factor_at_point(cx, cy);
let border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_LOGICAL_PX * scale).round() as i32;
@@ -951,6 +1078,7 @@ 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(())
}
@@ -1051,7 +1179,7 @@ fn open_url(url: String) -> Result<(), String> {
}
#[tauri::command]
fn export(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 clip = state
.last_clip
@@ -1125,14 +1253,35 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&state.app_dir),
crop: None,
crop: request.crop,
deleted_frame_indices: request.deleted_frame_indices,
trim_start_secs: trim_start,
trim_end_secs: trim_end,
clicks: transformed_clicks,
progress_tx: None,
};
encode::transcode(&ffmpeg, &req).map_err(|e| format!("{e:#}"))?;
let total_passes: u8 = if request.format == crate::config::Format::Gif { 1 } else { 2 };
let (tx, rx) = std::sync::mpsc::channel();
let mut req_with_progress = req;
req_with_progress.progress_tx = Some(tx);
let app_handle = app.clone();
// Spawn a thread to forward encode progress to the frontend.
std::thread::spawn(move || {
while let Ok(progress) = rx.recv() {
let _ = app_handle.emit(
"encode-progress",
encode::EncodeProgress {
pass: progress.pass,
total_passes,
percent: progress.percent,
},
);
}
});
encode::transcode(&ffmpeg, &req_with_progress).map_err(|e| format!("{e:#}"))?;
let size_bytes = std::fs::metadata(&out_path)
.map(|m| m.len())
@@ -1143,12 +1292,6 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
})
}
// Suppress dead-code warnings for codec helper functions used only via config.
#[allow(dead_code)]
fn _codec_keepalive() -> (GifDither, WebmCodec, Mp4Codec) {
(GifDither::None, WebmCodec::Vp9, Mp4Codec::H264)
}
pub fn run() {
tracing_subscriber::fmt::init();
@@ -1237,7 +1380,8 @@ pub fn run() {
let cfg = st.config.lock().expect("config mutex").clone();
(cfg.updates.check_on_launch, cfg)
};
register_hotkeys(app.handle(), &cfg);
let _ = register_hotkeys(app.handle(), &cfg);
start_overlay_clickthrough_poll(app.handle().clone());
if check_on_launch {
let handle = app.handle().clone();
tauri::async_runtime::spawn(async move {