From b7ac517381d7b023c70d10f103003eb402450898 Mon Sep 17 00:00:00 2001 From: lashman Date: Tue, 12 May 2026 01:47:45 +0300 Subject: [PATCH] click highlights via global mouse hook + ffmpeg drawbox --- src-tauri/Cargo.toml | 2 +- src-tauri/src/capture.rs | 11 +++++ src-tauri/src/clicks.rs | 75 ++++++++++++++++++++++++++++++++++ src-tauri/src/encode.rs | 45 +++++++++++++++++++-- src-tauri/src/lib.rs | 87 ++++++++++++++++++++++++++++++++++++++++ src/lib/api.ts | 9 +++++ 6 files changed, 224 insertions(+), 5 deletions(-) create mode 100644 src-tauri/src/clicks.rs diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 137e900..5f62867 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -18,7 +18,7 @@ tauri = { version = "2.11", features = ["protocol-asset"] } tauri-plugin-dialog = "2" tauri-plugin-global-shortcut = "2" windows-capture = "2.0" -windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation"] } +windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_Foundation"] } cpal = "0.16" tokio = { version = "1.47", features = ["full"] } serde = { version = "1.0", features = ["derive"] } diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 04e6792..1239530 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -142,6 +142,17 @@ pub struct CaptureSession { control: CaptureControl, } +pub fn primary_monitor_dims() -> Result<(u32, u32)> { + let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?; + let w = monitor + .width() + .map_err(|e| anyhow!("monitor width: {e:?}"))?; + let h = monitor + .height() + .map_err(|e| anyhow!("monitor height: {e:?}"))?; + Ok((w & !1, h & !1)) +} + pub fn start( output_path: PathBuf, ffmpeg_path: PathBuf, diff --git a/src-tauri/src/clicks.rs b/src-tauri/src/clicks.rs new file mode 100644 index 0000000..a479cb0 --- /dev/null +++ b/src-tauri/src/clicks.rs @@ -0,0 +1,75 @@ +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread::{self, JoinHandle}; +use std::time::{Duration, Instant}; + +use serde::Serialize; + +#[derive(Debug, Clone, Copy, Serialize)] +pub struct Click { + pub time_secs: f64, + pub x: i32, + pub y: i32, +} + +pub struct ClickRecorder { + running: Arc, + thread: Option>, + clicks: Arc>>, +} + +pub fn start() -> ClickRecorder { + let running = Arc::new(AtomicBool::new(true)); + let clicks: Arc>> = Arc::new(Mutex::new(Vec::new())); + let running_clone = running.clone(); + let clicks_clone = clicks.clone(); + + let thread = thread::spawn(move || { + use windows::Win32::Foundation::POINT; + use windows::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState; + use windows::Win32::UI::WindowsAndMessaging::GetCursorPos; + + const VK_LBUTTON: i32 = 0x01; + let start = Instant::now(); + let mut last_pressed = false; + + 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); + } + } + } + last_pressed = pressed; + thread::sleep(Duration::from_millis(5)); + } + }); + + ClickRecorder { + running, + thread: Some(thread), + clicks, + } +} + +impl ClickRecorder { + pub fn stop(mut self) -> Vec { + self.running.store(false, Ordering::Relaxed); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + self.clicks + .lock() + .map(|v| v.clone()) + .unwrap_or_default() + } +} diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index 6cfb5f8..ed88bfe 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -5,6 +5,7 @@ use std::process::Command; use anyhow::{anyhow, bail, Context, Result}; +use crate::clicks::Click; use crate::config::{Format, GifDither, Mp4Codec, WebmCodec}; use crate::CaptureRect; @@ -27,6 +28,30 @@ pub struct TranscodeRequest { pub deleted_frame_indices: Vec, pub trim_start_secs: Option, pub trim_end_secs: Option, + pub clicks: Vec, +} + +fn click_filters(req: &TranscodeRequest) -> Option { + if req.clicks.is_empty() { + return None; + } + let size = 24i32; + let half = size / 2; + let mut parts: Vec = Vec::new(); + for click in &req.clicks { + let x = click.x - half; + let y = click.y - half; + let t1 = (click.time_secs - 0.05).max(0.0); + let t2 = click.time_secs + 0.25; + 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})'" + )); + } + if parts.is_empty() { + None + } else { + Some(parts.join(",")) + } } fn apply_trim(cmd: &mut Command, req: &TranscodeRequest) { @@ -194,6 +219,13 @@ fn two_pass_video( let null_target = if cfg!(windows) { "NUL" } else { "/dev/null" }; let crop = crop_filter(req.crop); + let clicks = click_filters(req); + let combined_vf: Option = match (&crop, &clicks) { + (Some(c), Some(k)) => Some(format!("{c},{k}")), + (Some(c), None) => Some(c.clone()), + (None, Some(k)) => Some(k.clone()), + (None, None) => None, + }; let mut pass1 = Command::new(ffmpeg); pass1 @@ -202,7 +234,7 @@ fn two_pass_video( .arg("-i") .arg(&req.input); apply_trim(&mut pass1, req); - if let Some(c) = &crop { + if let Some(c) = &combined_vf { pass1.args(["-vf", c]); } pass1 @@ -222,7 +254,7 @@ fn two_pass_video( .arg("-i") .arg(&req.input); apply_trim(&mut pass2, req); - if let Some(c) = &crop { + if let Some(c) = &combined_vf { pass2.args(["-vf", c]); } pass2 @@ -271,12 +303,16 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { let crop_prefix = crop_filter(req.crop) .map(|c| format!("{c},")) .unwrap_or_default(); + let click_prefix = click_filters(req) + .map(|c| format!("{c},")) + .unwrap_or_default(); let select_prefix = select_filter_for_deleted(&req.deleted_frame_indices) .map(|s| format!("{s},")) .unwrap_or_default(); let palettegen_filter = format!( - "{cprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff", + "{cprefix}{kprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos,palettegen=stats_mode=diff", cprefix = crop_prefix, + kprefix = click_prefix, sprefix = select_prefix, fps = req.fps, w = scale_width, @@ -298,8 +334,9 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { GifDither::None => "none", }; let use_filter = format!( - "{cprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}", + "{cprefix}{kprefix}fps={fps},{sprefix}scale={w}:-1:flags=lanczos[x];[x][1:v]paletteuse=dither={d}", cprefix = crop_prefix, + kprefix = click_prefix, sprefix = select_prefix, fps = req.fps, w = scale_width, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 36596dc..91db9a0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,6 +1,7 @@ mod audio; mod bootstrap; mod capture; +mod clicks; mod config; mod encode; mod updates; @@ -31,6 +32,7 @@ pub struct AppState { pub config: Mutex, pub capture: Mutex>, pub audio: Mutex>, + pub click_recorder: Mutex>, pub last_clip: Mutex>, pub session: Mutex>, } @@ -46,6 +48,10 @@ pub struct SessionState { pub crop: Option, pub width: u32, pub height: u32, + pub monitor_width: u32, + pub monitor_height: u32, + pub clicks: Vec, + pub segment_start_offsets: Vec, } #[derive(Debug, Clone, Serialize)] @@ -54,7 +60,10 @@ pub struct RecordedClip { pub duration_secs: f64, pub width: u32, pub height: u32, + pub monitor_width: u32, + pub monitor_height: u32, pub crop: Option, + pub clicks: Vec, } fn exe_dir() -> Result { @@ -293,6 +302,9 @@ 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 session = capture::start( output, ffmpeg.clone(), @@ -334,11 +346,22 @@ fn start_capture( crop, width: session.width, height: session.height, + monitor_width: monitor_w, + monitor_height: monitor_h, + clicks: Vec::new(), + segment_start_offsets: vec![0.0], + }; + + let click_rec = if cfg.capture.capture_cursor { + Some(clicks::start()) + } else { + None }; *state.session.lock().expect("session mutex") = Some(session_state); *state.capture.lock().expect("capture mutex") = Some(session); *state.audio.lock().expect("audio mutex") = audio_session; + *state.click_recorder.lock().expect("click mutex") = click_rec; Ok(()) } @@ -360,15 +383,31 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> { .take() .and_then(|a| a.stop().ok()); + let new_clicks: Vec = state + .click_recorder + .lock() + .expect("click mutex") + .take() + .map(|r| r.stop()) + .unwrap_or_default(); + let mut ss = state.session.lock().expect("session mutex"); let ss = ss .as_mut() .ok_or_else(|| "no session state".to_string())?; + let offset = *ss.segment_start_offsets.last().unwrap_or(&0.0); + for c in new_clicks { + ss.clicks.push(clicks::Click { + time_secs: offset + c.time_secs, + ..c + }); + } ss.segments.push(path); if let Some(ap) = audio_path { ss.audio_segments.push(ap); } ss.total_recorded_secs += elapsed; + ss.segment_start_offsets.push(ss.total_recorded_secs); Ok(()) } @@ -415,8 +454,15 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> { None }; + let click_rec = if capture_cursor { + Some(clicks::start()) + } else { + None + }; + *state.capture.lock().expect("capture mutex") = Some(session); *state.audio.lock().expect("audio mutex") = audio_session; + *state.click_recorder.lock().expect("click mutex") = click_rec; Ok(()) } @@ -446,6 +492,21 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result) -> Result, request: ExportRequest) -> Result clip.duration_secs, }; + let (src_w, src_origin) = if let Some(c) = clip.crop { + (c.width, (c.x, c.y)) + } else { + ( + clip + .monitor_width + .max(1), + (0, 0), + ) + }; + let scale = clip.width as f64 / src_w as f64; + let transformed_clicks: Vec = clip + .clicks + .iter() + .map(|c| clicks::Click { + time_secs: c.time_secs, + x: (((c.x - src_origin.0) as f64) * scale).round() as i32, + y: (((c.y - src_origin.1) as f64) * scale).round() as i32, + }) + .collect(); + let req = encode::TranscodeRequest { input: clip.temp_path.clone(), output: out_path.clone(), @@ -747,6 +832,7 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result