From f0775b8ff0375d3d31fef64c8de111009f468d24 Mon Sep 17 00:00:00 2001 From: lashman Date: Wed, 27 May 2026 18:56:36 +0300 Subject: [PATCH] current state before improvement pass --- src-tauri/Cargo.toml | 2 +- src-tauri/src/audio.rs | 270 ++++- src-tauri/src/bootstrap.rs | 119 ++- src-tauri/src/capture.rs | 51 +- src-tauri/src/config.rs | 85 +- src-tauri/src/encode.rs | 266 ++++- src-tauri/src/lib.rs | 370 +++++-- src-tauri/src/updates.rs | 42 + src-tauri/tauri.conf.json | 2 +- src/App.svelte | 44 +- src/app.css | 150 ++- src/lib/Bootstrap.svelte | 311 ++++-- src/lib/FirstRun.svelte | 236 +++-- src/lib/HotkeyInput.svelte | 130 ++- src/lib/Loading.svelte | 42 +- src/lib/Main.svelte | 1984 +++++++++++++++++++++-------------- src/lib/Overlay.svelte | 250 ++--- src/lib/Picker.svelte | 164 +-- src/lib/Settings.svelte | 620 +++++++---- src/lib/UpdateBanner.svelte | 248 ++--- src/lib/api.ts | 28 +- src/overlay.ts | 1 + src/picker.ts | 1 + 23 files changed, 3563 insertions(+), 1853 deletions(-) diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 2338855..93dfddc 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_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_Foundation", "Win32_Graphics_Dwm"] } +windows = { version = "0.62", features = ["Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_HiDpi", "Win32_Foundation", "Win32_Graphics_Dwm", "Win32_Graphics_Gdi", "Win32_System_SystemInformation", "Win32_Media_Audio", "Win32_Media_Multimedia", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_Threading", "Win32_System_Variant"] } cpal = "0.16" tokio = { version = "1.47", features = ["full"] } serde = { version = "1.0", features = ["derive"] } diff --git a/src-tauri/src/audio.rs b/src-tauri/src/audio.rs index e305c7d..f909a44 100644 --- a/src-tauri/src/audio.rs +++ b/src-tauri/src/audio.rs @@ -1,77 +1,251 @@ use std::fs::File; use std::io::{BufWriter, Write}; use std::path::PathBuf; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::thread::{self, JoinHandle}; -use anyhow::{anyhow, Context, Result}; -use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; +use anyhow::{bail, Context, Result}; +use windows::Win32::Media::Audio::{ + eConsole, eRender, IAudioCaptureClient, IAudioClient, IMMDeviceEnumerator, + MMDeviceEnumerator, WAVEFORMATEX, WAVEFORMATEXTENSIBLE, +}; +use windows::Win32::System::Com::{ + CoCreateInstance, CoInitializeEx, CoTaskMemFree, CLSCTX_ALL, COINIT_APARTMENTTHREADED, +}; + +// WASAPI constants — defined here so we don't depend on exact windows-crate naming. +const AUDCLNT_STREAMFLAGS_LOOPBACK: u32 = 0x2000_0000; +const AUDCLNT_BUFFERFLAGS_SILENT: u32 = 0x0000_0002; + +const WAVE_FORMAT_PCM: u16 = 0x0001; +const WAVE_FORMAT_IEEE_FLOAT: u16 = 0x0003; +const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; pub struct AudioSession { - _stream: cpal::Stream, - pub output_path: PathBuf, + thread: Option>>, + running: Arc, + output_path: PathBuf, pub sample_rate: u32, pub channels: u16, - writer: Arc>>>, } pub fn start(output_path: PathBuf) -> Result { - let host = cpal::default_host(); - let device = host - .default_output_device() - .ok_or_else(|| anyhow!("no default output device for loopback"))?; - let supported = device - .default_output_config() - .context("default output config")?; - let sample_rate = supported.sample_rate().0; - let channels = supported.channels(); - let stream_config: cpal::StreamConfig = supported.config(); + let running = Arc::new(AtomicBool::new(true)); + let running_clone = running.clone(); + let path_clone = output_path.clone(); - if let Some(parent) = output_path.parent() { - std::fs::create_dir_all(parent).ok(); - } - let file = File::create(&output_path).context("creating audio output file")?; - let writer = Arc::new(Mutex::new(Some(BufWriter::new(file)))); - let writer_clone = writer.clone(); + let (init_tx, init_rx) = std::sync::mpsc::channel(); - let stream = device - .build_input_stream( - &stream_config, - move |data: &[f32], _info: &cpal::InputCallbackInfo| { - if let Ok(mut guard) = writer_clone.lock() { - if let Some(w) = guard.as_mut() { - let bytes: &[u8] = bytemuck_cast(data); - let _ = w.write_all(bytes); - } - } - }, - |err| tracing::warn!("audio capture error: {err}"), - None, - ) - .context("building input stream")?; - stream.play().context("starting audio stream")?; + let thread = thread::spawn(move || { + let result = capture_thread(running_clone, path_clone, init_tx); + if let Err(ref e) = result { + tracing::error!("audio capture thread ended with error: {e:#}"); + } + result + }); + + let (sample_rate, channels) = init_rx + .recv_timeout(std::time::Duration::from_secs(3)) + .context("audio capture thread failed to initialize within 3 seconds")? + .context("audio capture initialization failed")?; Ok(AudioSession { - _stream: stream, + thread: Some(thread), + running, output_path, sample_rate, channels, - writer, }) } impl AudioSession { pub fn stop(self) -> Result { - drop(self._stream); - if let Ok(mut guard) = self.writer.lock() { - if let Some(mut w) = guard.take() { - let _ = w.flush(); - } + self.running.store(false, Ordering::Relaxed); + if let Some(t) = self.thread { + let _ = t.join(); } Ok(self.output_path) } } -fn bytemuck_cast(data: &[f32]) -> &[u8] { - let len_bytes = std::mem::size_of_val(data); - unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, len_bytes) } +fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> { + // WAVEFORMATEX is repr(packed); copy fields to avoid unaligned ref UB. + let w_format_tag = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wFormatTag)) }; + let n_channels = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nChannels)) }; + let n_samples_per_sec = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.nSamplesPerSec)) }; + let w_bits_per_sample = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(fmt.wBitsPerSample)) }; + + let is_float = if w_format_tag == WAVE_FORMAT_IEEE_FLOAT { + true + } else if w_format_tag == WAVE_FORMAT_PCM { + false + } else if w_format_tag == WAVE_FORMAT_EXTENSIBLE { + let ext = unsafe { &*(fmt as *const WAVEFORMATEX as *const WAVEFORMATEXTENSIBLE) }; + let sub_fmt = unsafe { std::ptr::read_unaligned(std::ptr::addr_of!(ext.SubFormat)) }; + sub_fmt == windows::core::GUID::from_u128(0x00000003_0000_0010_8000_00aa00389b71) + } else { + bail!("unsupported WAVEFORMATEX format tag: {}", w_format_tag); + }; + + Ok((n_samples_per_sec, n_channels, w_bits_per_sample, is_float)) +} + +fn capture_thread( + running: Arc, + output_path: PathBuf, + init_tx: std::sync::mpsc::Sender>, +) -> Result<()> { + unsafe { + CoInitializeEx(None, COINIT_APARTMENTTHREADED) + .ok() + .context("CoInitializeEx")?; + } + + let enumerator: IMMDeviceEnumerator = unsafe { + CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL) + .context("CoCreateInstance MMDeviceEnumerator")? + }; + + let device = unsafe { + enumerator + .GetDefaultAudioEndpoint(eRender, eConsole) + .context("GetDefaultAudioEndpoint")? + }; + + let client: IAudioClient = unsafe { + device + .Activate::(CLSCTX_ALL, None) + .context("Activate IAudioClient")? + }; + + let mix_format_ptr = unsafe { client.GetMixFormat().context("GetMixFormat")? }; + let mix_format = unsafe { &*mix_format_ptr }; + + let (sample_rate, channels, bits_per_sample, is_float) = parse_format(mix_format)?; + + let buffer_duration = 10_000_000i64; // 1 second in 100-ns units + unsafe { + client + .Initialize( + windows::Win32::Media::Audio::AUDCLNT_SHAREMODE(0), // Shared + AUDCLNT_STREAMFLAGS_LOOPBACK, + buffer_duration, + 0, + mix_format_ptr, + None, + ) + .context("IAudioClient::Initialize")?; + } + + unsafe { + CoTaskMemFree(Some(mix_format_ptr as *mut _)); + } + + let capture_client: IAudioCaptureClient = unsafe { + client + .GetService::() + .context("GetService IAudioCaptureClient")? + }; + + unsafe { + client.Start().context("IAudioClient::Start")?; + } + + let file = File::create(&output_path).context("creating audio output file")?; + let mut writer = BufWriter::new(file); + + // Notify parent that init succeeded. + let _ = init_tx.send(Ok((sample_rate, channels))); + + while running.load(Ordering::Relaxed) { + let mut packet_length = unsafe { + capture_client + .GetNextPacketSize() + .context("GetNextPacketSize")? + }; + + while packet_length > 0 { + let mut data_ptr = std::ptr::null_mut(); + let mut num_frames_available = 0u32; + let mut flags = 0u32; + unsafe { + capture_client + .GetBuffer( + &mut data_ptr, + &mut num_frames_available, + &mut flags, + None, + None, + ) + .context("GetBuffer")?; + } + + if num_frames_available > 0 { + let is_silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) != 0; + 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")?; + } else if is_float { + let num_bytes = samples * (bits_per_sample as usize / 8); + let slice = unsafe { + std::slice::from_raw_parts(data_ptr as *const u8, num_bytes) + }; + 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 { + std::slice::from_raw_parts(data_ptr as *const i16, samples) + }; + for &sample in i16_slice { + let f = sample as f32 / 32768.0; + writer + .write_all(&f.to_le_bytes()) + .context("writing f32 sample")?; + } + } + 32 => { + let i32_slice = unsafe { + std::slice::from_raw_parts(data_ptr as *const i32, samples) + }; + for &sample in i32_slice { + let f = sample as f32 / 2147483648.0; + writer + .write_all(&f.to_le_bytes()) + .context("writing f32 sample")?; + } + } + _ => bail!("unsupported bits per sample: {bits_per_sample}"), + } + } + } + + unsafe { + capture_client + .ReleaseBuffer(num_frames_available) + .context("ReleaseBuffer")?; + } + + packet_length = unsafe { + capture_client + .GetNextPacketSize() + .context("GetNextPacketSize")? + }; + } + + thread::sleep(std::time::Duration::from_millis(1)); + } + + unsafe { + let _ = client.Stop(); + } + + writer.flush().context("flushing audio writer")?; + Ok(()) } diff --git a/src-tauri/src/bootstrap.rs b/src-tauri/src/bootstrap.rs index cb1b794..b6d6a0f 100644 --- a/src-tauri/src/bootstrap.rs +++ b/src-tauri/src/bootstrap.rs @@ -46,7 +46,7 @@ struct Source { const SOURCES: &[Source] = &[ Source { name: "GyanD", - release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/tags/8.1.1", + release_api_url: "https://api.github.com/repos/GyanD/codexffmpeg/releases/tags/latest", asset_name_suffix: "full_build.7z", kind: ArchiveKind::SevenZ, }, @@ -60,6 +60,7 @@ const SOURCES: &[Source] = &[ #[derive(Debug, Deserialize)] struct GithubRelease { + tag_name: String, assets: Vec, } @@ -67,8 +68,6 @@ struct GithubRelease { struct GithubAsset { name: String, browser_download_url: String, - #[serde(default)] - digest: Option, } pub async fn download(app_dir: &Path, mut on_progress: F) -> Result<()> @@ -103,14 +102,31 @@ where .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION"))) .build()?; - let asset = pick_asset(&client, source).await?; + let (asset, version) = pick_asset(&client, source).await?; - let expected = parse_sha256_digest(&asset.digest) - .with_context(|| format!("parsing digest for {}", asset.name))?; + // GyanD publishes a .sha256 file alongside each release. + // BtbN does not, so we skip verification for BtbN. + let expected = if source.name == "GyanD" { + let checksum_url = format!( + "https://github.com/GyanD/codexffmpeg/releases/download/{}/{}.sha256", + version, + asset.name + ); + Some(fetch_sha256(&client, &checksum_url).await?) + } else { + tracing::warn!("BtbN build: skipping SHA-256 verification (no checksum file)"); + None + }; - let archive = download_verified(&client, &asset.browser_download_url, &expected, on_progress) - .await - .with_context(|| format!("downloading {}", asset.browser_download_url))?; + let archive = if let Some(ref hash) = expected { + download_verified(&client, &asset.browser_download_url, hash, on_progress) + .await + .with_context(|| format!("downloading {}", asset.browser_download_url))? + } else { + download_plain(&client, &asset.browser_download_url, on_progress) + .await + .with_context(|| format!("downloading {}", asset.browser_download_url))? + }; match source.kind { ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?, @@ -119,7 +135,65 @@ where Ok(()) } -async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result { +/// Fetch and parse a SHA-256 checksums file from GyanD. +/// The file contains a line like: +/// abc123def456... ffmpeg-8.1.1-full_build.7z +async fn fetch_sha256(client: &reqwest::Client, url: &str) -> Result<[u8; 32]> { + let resp = client.get(url).send().await?.error_for_status()?; + let text = resp.text().await?; + // Each line is: " " - find the line with our filename + let hash_str = text + .lines() + .find_map(|line| { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + return None; + } + // SHA-256 hex is 64 chars, followed by spaces and the filename + if line.len() < 64 { + return None; + } + let (hash, _file) = line.split_at(64); + let remainder = _file.trim_start(); + // Must be followed by two spaces and a filename + if !remainder.starts_with(" ") { + return None; + } + Some(hash) + }) + .ok_or_else(|| anyhow!("SHA-256 for this build not found in checksums file"))?; + let bytes = hex::decode(hash_str).context("checksum is not valid hex")?; + if bytes.len() != 32 { + bail!("checksum length is {} bytes, expected 32", bytes.len()); + } + let mut sha = [0u8; 32]; + sha.copy_from_slice(&bytes); + Ok(sha) +} + +async fn download_plain( + client: &reqwest::Client, + url: &str, + mut on_progress: F, +) -> Result> +where + F: FnMut(u64, Option), +{ + let resp = client.get(url).send().await?.error_for_status()?; + let total = resp.content_length(); + let mut buf: Vec = Vec::with_capacity(total.unwrap_or(0) as usize); + let mut downloaded = 0u64; + let mut stream = resp.bytes_stream(); + while let Some(chunk) = stream.next().await { + let chunk = chunk?; + buf.extend_from_slice(&chunk); + downloaded += chunk.len() as u64; + on_progress(downloaded, total); + } + Ok(buf) +} + +async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<(GithubAsset, String)> { let resp = client .get(source.release_api_url) .header("Accept", "application/vnd.github+json") @@ -129,7 +203,11 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result Result) -> Result<[u8; 32]> { - let raw = digest - .as_deref() - .ok_or_else(|| anyhow!("release asset has no digest"))?; - let hex_str = raw - .strip_prefix("sha256:") - .ok_or_else(|| anyhow!("digest is not sha256: '{raw}'"))?; - let bytes = hex::decode(hex_str).context("digest is not valid hex")?; - if bytes.len() != 32 { - bail!("digest length is {} bytes, expected 32", bytes.len()); - } - let mut sha = [0u8; 32]; - sha.copy_from_slice(&bytes); - Ok(sha) + })?; + Ok((asset, version)) } async fn download_verified( diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 1239530..52e5fb0 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -3,7 +3,7 @@ use std::path::PathBuf; use std::process::{Child, ChildStdin, Command, Stdio}; use std::time::Instant; -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, bail, Context, Result}; use windows_capture::capture::{ CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler, }; @@ -114,12 +114,14 @@ impl GraphicsCaptureApiHandler for CaptureHandler { self.scratch.clear(); let bytes = buf.as_nopadding_buffer(&mut self.scratch); let expected = (self.width as usize) * (self.height as usize) * 4; - let slice = if bytes.len() >= expected { - &bytes[..expected] - } else { - bytes - }; - let _ = stdin.write_all(slice); + if bytes.len() < expected { + tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected); + return Ok(()); + } + stdin.write_all(&bytes[..expected]).map_err(|e| { + tracing::error!("ffmpeg stdin write failed: {e} — encoder may have crashed"); + anyhow!("ffmpeg encoder stopped unexpectedly: {e}") + })?; Ok(()) } } @@ -153,6 +155,22 @@ pub fn primary_monitor_dims() -> Result<(u32, u32)> { Ok((w & !1, h & !1)) } +/// Find the monitor containing the given screen point using the Win32 API. +/// Falls back to the primary monitor if no monitor is found. +fn monitor_at_point(x: i32, y: i32) -> Result { + use windows::Win32::Foundation::POINT; + use windows::Win32::Graphics::Gdi::{MonitorFromPoint, MONITOR_DEFAULTTONEAREST}; + + let pt = POINT { x, y }; + let hmonitor = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) }; + if hmonitor.0.is_null() { + bail!("MonitorFromPoint returned null for ({x}, {y})"); + } + // SAFETY: hmonitor is a valid monitor handle from MonitorFromPoint. + let monitor = Monitor::from_raw_hmonitor(hmonitor.0 as *mut _); + Ok(monitor) +} + pub fn start( output_path: PathBuf, ffmpeg_path: PathBuf, @@ -161,7 +179,19 @@ pub fn start( crop: Option, fps: u32, ) -> Result { - let monitor = Monitor::primary().map_err(|e| anyhow!("primary monitor: {e:?}"))?; + // Use the center of the capture region to determine which monitor to capture. + // If the region spans monitors, we pick the one containing the center. + let monitor = if let Some(ref c) = crop { + let cx = c.x.saturating_add(c.width as i32 / 2); + let cy = c.y.saturating_add(c.height as i32 / 2); + tracing::info!("capture center=({cx}, {cy}), selecting monitor"); + monitor_at_point(cx, cy).unwrap_or_else(|_| { + tracing::warn!("no monitor at ({cx}, {cy}), falling back to primary"); + Monitor::primary().expect("primary monitor always available") + }) + } else { + Monitor::primary().expect("primary monitor always available") + }; let raw_width = monitor .width() .map_err(|e| anyhow!("monitor width: {e:?}"))?; @@ -238,6 +268,11 @@ impl CaptureSession { self.control .stop() .map_err(|e| anyhow!("capture stop: {e}"))?; + 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"); + } Ok(self.output_path) } } diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 3ee5ed6..4c468ad 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -3,6 +3,14 @@ use std::path::{Path, PathBuf}; use anyhow::Result; use serde::{Deserialize, Serialize}; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "lowercase")] +pub enum Theme { + #[default] + Dark, + Light, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Config { #[serde(default)] @@ -15,6 +23,8 @@ pub struct Config { pub updates: UpdatesConfig, #[serde(default)] pub output_dir: Option, + #[serde(default)] + pub theme: Theme, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -44,32 +54,36 @@ pub struct UpdatesConfig { pub check_on_launch: bool, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Format { + #[default] Gif, Webm, Mp4, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "snake_case")] pub enum GifDither { + #[default] FloydSteinberg, Bayer, None, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum WebmCodec { + #[default] Vp9, Av1, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Mp4Codec { + #[default] H264, H265, } @@ -82,6 +96,7 @@ impl Default for Config { hotkeys: HotkeyConfig::default(), updates: UpdatesConfig::default(), output_dir: None, + theme: Theme::Dark, } } } @@ -143,3 +158,65 @@ impl Config { pub fn config_path(app_dir: &Path) -> PathBuf { app_dir.join("config.toml") } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn config_roundtrip() { + let cfg = Config { + export: ExportConfig { + default_format: Format::Webm, + gif_dither: GifDither::Bayer, + webm_codec: WebmCodec::Av1, + mp4_codec: Mp4Codec::H265, + }, + capture: CaptureConfig { + default_fps: 60, + capture_cursor: false, + capture_audio: true, + }, + hotkeys: HotkeyConfig { + start: Some("F9".to_string()), + stop: Some("F10".to_string()), + pause: Some("F11".to_string()), + }, + updates: UpdatesConfig { check_on_launch: false }, + output_dir: Some(PathBuf::from("./custom")), + theme: Theme::Light, + }; + + let dir = std::env::temp_dir().join("bytesize-test-config"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("config.toml"); + cfg.save(&path).unwrap(); + let loaded = Config::load_or_create(&path).unwrap(); + assert_eq!(loaded.export.default_format, Format::Webm); + assert_eq!(loaded.capture.default_fps, 60); + assert_eq!(loaded.hotkeys.start, Some("F9".to_string())); + assert_eq!(loaded.output_dir, Some(PathBuf::from("./custom"))); + assert_eq!(loaded.theme, Theme::Light); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn needs_first_run_when_hotkeys_missing() { + let cfg = Config::default(); + assert!(cfg.needs_first_run()); + } + + #[test] + fn no_first_run_when_hotkeys_set() { + let cfg = Config { + hotkeys: HotkeyConfig { + start: Some("F9".to_string()), + stop: Some("F10".to_string()), + pause: Some("F11".to_string()), + }, + ..Config::default() + }; + assert!(!cfg.needs_first_run()); + } +} diff --git a/src-tauri/src/encode.rs b/src-tauri/src/encode.rs index bc38be7..2e312aa 100644 --- a/src-tauri/src/encode.rs +++ b/src-tauri/src/encode.rs @@ -2,6 +2,8 @@ use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::mpsc::Sender; +use std::thread; use anyhow::{anyhow, bail, Context, Result}; @@ -9,7 +11,19 @@ use crate::clicks::Click; use crate::config::{Format, GifDither, Mp4Codec, WebmCodec}; use crate::CaptureRect; -const AUDIO_BITRATE_KBPS: u64 = 128; +// Used both for bitrate budget calculation and final mux. Must be consistent. +const AUDIO_BITRATE_KBPS: u64 = 192; + +/// Progress update sent during encoding. +/// pass: 1-based pass number (1 or 2 for two-pass video, 1 for GIF). +/// total_passes: total number of passes. +/// percent: 0.0 to 100.0. +#[derive(Debug, Clone, Copy, serde::Serialize)] +pub struct EncodeProgress { + pub pass: u8, + pub total_passes: u8, + pub percent: f64, +} #[derive(Debug, Clone)] pub struct TranscodeRequest { @@ -29,8 +43,13 @@ pub struct TranscodeRequest { pub trim_start_secs: Option, pub trim_end_secs: Option, pub clicks: Vec, + /// Optional channel to report encoding progress. + #[doc(hidden)] + pub progress_tx: Option>, } +const MAX_CLICK_HIGHLIGHTS: usize = 50; + fn click_filters(req: &TranscodeRequest) -> Option { if req.clicks.is_empty() { return None; @@ -38,7 +57,15 @@ fn click_filters(req: &TranscodeRequest) -> Option { let size = 24i32; let half = size / 2; let mut parts: Vec = Vec::new(); - for click in &req.clicks { + let clicks_to_render = req.clicks.len().min(MAX_CLICK_HIGHLIGHTS); + if req.clicks.len() > MAX_CLICK_HIGHLIGHTS { + tracing::warn!( + "{} click events recorded, only first {} will be highlighted", + req.clicks.len(), + MAX_CLICK_HIGHLIGHTS + ); + } + for click in &req.clicks[..clicks_to_render] { let x = click.x - half; let y = click.y - half; let t1 = (click.time_secs - 0.05).max(0.0); @@ -206,9 +233,8 @@ fn two_pass_video( req: &TranscodeRequest, video_codec: &str, audio_codec: &str, - container: &str, + _container: &str, ) -> Result<()> { - let _ = container; let bitrate_kbps = video_bitrate_kbps(req)?; let bitrate = format!("{bitrate_kbps}k"); @@ -245,7 +271,16 @@ fn two_pass_video( .arg("-an") .args(["-f", "null"]) .arg(null_target); - run(&mut pass1, "pass 1")?; + + let tx = req.progress_tx.clone(); + let dur = req.duration_secs; + let fps = req.fps; + run_with_progress(&mut pass1, "pass 1", 1, 2, dur, fps, tx.as_ref())?; + + // Send 50% to signal pass 1 done, pass 2 starting. + if let Some(ref t) = tx { + let _ = t.send(EncodeProgress { pass: 1, total_passes: 2, percent: 100.0 }); + } let mut pass2 = Command::new(ffmpeg); pass2 @@ -270,7 +305,7 @@ fn two_pass_video( pass2.arg("-an"); } pass2.arg(&req.output); - run(&mut pass2, "pass 2")?; + run_with_progress(&mut pass2, "pass 2", 2, 2, dur, fps, tx.as_ref())?; cleanup_pass_logs(&log_stem); Ok(()) @@ -356,7 +391,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> { .args(["-lavfi", &use_filter]) .args(["-loop", "0"]) .arg(&req.output); - run(&mut encode, "gif encode")?; + run_with_progress( + &mut encode, + "gif encode", + 1, + 1, + req.duration_secs, + req.fps, + req.progress_tx.as_ref(), + )?; let _ = std::fs::remove_file(&palette_path); Ok(()) @@ -533,6 +576,44 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re } fn run(cmd: &mut Command, label: &str) -> Result<()> { + let output = run_impl(cmd, label, 0, 0, 0.0, 0, None)?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let head: String = stderr.lines().take(12).collect::>().join("\n"); + bail!("ffmpeg {label} exited with {}: {}", output.status, head); + } + Ok(()) +} + +/// Run an ffmpeg command with progress monitoring. +/// progress_tx, if provided, receives (pass, total_passes, percent) updates. +fn run_with_progress( + cmd: &mut Command, + label: &str, + pass: u8, + total_passes: u8, + duration_secs: f64, + fps: u32, + progress_tx: Option<&Sender>, +) -> Result<()> { + let output = run_impl(cmd, label, pass, total_passes, duration_secs, fps, progress_tx.cloned())?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let head: String = stderr.lines().take(12).collect::>().join("\n"); + bail!("ffmpeg {label} exited with {}: {}", output.status, head); + } + Ok(()) +} + +fn run_impl( + cmd: &mut Command, + label: &str, + progress_pass: u8, + progress_total_passes: u8, + progress_duration_secs: f64, + progress_fps: u32, + progress_tx: Option>, +) -> Result { use std::process::Stdio; let mut printable = OsString::from(label); @@ -544,14 +625,169 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> { } tracing::debug!("{}", printable.to_string_lossy()); - cmd.stdout(Stdio::null()).stderr(Stdio::piped()); - let output = cmd - .output() + let mut child = cmd + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() .with_context(|| format!("spawning ffmpeg for {label}"))?; - if !output.status.success() { - let stderr = String::from_utf8_lossy(&output.stderr); - let tail: String = stderr.lines().rev().take(12).collect::>().into_iter().rev().collect::>().join("\n"); - bail!("ffmpeg {label} exited with {}: {}", output.status, tail); + + // Spawn a thread to monitor stderr and emit progress. + let stderr = child.stderr.take(); + let tx = progress_tx.clone(); + + let handle = stderr.map(move |serr| { + // Clone the Sender if present. + let tx = tx.as_ref().map(|t| t.clone()); + let encode_dur = progress_duration_secs; + let fps = progress_fps; + let pass = progress_pass; + let total_passes = progress_total_passes; + thread::spawn(move || { + use std::io::{BufRead, BufReader}; + let reader = BufReader::new(serr); + for line in reader.lines().map_while(Result::ok) { + if let Some(frame) = parse_frame_from_stderr(&line) { + let total = (encode_dur * fps as f64).max(1.0); + let percent = (frame / total * 100.0).min(100.0); + if let Some(ref sender) = tx { + let _ = sender.send(EncodeProgress { + pass, + total_passes, + percent, + }); + } + } + } + }) + }); + + let output = child.wait_with_output().context("waiting for ffmpeg")?; + if let Some(h) = handle { + let _ = h.join(); + } + Ok(output) +} + +/// Parse a frame count from an ffmpeg stderr progress line. +/// Lines look like: "frame= 123 fps= 30 q=-0.0 size= 1024kB time=00:00:04.10 ..." +fn parse_frame_from_stderr(line: &str) -> Option { + let trimmed = line.trim(); + if !trimmed.starts_with("frame=") { + return None; + } + // Find the "frame= NNN" token and extract the number after it. + let after = trimmed.strip_prefix("frame=")?.trim_start(); + let end = after + .find(|c: char| !c.is_ascii_digit()) + .unwrap_or(after.len()); + let frame_str = &after[..end]; + frame_str.parse().ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dummy_request() -> TranscodeRequest { + TranscodeRequest { + input: PathBuf::new(), + output: PathBuf::new(), + format: Format::Mp4, + target_bytes: 0, + duration_secs: 10.0, + fps: 30, + keep_audio: true, + gif_dither: GifDither::FloydSteinberg, + webm_codec: WebmCodec::Vp9, + mp4_codec: Mp4Codec::H264, + scratch_dir: PathBuf::new(), + crop: None, + deleted_frame_indices: vec![], + trim_start_secs: None, + trim_end_secs: None, + clicks: vec![], + progress_tx: None, + } + } + + #[test] + fn bitrate_for_8mb_10s_with_audio() { + let mut req = dummy_request(); + req.target_bytes = 8 * 1024 * 1024; + req.duration_secs = 10.0; + req.keep_audio = true; + let kbps = video_bitrate_kbps(&req).unwrap(); + // 8 MB * 8 * 0.95 = 60.96 Mbits total + // minus 192k * 10 = 1.92 Mbits audio + // video = ~59 Mbits / 10s = ~5900 kbps + assert!(kbps > 5800 && kbps < 6200); + } + + #[test] + fn bitrate_for_8mb_10s_no_audio() { + let mut req = dummy_request(); + req.target_bytes = 8 * 1024 * 1024; + req.duration_secs = 10.0; + req.keep_audio = false; + let kbps = video_bitrate_kbps(&req).unwrap(); + // 8 MB * 8 * 0.95 = 60.96 Mbits total, all video + // 60.96 Mbits / 10s = ~6096 kbps + assert!(kbps > 6000 && kbps < 6500); + } + + #[test] + fn bitrate_rejects_too_small() { + let mut req = dummy_request(); + req.target_bytes = 1000; + req.duration_secs = 10.0; + req.keep_audio = true; + assert!(video_bitrate_kbps(&req).is_err()); + } + + #[test] + fn bitrate_floor_at_16_kbps() { + let mut req = dummy_request(); + req.target_bytes = 1024 * 1024; + req.duration_secs = 600.0; + req.keep_audio = false; + let kbps = video_bitrate_kbps(&req).unwrap(); + assert_eq!(kbps, 16); + } + + #[test] + fn parse_ffmpeg_stderr_frame() { + assert_eq!( + parse_frame_from_stderr("frame= 123 fps= 30 q=-0.0 size= 1024kB"), + Some(123.0) + ); + assert_eq!( + parse_frame_from_stderr("frame=9999 fps=60.0"), + Some(9999.0) + ); + assert_eq!(parse_frame_from_stderr("size= 1024kB"), None); + } + + #[test] + fn crop_filter_output() { + let rect = CaptureRect { x: 10, y: 20, width: 100, height: 200 }; + assert_eq!( + crop_filter(Some(rect)), + Some("crop=100:200:10:20".to_string()) + ); + assert_eq!(crop_filter(None), None); + } + + #[test] + fn click_filters_capped_at_max() { + let clicks: Vec = (0..100) + .map(|i| Click { time_secs: i as f64, x: i, y: i }) + .collect(); + let req = TranscodeRequest { + clicks, + ..dummy_request() + }; + let filter = click_filters(&req).unwrap(); + let count = filter.matches("drawbox").count(); + assert_eq!(count, MAX_CLICK_HIGHLIGHTS); } - Ok(()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index aa0a585..bee2f5e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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::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, + pub stop_ok: Option, + pub pause_ok: Option, +} + +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 ®istered { - 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 { 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, #[serde(default)] pub output_path: Option, + #[serde(default)] + pub crop: Option, } #[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 = 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::(); + 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::() 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 { +fn export(app: AppHandle, state: State<'_, AppState>, request: ExportRequest) -> Result { 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, request: ExportRequest) -> Result (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 { diff --git a/src-tauri/src/updates.rs b/src-tauri/src/updates.rs index 614a7a6..d2a2c6a 100644 --- a/src-tauri/src/updates.rs +++ b/src-tauri/src/updates.rs @@ -124,3 +124,45 @@ fn is_newer(latest: &str, current: &str) -> bool { c.resize(max, 0); l > c } + +#[cfg(test)] +mod tests { + use super::is_newer; + + #[test] + fn version_major_bump() { + assert!(is_newer("2.0.0", "1.9.9")); + assert!(!is_newer("1.9.9", "2.0.0")); + } + + #[test] + fn version_minor_bump() { + assert!(is_newer("1.1.0", "1.0.0")); + assert!(!is_newer("1.0.0", "1.1.0")); + } + + #[test] + fn version_patch_bump() { + assert!(is_newer("1.0.1", "1.0.0")); + assert!(!is_newer("1.0.0", "1.0.1")); + } + + #[test] + fn version_equal() { + assert!(!is_newer("1.0.0", "1.0.0")); + } + + #[test] + fn version_different_lengths() { + assert!(is_newer("1.0.1", "1.0")); + assert!(!is_newer("1.0", "1.0.1")); + assert!(is_newer("1.1", "1.0.9")); + } + + #[test] + fn version_ignores_extra_text() { + assert!(is_newer("1.0.0-beta", "0.9.0")); + // "beta" doesn't parse as u32, so it's filtered out. + // 1.0.0 vs 0.9.0 -> newer + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 3271940..7c896a8 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -56,7 +56,7 @@ "csp": null, "assetProtocol": { "enable": true, - "scope": ["**/*"] + "scope": ["$APPDIR/**", "$TEMP/**"] } } }, diff --git a/src/App.svelte b/src/App.svelte index 0c66e32..c6f9f76 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -17,11 +17,16 @@ let status: AppStatus try { status = await api.getStatus() - } catch (e) { - console.error("get_status failed", e) + } catch { view = "bootstrap" return } + try { + const cfg = await api.getConfig() + document.documentElement.setAttribute("data-theme", cfg.theme) + } catch { + document.documentElement.setAttribute("data-theme", "dark") + } if (status.ffmpeg === "missing") view = "bootstrap" else if (status.needs_first_run) view = "first-run" else view = "main" @@ -32,14 +37,27 @@ -{#if view === "loading"} - -{:else if view === "bootstrap"} - -{:else if view === "first-run"} - -{:else if view === "settings"} - view = "main"} /> -{:else} -
view = "settings"} /> -{/if} +
+ {#if view === "loading"} + + {:else if view === "bootstrap"} + + {:else if view === "first-run"} + + {:else if view === "settings"} + view = "main"} /> + {:else} +
view = "settings"} /> + {/if} +
+ + diff --git a/src/app.css b/src/app.css index 2a40f63..511cb90 100644 --- a/src/app.css +++ b/src/app.css @@ -1,16 +1,154 @@ -:root { - font-family: system-ui, -apple-system, "Segoe UI", sans-serif; +/* ============================================================ + ByteSize - Noir Precision Design System + Ultra-dark instrument panel aesthetic. + Electric teal accent. Monospace data readouts. + ============================================================ */ + +@import url('https://fonts.bunny.net/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&family=JetBrains+Mono:wght@400;500&display=swap'); + +/* ---- Dark theme (default) ---- */ +:root, +[data-theme="dark"] { + /* Backgrounds - layered near-blacks */ + --bg: #09090B; + --bg-2: #0E0E11; + --bg-3: #13131A; + --bg-4: #1A1A22; + + /* Accent - electric teal */ + --accent: #14B8A6; + --accent-hover: #2DD4BF; + --accent-dim: rgba(20, 184, 166, 0.10); + --accent-glow: rgba(20, 184, 166, 0.25); + --accent-text: #020617; + + /* Semantic - recording */ + --recording: #22C55E; + --recording-dim: rgba(34, 197, 94, 0.10); + --recording-glow: rgba(34, 197, 94, 0.20); + + /* Semantic - stop / danger */ + --stop: #EF4444; + --stop-hover: #F87171; + --stop-dim: rgba(239, 68, 68, 0.10); + + /* Semantic - error */ + --err: #EF4444; + --err-border: rgba(239, 68, 68, 0.30); + --err-dim: rgba(239, 68, 68, 0.08); + + /* Semantic - warning */ + --warn: #EAB308; + --warn-dim: rgba(234, 179, 8, 0.08); + + /* Borders */ + --border: rgba(255, 255, 255, 0.06); + --border-2: rgba(255, 255, 255, 0.10); + --border-3: rgba(255, 255, 255, 0.14); + + /* Text */ + --text: #E4E4E7; + --text-2: #A1A1AA; + --text-3: #71717A; + --text-4: #52525B; + + /* Typography */ + --sans: 'DM Sans', system-ui, sans-serif; + --mono: 'JetBrains Mono', ui-monospace, monospace; + + /* Radii */ + --r-sm: 3px; + --r-md: 6px; + --r-lg: 8px; + color-scheme: dark; - background: #1a1a1a; - color: #f0f0f0; - font-size: 14px; } -* { +/* ---- Light theme ---- */ +[data-theme="light"] { + --bg: #FAFAFA; + --bg-2: #F4F4F5; + --bg-3: #E4E4E7; + --bg-4: #D4D4D8; + + --accent: #0D9488; + --accent-hover: #0F766E; + --accent-dim: rgba(13, 148, 136, 0.08); + --accent-glow: rgba(13, 148, 136, 0.15); + --accent-text: #FFFFFF; + + --recording: #16A34A; + --recording-dim: rgba(22, 163, 74, 0.08); + --recording-glow: rgba(22, 163, 74, 0.12); + + --stop: #DC2626; + --stop-hover: #B91C1C; + --stop-dim: rgba(220, 38, 38, 0.08); + + --err: #DC2626; + --err-border: rgba(220, 38, 38, 0.25); + --err-dim: rgba(220, 38, 38, 0.06); + + --warn: #CA8A04; + --warn-dim: rgba(202, 138, 4, 0.06); + + --border: rgba(0, 0, 0, 0.08); + --border-2: rgba(0, 0, 0, 0.12); + --border-3: rgba(0, 0, 0, 0.18); + + --text: #18181B; + --text-2: #52525B; + --text-3: #71717A; + --text-4: #A1A1AA; + + color-scheme: light; +} + +/* ---- Reset & base ---- */ +*, *::before, *::after { box-sizing: border-box; } +html { + font-family: var(--sans); + font-size: 14px; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + body { margin: 0; + background: var(--bg); + color: var(--text); min-height: 100vh; } + +/* ---- Selection ---- */ +::selection { + background: var(--accent-dim); + color: var(--text); +} + +/* ---- Scrollbar ---- */ +::-webkit-scrollbar { width: 5px; height: 5px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { + background: var(--border-2); + border-radius: 3px; +} +::-webkit-scrollbar-thumb:hover { background: var(--text-4); } + +/* ---- Focus ---- */ +:focus-visible { + outline: none; + box-shadow: 0 0 0 1px var(--accent), 0 0 0 3px var(--accent-glow); + border-radius: var(--r-sm); +} + +/* ---- Reduced motion ---- */ +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + transition-duration: 0.01ms !important; + } +} diff --git a/src/lib/Bootstrap.svelte b/src/lib/Bootstrap.svelte index 1e09c05..72528c4 100644 --- a/src/lib/Bootstrap.svelte +++ b/src/lib/Bootstrap.svelte @@ -4,17 +4,13 @@ let { onReady }: { onReady: () => void } = $props() type Phase = "idle" | "downloading" | "error" - let phase: Phase = $state("idle") - let progress: DownloadProgress | null = $state(null) - let errMsg: string | null = $state(null) + let phase: Phase = $state("idle") + let progress = $state(null) + let errMsg = $state(null) async function start() { - phase = "downloading" - errMsg = null - progress = null - const unlisten = await api.onFfmpegProgress((p) => { - progress = p - }) + phase = "downloading"; errMsg = null; progress = null + const unlisten = await api.onFfmpegProgress((p) => { progress = p }) try { await api.downloadFfmpeg() unlisten() @@ -27,115 +23,216 @@ } -
-
-

ByteSize

-

set up encoder

-
+
+
+
+ +
encoder setup
+
- {#if phase === "idle"} -

- ByteSize needs ffmpeg to encode video. The download is around 30 MB and - is verified against a published SHA-256 checksum. -

-
- -
-

- Already have ffmpeg? Drop ffmpeg.exe into the - bin/ folder next to the app, then click below. -

-
- -
- {:else if phase === "downloading"} -

downloading ffmpeg...

- -

- {#if progress && progress.total} - {formatBytes(progress.downloaded)} / {formatBytes(progress.total)} - {:else if progress} - {formatBytes(progress.downloaded)} downloaded - {/if} -

- {:else} -

download failed

-
{errMsg}
-
- - -
- {/if} -
+ {#if phase === "idle"} +
+

+ ByteSize needs ffmpeg to encode video. Download is ~30 MB and verified against a published SHA-256 checksum. +

+ +

+ Already have ffmpeg? Drop ffmpeg.exe into the bin/ folder, then + . +

+
+ + {:else if phase === "downloading"} +
+

Downloading ffmpeg

+ {#if progress?.total} +
+
+
+

+ {formatBytes(progress.downloaded)} / {formatBytes(progress.total)} +

+ {:else if progress} +

{formatBytes(progress.downloaded)} downloaded

+ {:else} +

Connecting

+ {/if} +
+ + {:else} +
+ + {#if errMsg}
{errMsg}
{/if} + + +
+ {/if} + + diff --git a/src/lib/FirstRun.svelte b/src/lib/FirstRun.svelte index f172047..770df25 100644 --- a/src/lib/FirstRun.svelte +++ b/src/lib/FirstRun.svelte @@ -5,121 +5,179 @@ let { onDone }: { onDone: () => void } = $props() let start: string | null = $state(null) - let stop: string | null = $state(null) + let stop: string | null = $state(null) let pause: string | null = $state(null) let saving: boolean = $state(false) + let warnings: string[] = $state([]) async function save() { saving = true + warnings = [] try { const cfg = await api.getConfig() cfg.hotkeys.start = start - cfg.hotkeys.stop = stop + cfg.hotkeys.stop = stop cfg.hotkeys.pause = pause - await api.saveConfig(cfg) - onDone() - } finally { - saving = false - } + const result = await api.saveConfig(cfg) + const failed: string[] = [] + if (result.hotkey_result.start_ok === false) failed.push("start") + if (result.hotkey_result.stop_ok === false) failed.push("stop") + if (result.hotkey_result.pause_ok === false) failed.push("pause") + if (failed.length > 0) { + warnings = [`${failed.join(", ")} - hotkey may be in use by another app. try different keys.`] + } else { + onDone() + } + } finally { saving = false } } let valid = $derived(!!start && !!stop && !!pause) -
-
-

ByteSize

-

assign your hotkeys

-
-

- ByteSize doesn't ship default hotkeys. Pick combinations that won't clash - with apps you use. You can change these later in settings. -

-
- - - +
+
+
+ +
assign your hotkeys
+
+ +
+

+ No defaults are shipped. Pick combos that work for you - you can change these later in settings. +

+ +
+ + + +
+ + {#if warnings.length > 0} + + {/if} + + + +

Click a field, press your combo. Escape to cancel.

+
-
- -
-

- Click each field, then press your combo. Escape cancels. -

-
+ diff --git a/src/lib/HotkeyInput.svelte b/src/lib/HotkeyInput.svelte index c2b4b4a..41a02b8 100644 --- a/src/lib/HotkeyInput.svelte +++ b/src/lib/HotkeyInput.svelte @@ -1,36 +1,34 @@ + +
+
+ + + +
+
diff --git a/src/lib/Main.svelte b/src/lib/Main.svelte index 19c5feb..c8dc05e 100644 --- a/src/lib/Main.svelte +++ b/src/lib/Main.svelte @@ -1,14 +1,6 @@ -
-
-
-

ByteSize

-

- {#if phase === "recording"}recording... - {:else if phase === "paused"}paused - {:else if phase === "editing"}clip ready - {:else if phase === "exporting"}encoding... - {:else if phase === "done"}exported - {:else}ready{/if} -

+
+ +
+
+ BYTESIZE +
+
+ + + {phaseLabel} + + {#if clip && (phase === "editing" || phase === "exporting" || phase === "done")} + {clip.width}x{clip.height} · {clip.duration_secs.toFixed(2)}s + {/if} + {#if phase === "recording" || phase === "paused"} + {elapsed.toFixed(1)}s + {/if} +
+
+
-
- {#if phase === "idle"} -
- - -
- {#if useFrame} -
- preset: - - - - -
- {/if} -

- {#if useFrame} - The green frame stays visible during recording but is excluded from - the capture itself. Drag it to position the region, or pick a preset - above for common dimensions. - {:else} - Captures your full primary monitor. Toggle the capture frame on to - record a region instead. - {/if} -

- {:else if phase === "recording" || phase === "paused"} -
-
- {elapsed.toFixed(1)}s -
- {#if config?.capture.capture_audio} -
- - - - - + +
+ + {#if phase === "idle"} +
+
- {/if} -
- - {#if phase === "recording"} - - {:else} - - {/if} -
-
- {:else if phase === "editing" && clip} -
-

clip

-
-
duration
{clip.duration_secs.toFixed(2)}s
-
dimensions
{clip.width} x {clip.height}
-
-
+ +

+ {#if useFrame} + Drag the frame to position your capture region + {:else} + Captures the full primary monitor + {/if} +

-
-

trim

-
-
-
-
-
-
-

export

- -
- - - -
- -
- -
{targetMB.toFixed(1)} MB
-
-

- {targetMB.toFixed(1)} MB → {previewDims} at {fps}fps, {trimmedDuration.toFixed(1)}s -

- - {#if previewPath} -
- - {#if previewLoading}
rendering...
{/if} -
- {/if} - -
- - - {#if format !== "gif"} - - {/if} -
- - {#if format === "gif"} -
-
- frames {thumbnails.length > 0 ? `(${thumbnails.length - deletedFrames.size} kept / ${thumbnails.length})` : ""} - {#if deletedFrames.size > 0} - - {/if} -
- {#if loadingThumbs} -

extracting frames...

- {:else if thumbnails.length > 0} -
- {#each thumbnails as path, idx} - + {#if useFrame} +
+ {#each PRESETS as [w, h, label]} + {/each}
{/if}
- {/if} +
-
-
- {:else if phase === "exporting"} -
-

ffmpeg is working...

-

two-pass encode for target size. usually a few seconds.

-
- {:else if phase === "done" && exportResult} -
-

exported

-

{exportResult.output_path}

-

final size: {formatBytes(exportResult.size_bytes)}

-
- - -
-
- {/if} + + {:else if phase === "editing" && clip} +
+ +
+ +
+ {#each (["gif","webm","mp4"] as const) as f} + + {/each} +
+ + {#if previewPath} +
+ + {#if previewLoading}
rendering
{/if} +
+ {:else} +
+ preview +
+ {/if} + + +
+
+ {trimStart.toFixed(2)}s + {trimmedDuration.toFixed(2)}s kept + {trimEnd.toFixed(2)}s +
+
+
+
startDrag('start', e)} + onpointermove={onDrag} + onpointerup={endDrag} + >
+
startDrag('end', e)} + onpointermove={onDrag} + onpointerup={endDrag} + >
+
+ { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimStart = Math.min(v, trimEnd - 0.1) }} + class="sr-only" aria-label="trim start seconds" /> + { const v = parseFloat((e.currentTarget as HTMLInputElement).value); trimEnd = Math.max(v, trimStart + 0.1) }} + class="sr-only" aria-label="trim end seconds" /> +
+ + + {#if format === "gif" && (thumbnails.length > 0 || loadingThumbs)} +
+
+ Frames + {#if deletedFrames.size > 0} + + {/if} +
+ {#if loadingThumbs} +

extracting...

+ {:else} +
+ {#each thumbnails as path, idx} + + {/each} +
+ {/if} +
+ {/if} +
+ + +
+ +
+
+ Target size + {targetMB.toFixed(1)} MB +
+ +

{previewDims} · {fps}fps · {trimmedDuration.toFixed(1)}s

+
+ + +
+ + {#if format !== "gif"} + + {/if} +
+ + +
+
+ Crop + +
+ {#if cropEnabled} +
+ + + + +
+ {/if} +
+ + +
+ Output +
+ pathOverridden = true} aria-label="output file path" /> + +
+
+ + +
+ + +
+
+
+ + + {:else if phase === "exporting"} +
+ {#if encodeProgress} +
+ Pass {encodeProgress.pass}/{encodeProgress.total} + {encodeProgress.pct.toFixed(0)}% +
+
+
+
+ {:else} +
Preparing
+
+ {/if} +

ffmpeg is encoding your clip

+
+ + + {:else if phase === "done" && exportResult} +
+
+ + + +
+

Exported

+

{formatBytes(exportResult.size_bytes)}

+

{exportResult.output_path}

+
+ + +
+
+ {/if} +
+ + {#if errMsg} -

{errMsg}

+ {/if} -
+ diff --git a/src/lib/Overlay.svelte b/src/lib/Overlay.svelte index cc603fb..13b4873 100644 --- a/src/lib/Overlay.svelte +++ b/src/lib/Overlay.svelte @@ -5,129 +5,94 @@ import { invoke } from "@tauri-apps/api/core" const win = getCurrentWebviewWindow() + type Rect = { x: number; y: number; width: number; height: number } - let width: number = $state(0) + let width: number = $state(0) let height: number = $state(0) let phase: "idle" | "recording" | "paused" = $state("idle") - let fps: number = $state(30) + let fps: number = $state(30) let elapsed: number = $state(0) let timer: number | null = null onMount(() => { const updateSize = async () => { - const size = await win.innerSize() - const scale = await win.scaleFactor() - width = Math.round(size.width / scale) - height = Math.round(size.height / scale) + const sz = await win.innerSize() + const sf = await win.scaleFactor() + width = Math.round(sz.width / sf) + height = Math.round(sz.height / sf) } updateSize() - const unlistenResize = win.onResized(updateSize) + const rp = win.onResized(updateSize) - const unlistenStatePromise = listen<{ - phase: "idle" | "recording" | "paused" - fps: number - }>("recording-state", (e) => { - const next = e.payload.phase - fps = e.payload.fps - if (next === "recording") { - if (phase === "idle") elapsed = 0 - startTimer() - } else { - stopTimer() - } - if (next === "idle") elapsed = 0 - phase = next - }) + let rp2: Promise<() => void> | null = null + void (async () => { + rp2 = listen<{ phase: "idle"|"recording"|"paused"; fps: number }>( + "recording-state", (e) => { + fps = e.payload.fps + if (e.payload.phase === "recording") { + if (phase !== "recording") elapsed = 0 + startTimer() + } else { + stopTimer() + } + if (e.payload.phase === "idle") { elapsed = 0; phase = "idle" } + phase = e.payload.phase + } + ) + })() - return () => { - stopTimer() - unlistenResize.then((fn) => fn()) - unlistenStatePromise.then((fn) => fn()) - } + let rp3: Promise<() => void> | null = null + void (async () => { + rp3 = listen("picker-pick", async (e: { payload: Rect }) => { + try { await invoke("set_overlay_to_window", e.payload) } catch {} + 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()) } }) function startTimer() { if (timer !== null) return - timer = window.setInterval(() => { - elapsed += 0.1 - }, 100) + timer = window.setInterval(() => { elapsed += 0.1 }, 100) } - function stopTimer() { - if (timer !== null) { - clearInterval(timer) - timer = null - } + if (timer !== null) { clearInterval(timer); timer = null } } - function startDrag(e: MouseEvent) { - if (e.button === 0) { - e.preventDefault() - void win.startDragging().catch((err) => console.error("startDragging", err)) - } + function drag(e: MouseEvent) { + if (e.button === 0) void win.startDragging() } async function openPicker() { - try { - await invoke("open_window_picker") - } catch (e) { - console.error("open_window_picker", e) - } + try { await invoke("open_window_picker") } catch (err) { console.error(err) } } - - onMount(() => { - let unlistenPick: (() => void) | null = null - let unlistenCancel: (() => void) | null = null - void (async () => { - unlistenPick = await listen<{ x: number; y: number; width: number; height: number }>( - "picker-pick", - async (e) => { - try { - await invoke("set_overlay_to_window", e.payload) - } catch (err) { - console.error("set_overlay_to_window", err) - } - try { - await invoke("close_window_picker") - } catch (err) { - console.error("close_window_picker", err) - } - }, - ) - unlistenCancel = await listen("picker-cancel", async () => { - try { - await invoke("close_window_picker") - } catch (err) { - console.error("close_window_picker", err) - } - }) - })() - return () => { - unlistenPick?.() - unlistenCancel?.() - } - }) -
- diff --git a/src/lib/UpdateBanner.svelte b/src/lib/UpdateBanner.svelte index e8880a2..5b8ae78 100644 --- a/src/lib/UpdateBanner.svelte +++ b/src/lib/UpdateBanner.svelte @@ -2,8 +2,7 @@ import { onMount } from "svelte" import { api, formatBytes, type UpdateInfo, type UpdateDownloadProgress } from "./api" - type Phase = "info" | "downloading" | "ready-to-apply" | "error" - + type Phase = "info" | "downloading" | "ready" | "error" let info: UpdateInfo | null = $state(null) let phase: Phase = $state("info") let progress: UpdateDownloadProgress | null = $state(null) @@ -11,113 +10,72 @@ onMount(() => { let unlistenInfo: (() => void) | null = null - let unlistenProgress: (() => void) | null = null + let unlistenProg: (() => void) | null = null void (async () => { - unlistenInfo = await api.onUpdateAvailable((i) => { - info = i - phase = "info" - }) - unlistenProgress = await api.onUpdateDownloadProgress((p) => { - progress = p - }) - if (await api.pendingUpdate()) { - phase = "ready-to-apply" - } + unlistenInfo = await api.onUpdateAvailable((i) => { info = i; phase = "info" }) + unlistenProg = await api.onUpdateDownloadProgress((p) => { progress = p }) + if (await api.pendingUpdate()) phase = "ready" })() - return () => { - unlistenInfo?.() - unlistenProgress?.() - } + return () => { unlistenInfo?.(); unlistenProg?.() } }) - function dismiss() { - info = null - phase = "info" - errMsg = null - } - - function viewRelease() { - if (info) void api.openUrl(info.release_url) - } + function dismiss() { info = null; errMsg = null; phase = "info" } + function viewRelease() { if (info) void api.openUrl(info.release_url) } async function download() { - if (!info?.download_url) { - errMsg = "this release has no downloadable exe asset" - phase = "error" - return - } - phase = "downloading" - progress = null - errMsg = null - try { - await api.downloadUpdate(info.download_url) - phase = "ready-to-apply" - } catch (e) { - errMsg = String(e) - phase = "error" - } + if (!info?.download_url) { errMsg = "no downloadable exe in this release"; phase = "error"; return } + phase = "downloading"; progress = null; errMsg = null + try { await api.downloadUpdate(info.download_url); phase = "ready" } + catch (e) { errMsg = String(e); phase = "error" } } - async function apply() { - try { - await api.applyUpdate() - } catch (e) { - errMsg = String(e) - phase = "error" - } - } - - let bodyPreview = $derived.by(() => { - const i = info - if (!i) return "" - return i.body.split("\n").slice(0, 3).join(" ").slice(0, 140) - }) + async function apply() { try { await api.applyUpdate() } catch (e) { errMsg = String(e); phase = "error" } } -{#if info || phase === "ready-to-apply"} -