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
+1 -1
View File
@@ -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"] }
+222 -48
View File
@@ -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<JoinHandle<Result<()>>>,
running: Arc<AtomicBool>,
output_path: PathBuf,
pub sample_rate: u32,
pub channels: u16,
writer: Arc<Mutex<Option<BufWriter<File>>>>,
}
pub fn start(output_path: PathBuf) -> Result<AudioSession> {
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<PathBuf> {
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<AtomicBool>,
output_path: PathBuf,
init_tx: std::sync::mpsc::Sender<Result<(u32, u16)>>,
) -> 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::<IAudioClient>(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::<IAudioCaptureClient>()
.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(())
}
+91 -28
View File
@@ -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<GithubAsset>,
}
@@ -67,8 +68,6 @@ struct GithubRelease {
struct GithubAsset {
name: String,
browser_download_url: String,
#[serde(default)]
digest: Option<String>,
}
pub async fn download<F>(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<GithubAsset> {
/// 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: "<hex> <filename>" - 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<F>(
client: &reqwest::Client,
url: &str,
mut on_progress: F,
) -> Result<Vec<u8>>
where
F: FnMut(u64, Option<u64>),
{
let resp = client.get(url).send().await?.error_for_status()?;
let total = resp.content_length();
let mut buf: Vec<u8> = 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<GithubA
let body = resp.text().await?;
let release: GithubRelease =
serde_json::from_str(&body).context("parsing release metadata")?;
release
let version = release
.tag_name
.trim_start_matches('v')
.to_string();
let asset = release
.assets
.into_iter()
.find(|a| a.name.ends_with(source.asset_name_suffix))
@@ -138,23 +216,8 @@ async fn pick_asset(client: &reqwest::Client, source: &Source) -> Result<GithubA
"no asset matching '*{}' in release",
source.asset_name_suffix
)
})
}
fn parse_sha256_digest(digest: &Option<String>) -> 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<F>(
+43 -8
View File
@@ -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<Monitor> {
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<CaptureRect>,
fps: u32,
) -> Result<CaptureSession> {
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)
}
}
+81 -4
View File
@@ -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<PathBuf>,
#[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());
}
}
+251 -15
View File
@@ -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<f64>,
pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>,
/// Optional channel to report encoding progress.
#[doc(hidden)]
pub progress_tx: Option<Sender<EncodeProgress>>,
}
const MAX_CLICK_HIGHLIGHTS: usize = 50;
fn click_filters(req: &TranscodeRequest) -> Option<String> {
if req.clicks.is_empty() {
return None;
@@ -38,7 +57,15 @@ fn click_filters(req: &TranscodeRequest) -> Option<String> {
let size = 24i32;
let half = size / 2;
let mut parts: Vec<String> = 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::<Vec<_>>().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<EncodeProgress>>,
) -> 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::<Vec<_>>().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<Sender<EncodeProgress>>,
) -> Result<std::process::Output> {
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::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().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<f64> {
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<Click> = (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(())
}
+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 {
+42
View File
@@ -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
}
}
+1 -1
View File
@@ -56,7 +56,7 @@
"csp": null,
"assetProtocol": {
"enable": true,
"scope": ["**/*"]
"scope": ["$APPDIR/**", "$TEMP/**"]
}
}
},
+31 -13
View File
@@ -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 @@
<UpdateBanner />
{#if view === "loading"}
<Loading />
{:else if view === "bootstrap"}
<Bootstrap onReady={refresh} />
{:else if view === "first-run"}
<FirstRun onDone={refresh} />
{:else if view === "settings"}
<Settings onClose={() => view = "main"} />
{:else}
<Main onSettings={() => view = "settings"} />
{/if}
<div class="view-stage" class:shift={view !== "loading"}>
{#if view === "loading"}
<Loading />
{:else if view === "bootstrap"}
<Bootstrap onReady={refresh} />
{:else if view === "first-run"}
<FirstRun onDone={refresh} />
{:else if view === "settings"}
<Settings onClose={() => view = "main"} />
{:else}
<Main onSettings={() => view = "settings"} />
{/if}
</div>
<style>
.view-stage {
min-height: 100vh;
animation: enter 180ms ease-out;
}
@keyframes enter {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
</style>
+144 -6
View File
@@ -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;
}
}
+204 -107
View File
@@ -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<DownloadProgress | null>(null)
let errMsg = $state<string | null>(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 @@
}
</script>
<main>
<header>
<h1>ByteSize</h1>
<p class="sub">set up encoder</p>
</header>
<div class="stage">
<div class="card">
<div class="card-head">
<div class="logo">BYTESIZE</div>
<div class="tag">encoder setup</div>
</div>
{#if phase === "idle"}
<p>
ByteSize needs ffmpeg to encode video. The download is around 30 MB and
is verified against a published SHA-256 checksum.
</p>
<div class="row">
<button class="primary" onclick={start}>download ffmpeg</button>
</div>
<p class="hint">
Already have ffmpeg? Drop <code>ffmpeg.exe</code> into the
<code>bin/</code> folder next to the app, then click below.
</p>
<div class="row">
<button onclick={onReady}>i added it manually</button>
</div>
{:else if phase === "downloading"}
<p>downloading ffmpeg...</p>
<progress
value={progress?.downloaded ?? 0}
max={progress?.total ?? undefined}
></progress>
<p class="hint">
{#if progress && progress.total}
{formatBytes(progress.downloaded)} / {formatBytes(progress.total)}
{:else if progress}
{formatBytes(progress.downloaded)} downloaded
{/if}
</p>
{:else}
<p class="err">download failed</p>
<pre>{errMsg}</pre>
<div class="row">
<button onclick={start}>retry</button>
<button onclick={onReady}>i added it manually</button>
</div>
{/if}
</main>
{#if phase === "idle"}
<div class="body">
<p class="copy">
ByteSize needs <strong>ffmpeg</strong> to encode video. Download is ~30 MB and verified against a published SHA-256 checksum.
</p>
<button class="btn-primary" onclick={start}>Download ffmpeg</button>
<p class="manual">
Already have ffmpeg? Drop <code>ffmpeg.exe</code> into the <code>bin/</code> folder, then
<button class="link" onclick={onReady}>use it</button>.
</p>
</div>
{:else if phase === "downloading"}
<div class="body">
<p class="status">Downloading ffmpeg</p>
{#if progress?.total}
<div class="track">
<div class="fill" style="width:{Math.min(100, (progress.downloaded / progress.total) * 100)}%"></div>
</div>
<p class="prog-text">
{formatBytes(progress.downloaded)} / {formatBytes(progress.total)}
</p>
{:else if progress}
<p class="prog-text">{formatBytes(progress.downloaded)} downloaded</p>
{:else}
<p class="prog-text">Connecting</p>
{/if}
</div>
{:else}
<div class="body">
<div class="err" role="alert">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<circle cx="7" cy="7" r="6"/><line x1="7" y1="4" x2="7" y2="7.5"/><circle cx="7" cy="10" r="0.5" fill="currentColor"/>
</svg>
Download failed
</div>
{#if errMsg}<pre class="err-detail">{errMsg}</pre>{/if}
<button class="btn-primary" onclick={start}>Retry</button>
<button class="link" onclick={onReady}>Use existing ffmpeg.exe</button>
</div>
{/if}
</div>
</div>
<style>
main {
padding: 2rem;
max-width: 560px;
margin: 0 auto;
.stage {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
background: var(--bg);
}
header h1 {
margin: 0 0 0.25rem;
font-size: 1.5rem;
letter-spacing: -0.01em;
}
.sub {
color: #888;
font-size: 0.875rem;
margin: 0 0 1.5rem;
}
.row {
display: flex;
gap: 0.5rem;
margin: 1rem 0;
}
.hint {
color: #888;
font-size: 0.85rem;
}
code {
background: #2a2a2a;
padding: 0.1rem 0.35rem;
border-radius: 3px;
font-size: 0.85em;
}
progress {
.card {
width: 100%;
height: 8px;
max-width: 380px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-md);
overflow: hidden;
}
pre {
background: #2a2a2a;
padding: 0.75rem;
border-radius: 4px;
overflow-x: auto;
font-size: 0.8rem;
color: #ec9a9a;
.card-head {
padding: 28px 24px 20px;
border-bottom: 1px solid var(--border);
text-align: center;
}
.err {
color: #ec9a9a;
.logo {
font-family: var(--mono);
font-size: 13px;
font-weight: 500;
letter-spacing: 0.12em;
color: var(--accent);
}
button {
font: inherit;
padding: 0.5rem 1rem;
border: 1px solid #444;
background: transparent;
color: inherit;
.tag {
margin-top: 6px;
font-size: 12px;
color: var(--text-3);
letter-spacing: 0.02em;
}
.body {
padding: 24px;
display: flex;
flex-direction: column;
gap: 16px;
}
.copy {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: var(--text-2);
}
.copy strong {
color: var(--text);
font-weight: 600;
}
.btn-primary {
width: 100%;
padding: 11px 16px;
background: var(--accent);
border: none;
color: var(--accent-text);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
font-weight: 600;
cursor: pointer;
border-radius: 4px;
transition: background 80ms;
}
button:hover {
border-color: #888;
.btn-primary:hover { background: var(--accent-hover); }
.manual {
margin: 0;
font-size: 12px;
color: var(--text-3);
text-align: center;
line-height: 1.5;
}
button.primary {
background: #4a8;
border-color: #4a8;
color: #111;
.manual code {
font-family: var(--mono);
font-size: 11px;
color: var(--text-2);
background: var(--bg-3);
padding: 1px 5px;
border-radius: var(--r-sm);
}
button.primary:hover {
background: #5b9;
border-color: #5b9;
.link {
background: none;
border: none;
color: var(--accent);
cursor: pointer;
font-size: 12px;
padding: 0;
font-family: var(--sans);
text-decoration: underline;
text-underline-offset: 2px;
}
.link:hover { color: var(--accent-hover); }
.status {
margin: 0;
font-size: 13px;
color: var(--text-2);
text-align: center;
}
.track {
width: 100%;
height: 3px;
background: var(--bg-3);
border-radius: 2px;
overflow: hidden;
}
.fill {
height: 100%;
background: var(--accent);
border-radius: 2px;
transition: width 0.4s ease;
}
.prog-text {
margin: 0;
font-size: 11px;
font-family: var(--mono);
color: var(--text-3);
text-align: center;
}
.err {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 10px 14px;
background: var(--err-dim);
border: 1px solid var(--err-border);
border-radius: var(--r-sm);
font-size: 12px;
color: var(--err);
}
.err-detail {
margin: 0;
padding: 10px;
background: var(--bg-3);
border: 1px solid var(--border);
border-radius: var(--r-sm);
font-family: var(--mono);
font-size: 10px;
color: var(--err);
white-space: pre-wrap;
word-break: break-all;
max-height: 120px;
overflow-y: auto;
}
</style>
+147 -89
View File
@@ -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)
</script>
<main>
<header>
<h1>ByteSize</h1>
<p class="sub">assign your hotkeys</p>
</header>
<p>
ByteSize doesn't ship default hotkeys. Pick combinations that won't clash
with apps you use. You can change these later in settings.
</p>
<div class="form">
<label>
<span>start</span>
<HotkeyInput bind:value={start} placeholder="e.g. F9" />
</label>
<label>
<span>stop</span>
<HotkeyInput bind:value={stop} placeholder="e.g. F9" />
</label>
<label>
<span>pause</span>
<HotkeyInput bind:value={pause} placeholder="e.g. F10" />
</label>
<div class="stage">
<div class="card">
<div class="card-head">
<div class="logo">BYTESIZE</div>
<div class="tag">assign your hotkeys</div>
</div>
<div class="body">
<p class="copy">
No defaults are shipped. Pick combos that work for you - you can change these later in settings.
</p>
<div class="fields">
<label class="field">
<span class="field-label">Start recording</span>
<HotkeyInput bind:value={start} placeholder="e.g. F9" />
</label>
<label class="field">
<span class="field-label">Stop recording</span>
<HotkeyInput bind:value={stop} placeholder="e.g. F10" />
</label>
<label class="field">
<span class="field-label">Pause / resume</span>
<HotkeyInput bind:value={pause} placeholder="e.g. F11" />
</label>
</div>
{#if warnings.length > 0}
<div class="warn" role="alert">
{#each warnings as w}<p>{w}</p>{/each}
</div>
{/if}
<button class="btn-primary" onclick={save} disabled={!valid || saving}>
{saving ? "Saving" : "Save and continue"}
</button>
<p class="hint">Click a field, press your combo. Escape to cancel.</p>
</div>
</div>
<div class="row">
<button class="primary" disabled={!valid || saving} onclick={save}>
{saving ? "saving..." : "save and continue"}
</button>
</div>
<p class="hint">
Click each field, then press your combo. Escape cancels.
</p>
</main>
</div>
<style>
main {
padding: 2rem;
max-width: 560px;
margin: 0 auto;
}
header h1 {
margin: 0 0 0.25rem;
font-size: 1.5rem;
letter-spacing: -0.01em;
}
.sub {
color: #888;
font-size: 0.875rem;
margin: 0 0 1.5rem;
}
.form {
.stage {
min-height: 100vh;
display: grid;
gap: 0.75rem;
margin: 1.25rem 0;
place-items: center;
padding: 24px;
background: var(--bg);
}
label {
display: grid;
grid-template-columns: 80px 1fr;
align-items: center;
gap: 0.75rem;
.card {
width: 100%;
max-width: 400px;
background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-md);
overflow: hidden;
}
label span {
color: #aaa;
font-size: 0.875rem;
.card-head {
padding: 28px 24px 20px;
border-bottom: 1px solid var(--border);
text-align: center;
}
.row {
.logo {
font-family: var(--mono);
font-size: 13px;
font-weight: 500;
letter-spacing: 0.12em;
color: var(--accent);
}
.tag {
margin-top: 6px;
font-size: 12px;
color: var(--text-3);
letter-spacing: 0.02em;
}
.body {
padding: 24px;
display: flex;
gap: 0.5rem;
margin: 1rem 0;
flex-direction: column;
gap: 16px;
}
.hint {
color: #888;
font-size: 0.85rem;
.copy {
margin: 0;
font-size: 13px;
line-height: 1.6;
color: var(--text-2);
text-align: center;
}
button {
font: inherit;
padding: 0.5rem 1rem;
border: 1px solid #444;
background: transparent;
color: inherit;
.fields {
display: flex;
flex-direction: column;
gap: 14px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
}
.field-label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--text-3);
}
.btn-primary {
width: 100%;
padding: 11px 16px;
background: var(--accent);
border: none;
color: var(--accent-text);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
font-weight: 600;
cursor: pointer;
border-radius: 4px;
transition: background 80ms;
}
button:hover:not(:disabled) {
border-color: #888;
.btn-primary:hover:not(:disabled) { background: var(--accent-hover); }
.btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
.hint {
margin: 0;
font-size: 11px;
color: var(--text-3);
text-align: center;
}
button.primary {
background: #4a8;
border-color: #4a8;
color: #111;
}
button.primary:disabled {
background: #333;
border-color: #333;
color: #666;
cursor: not-allowed;
.warn {
padding: 10px 14px;
background: var(--err-dim);
border: 1px solid var(--err-border);
border-radius: var(--r-sm);
text-align: center;
}
.warn p { margin: 0; font-size: 12px; color: var(--err); }
</style>
+74 -56
View File
@@ -1,36 +1,34 @@
<script lang="ts">
let {
value = $bindable(),
placeholder = "click to assign",
placeholder = "press a key...",
}: {
value: string | null
placeholder?: string
} = $props()
let capturing: boolean = $state(false)
let buttonEl: HTMLButtonElement | null = $state(null)
let capturing = $state(false)
let btn: HTMLButtonElement | null = $state(null)
const MODIFIER_KEYS = new Set(["Control", "Shift", "Alt", "Meta", "ControlLeft", "ControlRight"])
const MODIFIERS = new Set(["Control","Shift","Alt","Meta",
"ControlLeft","ControlRight","ShiftLeft","ShiftRight",
"AltLeft","AltRight","MetaLeft","MetaRight"])
function startCapture() {
function start() {
capturing = true
buttonEl?.focus()
btn?.focus()
}
function handleKeydown(e: KeyboardEvent) {
function keydown(e: KeyboardEvent) {
if (!capturing) return
e.preventDefault()
e.stopPropagation()
if (e.key === "Escape") {
capturing = false
buttonEl?.blur()
return
}
if (MODIFIER_KEYS.has(e.key)) {
btn?.blur()
return
}
if (MODIFIERS.has(e.key)) return
const parts: string[] = []
if (e.ctrlKey) parts.push("Ctrl")
@@ -45,11 +43,7 @@
parts.push(key)
value = parts.join("+")
capturing = false
buttonEl?.blur()
}
function handleBlur() {
capturing = false
btn?.blur()
}
function clear(e: MouseEvent) {
@@ -61,65 +55,89 @@
<div class="row">
<button
bind:this={buttonEl}
bind:this={btn}
class="key"
class:capturing
onclick={startCapture}
onkeydown={handleKeydown}
onblur={handleBlur}
onclick={start}
onkeydown={keydown}
onblur={() => { capturing = false }}
type="button"
aria-label={capturing ? "recording shortcut - press a key combo" : "click to assign shortcut"}
>
{#if capturing}
press a combo (Esc to cancel)
<span class="blink">type a combo</span>
{:else if value}
{value}
<span class="val">{value}</span>
{:else}
{placeholder}
<span class="ph">{placeholder}</span>
{/if}
</button>
{#if value && !capturing}
<button class="clear" onclick={clear} type="button" title="clear">×</button>
<button class="x" onclick={clear} type="button" aria-label="clear shortcut">
<svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<line x1="2" y1="2" x2="8" y2="8"/>
<line x1="8" y1="2" x2="2" y2="8"/>
</svg>
</button>
{/if}
</div>
<style>
.row {
display: flex;
gap: 0.4rem;
gap: 4px;
align-items: stretch;
}
button {
font: inherit;
padding: 0.45rem 0.7rem;
border: 1px solid #444;
background: #222;
color: inherit;
border-radius: 4px;
cursor: pointer;
text-align: left;
.key {
flex: 1;
height: 34px;
padding: 0 12px;
background: var(--bg-3);
border: 1px solid var(--border-2);
color: var(--text);
border-radius: var(--r-sm);
cursor: pointer;
font-family: var(--mono);
font-size: 12px;
font-weight: 500;
letter-spacing: 0.02em;
transition: border-color 80ms, background 80ms;
text-align: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
button:hover {
border-color: #888;
.key:hover { border-color: var(--border-3); background: var(--bg-4); }
.key:focus-visible { box-shadow: 0 0 0 1px var(--accent), 0 0 0 3px var(--accent-glow); outline: none; }
.key.capturing {
border-color: var(--accent);
background: var(--accent-dim);
color: var(--accent);
}
button.capturing {
border-color: #4a8;
background: #1a2a24;
color: #4a8;
outline: none;
.val { color: var(--text); }
.ph { color: var(--text-3); font-style: italic; font-family: var(--sans); font-weight: 400; }
.blink { animation: blink 1s step-end infinite; color: var(--accent); }
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
button:focus {
outline: none;
border-color: #4a8;
}
button.clear {
flex: 0 0 auto;
padding: 0.45rem 0.7rem;
color: #888;
.x {
display: grid;
place-items: center;
width: 34px;
height: 34px;
background: transparent;
border-color: #2a2a2a;
}
button.clear:hover {
color: #ec9a9a;
border-color: #ec9a9a;
border: 1px solid var(--border);
color: var(--text-3);
border-radius: var(--r-sm);
cursor: pointer;
flex-shrink: 0;
transition: color 80ms, border-color 80ms;
}
.x:hover { color: var(--err); border-color: var(--err-border); }
</style>
+36 -6
View File
@@ -1,14 +1,44 @@
<main class="center">
<p class="muted">loading...</p>
</main>
<script lang="ts">
// Minimal loading state - a single breathing mark.
</script>
<div class="stage">
<div class="mark">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</div>
</div>
<style>
main.center {
.stage {
min-height: 100vh;
display: grid;
place-items: center;
background: var(--bg);
}
.muted {
color: #777;
.mark {
display: flex;
gap: 4px;
align-items: flex-end;
height: 20px;
}
.bar {
display: block;
width: 3px;
background: var(--accent);
border-radius: 1px;
animation: breathe 1s ease-in-out infinite;
}
.bar:nth-child(1) { height: 8px; animation-delay: 0ms; }
.bar:nth-child(2) { height: 16px; animation-delay: 120ms; }
.bar:nth-child(3) { height: 12px; animation-delay: 240ms; }
@keyframes breathe {
0%, 100% { opacity: 0.35; transform: scaleY(0.8); }
50% { opacity: 1; transform: scaleY(1); }
}
</style>
+1201 -783
View File
File diff suppressed because it is too large Load Diff
+107 -143
View File
@@ -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<Rect>("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?.()
}
})
</script>
<div class="frame">
<div
class="titlebar"
data-tauri-drag-region
onmousedown={startDrag}
role="presentation"
>
<span class="grip" data-tauri-drag-region>⠿</span>
<span class="dim" data-tauri-drag-region>{width} x {height}</span>
<button
class="pick-btn"
onclick={openPicker}
onmousedown={(e) => e.stopPropagation()}
title="snap to window"
type="button"
>▦</button>
<div class="overlay">
<div class="titlebar" onmousedown={drag} role="presentation">
<span class="grip" aria-hidden="true">::</span>
<span class="dims" aria-label="dimensions">{width} x {height}</span>
<button class="pick-btn" onclick={openPicker} title="snap to window" aria-label="snap capture frame to a window">
<svg width="10" height="10" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round">
<rect x="1" y="1" width="4" height="4" rx="0.5"/>
<rect x="7" y="1" width="4" height="4" rx="0.5"/>
<rect x="1" y="7" width="4" height="4" rx="0.5"/>
<rect x="7" y="7" width="4" height="4" rx="0.5"/>
</svg>
</button>
{#if phase !== "idle"}
<span class="status" class:rec={phase === "recording"}>
{phase === "recording" ? "REC" : "PAUSE"} · {elapsed.toFixed(1)}s · {fps}fps
<span class="status" class:recording={phase === "recording"}>
{phase === "recording" ? "REC" : "PAUSE"}
<span class="sep">/</span>
{elapsed.toFixed(1)}s
<span class="sep">/</span>
{fps}fps
</span>
{/if}
</div>
@@ -135,72 +100,71 @@
<style>
:global(html), :global(body), :global(#overlay) {
margin: 0;
padding: 0;
margin: 0; padding: 0;
background: transparent;
height: 100vh;
width: 100vw;
height: 100vh; width: 100vw;
overflow: hidden;
}
.frame {
.overlay {
box-sizing: border-box;
height: 100vh;
width: 100vw;
border: 2px solid #4a8;
display: flex;
flex-direction: column;
height: 100vh; width: 100vw;
border: 2px solid #14B8A6;
display: flex; flex-direction: column;
background: transparent;
border-radius: var(--r-sm);
}
.titlebar {
height: 22px;
background: rgba(74, 170, 136, 0.85);
color: #0e1a16;
display: flex;
align-items: center;
gap: 8px;
height: 24px;
background: rgba(9, 9, 11, 0.92);
backdrop-filter: blur(8px);
color: rgba(228, 228, 231, 0.7);
display: flex; align-items: center; gap: 8px;
padding: 0 8px;
font: 11px ui-monospace, monospace;
font: 10px/1 var(--mono, 'JetBrains Mono', monospace);
cursor: grab;
flex-shrink: 0;
user-select: none;
border-bottom: 1px solid rgba(20, 184, 166, 0.2);
border-radius: 2px 2px 0 0;
}
.titlebar:active {
cursor: grabbing;
.titlebar:active { cursor: grabbing; }
.grip { opacity: 0.35; font-size: 11px; flex-shrink: 0; letter-spacing: 1px; }
.dims {
font-family: var(--mono, 'JetBrains Mono', monospace);
font-size: 10px;
color: rgba(228, 228, 231, 0.4);
letter-spacing: 0.02em;
}
.grip {
font-size: 14px;
opacity: 0.7;
}
.dim {
font-variant-numeric: tabular-nums;
.pick-btn {
display: grid; place-items: center;
width: 20px; height: 20px;
background: rgba(20, 184, 166, 0.1);
border: 1px solid rgba(20, 184, 166, 0.25);
color: rgba(20, 184, 166, 0.7);
border-radius: var(--r-sm);
cursor: pointer;
flex-shrink: 0;
transition: all 80ms;
}
.pick-btn:hover { background: rgba(20, 184, 166, 0.18); border-color: rgba(20, 184, 166, 0.5); color: #14B8A6; }
.status {
margin-left: auto;
font-variant-numeric: tabular-nums;
font-family: var(--mono, 'JetBrains Mono', monospace);
font-size: 10px; font-weight: 500;
color: rgba(228, 228, 231, 0.5);
display: flex; align-items: center; gap: 4px;
background: rgba(255,255,255,0.04);
padding: 1px 6px;
border-radius: 999px;
background: rgba(0, 0, 0, 0.25);
color: #eee;
border-radius: 2px;
}
.status.rec {
background: #c33;
color: #fff;
}
.pick-btn {
background: rgba(0, 0, 0, 0.2);
border: 1px solid rgba(14, 26, 22, 0.4);
color: #0e1a16;
font: inherit;
font-size: 12px;
padding: 1px 6px;
border-radius: 3px;
cursor: pointer;
line-height: 1;
}
.pick-btn:hover {
background: rgba(0, 0, 0, 0.35);
color: #fff;
.status.recording {
background: rgba(34, 197, 94, 0.15);
color: #22C55E;
}
.sep { opacity: 0.3; }
</style>
+82 -82
View File
@@ -1,138 +1,138 @@
<script lang="ts">
import { onMount } from "svelte"
import { listen } from "@tauri-apps/api/event"
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"
import { listen } from "@tauri-apps/api/event"
type Rect = {
x: number
y: number
width: number
height: number
}
type Rect = { x: number; y: number; width: number; height: number }
let hover: Rect | null = $state(null)
let scale: number = $state(1)
let originX: number = $state(0)
let originY: number = $state(0)
let dpr: number = $state(1)
let innerW: number = $state(0)
let innerH: number = $state(0)
let originX = 0, originY = 0, scale = 1
onMount(() => {
const win = getCurrentWebviewWindow()
let unlistenHover: (() => void) | null = null
let unlistenMoved: (() => void) | null = null
let unlisten: (() => void)[] = []
const refreshOrigin = async () => {
const refresh = async () => {
scale = await win.scaleFactor()
const pos = await win.innerPosition()
originX = pos.x
originY = pos.y
dpr = window.devicePixelRatio
innerW = window.innerWidth
innerH = window.innerHeight
originX = pos.x; originY = pos.y
}
void (async () => {
await refreshOrigin()
unlistenMoved = await win.onMoved(refreshOrigin)
unlistenHover = await listen<Rect>("picker-hover", (e) => {
hover = e.payload
})
await refresh()
unlisten.push(await win.onMoved(refresh))
unlisten.push(await listen<Rect>("picker-hover", (e) => { hover = e.payload }))
})()
return () => {
unlistenHover?.()
unlistenMoved?.()
}
return () => unlisten.forEach(fn => fn())
})
let style = $derived.by(() => {
let rectStyle = $derived.by(() => {
if (!hover) return ""
const left = (hover.x - originX) / scale
const top = (hover.y - originY) / scale
const width = hover.width / scale
const height = hover.height / scale
return `left: ${left}px; top: ${top}px; width: ${width}px; height: ${height}px;`
const l = (hover.x - originX) / scale
const t = (hover.y - originY) / scale
const w = hover.width / scale
const h = hover.height / scale
return `left:${l}px;top:${t}px;width:${w}px;height:${h}px`
})
</script>
<main>
<div class="dim"></div>
<div class="picker" aria-label="window picker - click a window to capture it, Esc to cancel">
<div class="dim" aria-hidden="true"></div>
{#if hover}
<div class="frame" style={style}>
<div class="dims">{hover.width} x {hover.height}</div>
<div class="frame" style={rectStyle} aria-hidden="true">
<span class="frame-label">{hover.width} x {hover.height}</span>
</div>
{/if}
<div class="hint">
origin=({originX},{originY}) scale={scale} dpr={dpr} inner={innerW}x{innerH} ·
<div class="hint" aria-live="polite">
{#if hover}
hover {hover.width}x{hover.height} @ ({hover.x},{hover.y})
click to capture - <kbd>{hover.width}x{hover.height}</kbd>
{:else}
move mouse over a window. Esc to cancel.
move mouse over a window to select it - <kbd>Esc</kbd> to cancel
{/if}
</div>
</main>
</div>
<style>
:global(html), :global(body), :global(#picker) {
margin: 0;
padding: 0;
margin: 0; padding: 0;
background: transparent;
height: 100vh;
width: 100vw;
height: 100vh; width: 100vw;
overflow: hidden;
cursor: crosshair;
}
main {
.picker {
position: relative;
width: 100vw;
height: 100vh;
width: 100vw; height: 100vh;
font-family: var(--mono, 'JetBrains Mono', monospace);
}
.dim {
position: absolute;
inset: 0;
background: rgba(10, 14, 12, 0.15);
position: absolute; inset: 0;
background: rgba(9, 9, 11, 0.15);
}
.frame {
position: absolute;
pointer-events: none;
background-color: transparent;
border: 2px solid #14B8A6;
background: transparent;
background-image:
linear-gradient(90deg, #4a8 50%, transparent 50%),
linear-gradient(90deg, #4a8 50%, transparent 50%),
linear-gradient(0deg, #4a8 50%, transparent 50%),
linear-gradient(0deg, #4a8 50%, transparent 50%);
background-position: 0 0, 0 100%, 0 0, 100% 0;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y;
background-size: 12px 2px, 12px 2px, 2px 12px, 2px 12px;
repeating-linear-gradient(90deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px),
repeating-linear-gradient(0deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px),
repeating-linear-gradient(90deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px),
repeating-linear-gradient(0deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px);
background-position: 0 0, 0 0, 0 100%, 100% 0;
background-size: 12px 2px, 2px 12px, 12px 2px, 2px 12px;
background-repeat: repeat-x, repeat-y, repeat-x, repeat-y;
animation: march 0.4s linear infinite;
transition: left 0.08s ease, top 0.08s ease, width 0.08s ease, height 0.08s ease;
}
@keyframes march {
to {
background-position: 12px 0, -12px 100%, 0 -12px, 100% 12px;
}
to { background-position: 12px 0, 0 12px, -12px 100%, 100% -12px; }
}
.dims {
.frame-label {
position: absolute;
top: -22px;
left: 0;
padding: 1px 6px;
background: #4a8;
color: #0e1a16;
font: 11px ui-monospace, monospace;
border-radius: 3px;
top: -20px; left: 0;
padding: 2px 6px;
background: #14B8A6;
color: #020617;
font-size: 9px;
font-weight: 600;
font-family: var(--mono, 'JetBrains Mono', monospace);
letter-spacing: 0.04em;
border-radius: 2px;
white-space: nowrap;
}
.hint {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 6px 14px;
background: rgba(0, 0, 0, 0.7);
color: #fff;
position: fixed;
bottom: 20px; left: 50%; transform: translateX(-50%);
padding: 7px 18px;
background: rgba(9, 9, 11, 0.9);
backdrop-filter: blur(10px);
color: rgba(228, 228, 231, 0.85);
font-size: 12px;
font-family: var(--sans, system-ui, sans-serif);
border: 1px solid rgba(20, 184, 166, 0.2);
border-radius: 999px;
font: 13px ui-monospace, monospace;
white-space: nowrap;
pointer-events: none;
}
kbd {
display: inline-block;
padding: 0 4px;
background: rgba(20, 184, 166, 0.12);
border: 1px solid rgba(20, 184, 166, 0.3);
border-radius: 2px;
font-family: var(--mono, 'JetBrains Mono', monospace);
font-size: 10px;
color: #14B8A6;
}
</style>
+419 -201
View File
@@ -8,250 +8,468 @@
let cfg: Config | null = $state(null)
let saving: boolean = $state(false)
let hotkeyWarnings: string[] = $state([])
let showAdvanced: boolean = $state(false)
let activeTab: string = $state("capture")
onMount(async () => {
cfg = await api.getConfig()
})
const TABS = [
{ id: "capture", label: "Capture" },
{ id: "export", label: "Export" },
{ id: "hotkeys", label: "Hotkeys" },
{ id: "output", label: "Output" },
{ id: "system", label: "System" },
]
onMount(async () => { cfg = await api.getConfig() })
async function save() {
if (!cfg) return
saving = true
hotkeyWarnings = []
try {
await api.saveConfig(cfg)
onClose()
} 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) {
hotkeyWarnings = [`${failed.join(", ")} - hotkey may be in use by another app`]
} else {
onClose()
}
} finally { saving = false }
}
async function pickOutputDir() {
if (!cfg) return
const picked = await open({
directory: true,
defaultPath: cfg.output_dir ?? undefined,
})
if (typeof picked === "string") {
cfg.output_dir = picked
}
const picked = await open({ directory: true, defaultPath: cfg.output_dir ?? undefined })
if (typeof picked === "string") cfg.output_dir = picked
}
</script>
<main>
<header>
<h1>settings</h1>
<button class="back" onclick={onClose}>← back</button>
<div class="settings">
<header class="settings-header">
<div class="header-left">
<button class="back-btn" onclick={onClose} aria-label="close settings">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="9,2 3,7 9,12"/>
</svg>
</button>
<h1>Settings</h1>
</div>
</header>
{#if cfg}
<section>
<h2>capture</h2>
<label>
<span>default fps</span>
<select bind:value={cfg.capture.default_fps}>
<option value={15}>15</option>
<option value={24}>24</option>
<option value={30}>30</option>
<option value={60}>60</option>
</select>
</label>
<label class="check">
<input type="checkbox" bind:checked={cfg.capture.capture_cursor} />
<span>capture cursor by default</span>
</label>
<label class="check">
<input type="checkbox" bind:checked={cfg.capture.capture_audio} />
<span>capture system audio by default</span>
</label>
</section>
<div class="settings-body">
<!-- Tab nav -->
<nav class="tab-nav" aria-label="settings categories">
{#each TABS as t}
<button
class="tab"
class:active={activeTab === t.id}
onclick={() => activeTab = t.id}
>{t.label}</button>
{/each}
</nav>
<section>
<h2>export defaults</h2>
<label>
<span>default format</span>
<select bind:value={cfg.export.default_format}>
<option value="gif">GIF</option>
<option value="webm">WebM</option>
<option value="mp4">MP4</option>
</select>
</label>
<label>
<span>GIF dithering</span>
<select bind:value={cfg.export.gif_dither}>
<option value="floyd_steinberg">Floyd-Steinberg</option>
<option value="bayer">Bayer</option>
<option value="none">none</option>
</select>
</label>
<label>
<span>WebM codec</span>
<select bind:value={cfg.export.webm_codec}>
<option value="vp9">VP9 (default)</option>
<option value="av1">AV1 (smaller, slower)</option>
</select>
</label>
<label>
<span>MP4 codec</span>
<select bind:value={cfg.export.mp4_codec}>
<option value="h264">H.264 (default)</option>
<option value="h265">H.265 (smaller, less universal)</option>
</select>
</label>
</section>
<!-- Tab content -->
<div class="tab-content">
{#if activeTab === "capture"}
<div class="tab-panel">
<div class="panel-head">
<h2>Capture</h2>
<p class="panel-desc">Recording behavior and defaults</p>
</div>
<div class="field-list">
<label class="field">
<span class="field-label">Default FPS</span>
<select bind:value={cfg.capture.default_fps}>
{#each [15,24,30,60] as f}<option value={f}>{f} fps</option>{/each}
</select>
</label>
<label class="field-check">
<input type="checkbox" bind:checked={cfg.capture.capture_cursor} />
<span>Capture cursor</span>
</label>
<label class="field-check">
<input type="checkbox" bind:checked={cfg.capture.capture_audio} />
<span>Capture system audio</span>
</label>
</div>
</div>
<section>
<h2>hotkeys</h2>
<label>
<span>start</span>
<HotkeyInput bind:value={cfg.hotkeys.start} placeholder="click to assign" />
</label>
<label>
<span>stop</span>
<HotkeyInput bind:value={cfg.hotkeys.stop} placeholder="click to assign" />
</label>
<label>
<span>pause</span>
<HotkeyInput bind:value={cfg.hotkeys.pause} placeholder="click to assign" />
</label>
</section>
{:else if activeTab === "export"}
<div class="tab-panel">
<div class="panel-head">
<h2>Export</h2>
<p class="panel-desc">Default format and encoding options</p>
</div>
<div class="field-list">
<label class="field">
<span class="field-label">Default format</span>
<select bind:value={cfg.export.default_format}>
<option value="gif">GIF</option>
<option value="webm">WebM</option>
<option value="mp4">MP4</option>
</select>
</label>
<section>
<h2>output</h2>
<label>
<span>save folder</span>
<div class="path-input">
<input
type="text"
placeholder="default: ./output next to the app"
value={cfg.output_dir ?? ""}
oninput={(e) => {
const v = (e.currentTarget as HTMLInputElement).value
if (cfg) cfg.output_dir = v.trim() ? v : null
}}
/>
<button class="small" onclick={pickOutputDir}>browse...</button>
</div>
</label>
</section>
<button class="advanced-toggle" onclick={() => showAdvanced = !showAdvanced} aria-expanded={showAdvanced}>
<svg width="10" height="10" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class:rotated={showAdvanced}>
<polyline points="2,3 5,6 8,3"/>
</svg>
Advanced codecs
</button>
<section>
<h2>updates</h2>
<label class="check">
<input type="checkbox" bind:checked={cfg.updates.check_on_launch} />
<span>check for updates on launch</span>
</label>
</section>
{#if showAdvanced}
<label class="field">
<span class="field-label">GIF dithering</span>
<select bind:value={cfg.export.gif_dither}>
<option value="floyd_steinberg">Floyd-Steinberg</option>
<option value="bayer">Bayer</option>
<option value="none">None</option>
</select>
</label>
<label class="field">
<span class="field-label">WebM codec</span>
<select bind:value={cfg.export.webm_codec}>
<option value="vp9">VP9 (default)</option>
<option value="av1">AV1 (smaller, slower)</option>
</select>
</label>
<label class="field">
<span class="field-label">MP4 codec</span>
<select bind:value={cfg.export.mp4_codec}>
<option value="h264">H.264 (default)</option>
<option value="h265">H.265 (smaller, less universal)</option>
</select>
</label>
{/if}
</div>
</div>
<div class="row">
<button class="primary" disabled={saving} onclick={save}>
{saving ? "saving..." : "save"}
</button>
<button onclick={onClose}>cancel</button>
{:else if activeTab === "hotkeys"}
<div class="tab-panel">
<div class="panel-head">
<h2>Hotkeys</h2>
<p class="panel-desc">Global keyboard shortcuts</p>
</div>
<div class="field-list">
<label class="field">
<span class="field-label">Start recording</span>
<HotkeyInput bind:value={cfg.hotkeys.start} placeholder="e.g. F9" />
</label>
<label class="field">
<span class="field-label">Stop recording</span>
<HotkeyInput bind:value={cfg.hotkeys.stop} placeholder="e.g. F10" />
</label>
<label class="field">
<span class="field-label">Pause / resume</span>
<HotkeyInput bind:value={cfg.hotkeys.pause} placeholder="e.g. F11" />
</label>
</div>
</div>
{:else if activeTab === "output"}
<div class="tab-panel">
<div class="panel-head">
<h2>Output</h2>
<p class="panel-desc">Where exported files are saved</p>
</div>
<div class="field-list">
<label class="field">
<span class="field-label">Save folder</span>
<div class="path-row">
<input type="text" class="path-input" placeholder="./output" value={cfg.output_dir ?? ""} oninput={(e) => { cfg!.output_dir = (e.currentTarget as HTMLInputElement).value.trim() || null }} />
<button class="btn-ghost" onclick={pickOutputDir}>Browse</button>
</div>
</label>
</div>
</div>
{:else if activeTab === "system"}
<div class="tab-panel">
<div class="panel-head">
<h2>System</h2>
<p class="panel-desc">Appearance and updates</p>
</div>
<div class="field-list">
<label class="field">
<span class="field-label">Theme</span>
<select bind:value={cfg.theme}>
<option value="dark">Dark</option>
<option value="light">Light</option>
</select>
</label>
<label class="field-check">
<input type="checkbox" bind:checked={cfg.updates.check_on_launch} />
<span>Check for updates on launch</span>
</label>
</div>
</div>
{/if}
{#if hotkeyWarnings.length > 0}
<div class="warn-block" role="alert">
{#each hotkeyWarnings as w}<p>{w}</p>{/each}
<div class="warn-actions">
<button class="btn-warn" onclick={save} disabled={saving}>Try again</button>
<button class="btn-ghost" onclick={onClose}>Cancel</button>
</div>
</div>
{:else}
<div class="panel-foot">
<button class="btn-primary" onclick={save} disabled={saving}>
{saving ? "Saving" : "Save changes"}
</button>
<button class="btn-ghost" onclick={onClose}>Cancel</button>
</div>
{/if}
</div>
</div>
{/if}
</main>
</div>
<style>
main {
padding: 2rem;
max-width: 720px;
margin: 0 auto;
}
header {
.settings {
min-height: 100vh;
background: var(--bg);
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
flex-direction: column;
}
header h1 {
.settings-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
height: 44px;
border-bottom: 1px solid var(--border);
background: var(--bg-2);
flex-shrink: 0;
}
.header-left {
display: flex;
align-items: center;
gap: 12px;
}
.back-btn {
display: grid; place-items: center;
width: 28px; height: 28px;
background: transparent;
border: 1px solid var(--border);
color: var(--text-3);
border-radius: var(--r-sm);
cursor: pointer;
transition: color 80ms, border-color 80ms;
}
.back-btn:hover { color: var(--text); border-color: var(--border-2); }
.settings-header h1 {
margin: 0;
font-size: 1.5rem;
font-size: 14px;
font-weight: 600;
color: var(--text);
letter-spacing: -0.01em;
}
section {
margin: 1.5rem 0;
padding-top: 1rem;
border-top: 1px solid #2a2a2a;
.settings-body {
flex: 1;
display: grid;
grid-template-columns: 160px 1fr;
max-width: 640px;
width: 100%;
margin: 0 auto;
min-height: 0;
}
h2 {
margin: 0 0 0.75rem;
font-size: 0.85rem;
color: #888;
font-weight: normal;
@media (max-width: 560px) {
.settings-body { grid-template-columns: 1fr; }
}
/* Tab nav */
.tab-nav {
display: flex;
flex-direction: column;
padding: 16px 8px;
gap: 2px;
border-right: 1px solid var(--border);
}
@media (max-width: 560px) {
.tab-nav {
flex-direction: row;
padding: 12px 16px;
border-right: none;
border-bottom: 1px solid var(--border);
overflow-x: auto;
}
}
.tab {
text-align: left;
padding: 7px 12px;
background: transparent;
border: 1px solid transparent;
color: var(--text-3);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 80ms;
white-space: nowrap;
}
.tab:hover { color: var(--text-2); background: var(--bg-2); }
.tab.active { background: var(--accent-dim); color: var(--accent); border-color: rgba(20, 184, 166, 0.15); }
/* Tab content */
.tab-content {
padding: 24px 28px;
display: flex;
flex-direction: column;
gap: 24px;
overflow: auto;
}
.tab-panel { display: flex; flex-direction: column; gap: 20px; }
.panel-head { display: flex; flex-direction: column; gap: 2px; }
.panel-head h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: var(--text);
letter-spacing: -0.01em;
}
.panel-desc {
margin: 0;
font-size: 12px;
color: var(--text-3);
}
.field-list { display: flex; flex-direction: column; gap: 14px; }
.field {
display: flex;
flex-direction: column;
gap: 6px;
}
.field-label {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.05em;
letter-spacing: 0.06em;
color: var(--text-3);
}
label {
display: grid;
grid-template-columns: 180px 1fr;
gap: 1rem;
.field-check {
display: flex;
align-items: center;
margin: 0.75rem 0;
font-size: 0.9rem;
gap: 10px;
font-size: 13px;
color: var(--text-2);
cursor: pointer;
}
label span {
color: #aaa;
.field-check input[type="checkbox"] {
width: 14px; height: 14px;
accent-color: var(--accent);
cursor: pointer;
}
label.check {
grid-template-columns: 20px 1fr;
}
select, input[type="text"] {
font: inherit;
padding: 0.4rem 0.6rem;
border: 1px solid #444;
background: #222;
color: inherit;
border-radius: 4px;
}
select:focus, input[type="text"]:focus {
select, .path-input {
padding: 8px 10px;
background: var(--bg-2);
border: 1px solid var(--border);
color: var(--text);
border-radius: var(--r-sm);
font-size: 13px;
outline: none;
border-color: #4a8;
}
.path-input {
display: grid;
grid-template-columns: 1fr auto;
gap: 0.4rem;
width: 100%;
}
.small {
padding: 0.25rem 0.5rem;
font-size: 0.8rem;
}
.row {
select:focus, .path-input:focus { border-color: var(--accent); }
select { cursor: pointer; font-family: var(--sans); }
.advanced-toggle {
display: flex;
gap: 0.5rem;
margin-top: 2rem;
}
button {
font: inherit;
padding: 0.5rem 1rem;
border: 1px solid #444;
background: transparent;
color: inherit;
cursor: pointer;
border-radius: 4px;
}
button:hover:not(:disabled) {
border-color: #888;
}
button.primary {
background: #4a8;
border-color: #4a8;
color: #111;
}
button.primary:disabled {
background: #333;
border-color: #333;
color: #666;
cursor: not-allowed;
}
button.back {
align-items: center;
gap: 6px;
background: transparent;
border: none;
padding: 0.25rem 0.5rem;
color: #aaa;
font-size: 0.9rem;
color: var(--text-3);
font-size: 12px;
font-family: var(--sans);
cursor: pointer;
padding: 4px 0;
transition: color 80ms;
width: fit-content;
}
button.back:hover {
.advanced-toggle:hover { color: var(--text-2); }
.advanced-toggle svg { transition: transform 150ms; }
.advanced-toggle svg.rotated { transform: rotate(180deg); }
.path-row { display: flex; gap: 6px; }
.path-input { flex: 1; font-family: var(--mono); font-size: 12px; }
.panel-foot {
display: flex;
gap: 10px;
padding-top: 8px;
border-top: 1px solid var(--border);
}
.btn-primary {
padding: 9px 22px;
background: var(--accent);
border: none;
color: var(--accent-text);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: background 80ms;
}
.btn-primary:hover:not(:disabled) { background: var(--accent-hover); }
.btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
.btn-ghost {
padding: 9px 18px;
background: transparent;
border: 1px solid var(--border-2);
color: var(--text-3);
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 13px;
cursor: pointer;
transition: border-color 80ms, color 80ms;
}
.btn-ghost:hover { border-color: var(--border-3); color: var(--text); }
.warn-block {
padding: 14px 16px;
background: var(--err-dim);
border: 1px solid var(--err-border);
border-radius: var(--r-sm);
display: flex;
flex-direction: column;
gap: 12px;
}
.warn-block p { margin: 0; font-size: 12px; color: var(--err); }
.warn-actions { display: flex; gap: 8px; }
.btn-warn {
padding: 8px 16px;
background: var(--err);
border: none;
color: #fff;
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: background 80ms;
}
.btn-warn:hover:not(:disabled) { background: var(--stop-hover); }
.btn-warn:disabled { opacity: 0.4; cursor: not-allowed; }
</style>
+100 -148
View File
@@ -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" } }
</script>
{#if info || phase === "ready-to-apply"}
<div class="banner">
<div class="text">
{#if phase === "ready-to-apply"}
<strong>update ready to apply</strong>
{#if info}
{#if info || phase === "ready"}
<div class="banner" role="status" aria-live="polite">
<div class="banner-main">
{#if phase === "ready"}
<span class="dot" style="background:var(--recording)"></span>
<span class="banner-text">
<span class="banner-label">Update ready</span>
{#if info}<span class="ver">v{info.version}</span>{/if}
</span>
<button class="btn" onclick={apply}>Apply</button>
<button class="btn ghost" onclick={dismiss}>Dismiss</button>
{:else if phase === "downloading"}
<span class="dot pulse"></span>
<span class="banner-text">
<span class="banner-label">Downloading</span>
{#if info}<span class="ver">v{info.version}</span>{/if}
{#if progress}
<span class="banner-hint">
{formatBytes(progress.downloaded)}{progress.total ? ` / ${formatBytes(progress.total)}` : ""}
</span>
{/if}
</span>
{:else if phase === "error"}
<span class="dot" style="background:var(--err)"></span>
<span class="banner-text">
<span class="banner-label">Update error</span>
{#if errMsg}<span class="banner-hint">{errMsg}</span>{/if}
</span>
<button class="btn ghost" onclick={dismiss}>Dismiss</button>
{:else if info}
<span class="dot pulse"></span>
<span class="banner-text">
<span class="banner-label">Update available</span>
<span class="ver">v{info.version}</span>
{/if}
<p class="body">click apply to swap and restart, or dismiss to keep the current version.</p>
{:else if phase === "downloading"}
<strong>downloading update...</strong>
{#if info}<span class="ver">v{info.version}</span>{/if}
{#if progress}
<p class="body">
{formatBytes(progress.downloaded)}
{#if progress.total} / {formatBytes(progress.total)}{/if}
</p>
{/if}
{:else if phase === "error"}
<strong>update error</strong>
<p class="body">{errMsg}</p>
{:else if info}
<strong>update available</strong>
<span class="ver">v{info.version}</span>
<span class="from">(you have v{info.current_version})</span>
{#if bodyPreview}
<p class="body">{bodyPreview}{info.body.length > 140 ? "..." : ""}</p>
{/if}
{/if}
</div>
<div class="actions">
{#if phase === "ready-to-apply"}
<button class="primary" onclick={apply}>apply now</button>
<button onclick={dismiss}>dismiss</button>
{:else if phase === "downloading"}
<span class="muted">working...</span>
{:else if phase === "error"}
<button onclick={dismiss}>dismiss</button>
{:else if info}
<span class="from">v{info.current_version}</span>
</span>
{#if info.download_url}
<button class="primary" onclick={download}>download</button>
<button class="btn" onclick={download}>Download</button>
{/if}
<button onclick={viewRelease}>view release</button>
<button onclick={dismiss}>dismiss</button>
<button class="btn ghost" onclick={viewRelease}>Notes</button>
<button class="btn ghost" onclick={dismiss}>Dismiss</button>
{/if}
</div>
</div>
@@ -125,66 +83,60 @@
<style>
.banner {
background: linear-gradient(180deg, #1f2e2a, #1a2522);
border-bottom: 1px solid #4a8;
padding: 0.75rem 1.25rem;
background: var(--bg-2);
border-bottom: 1px solid var(--border);
}
.banner-main {
display: flex;
gap: 1rem;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 8px 20px;
flex-wrap: wrap;
}
.text {
flex: 1;
min-width: 240px;
color: #d8eee5;
font-size: 0.9rem;
}
.ver {
color: #4a8;
font-weight: 600;
margin: 0 0.4rem;
}
.from {
color: #7a8e88;
font-size: 0.8rem;
}
.body {
margin: 0.3rem 0 0;
color: #9eb3ac;
font-size: 0.8rem;
line-height: 1.4;
}
.actions {
display: flex;
gap: 0.4rem;
.dot {
width: 6px; height: 6px;
border-radius: 50%;
background: var(--accent);
flex-shrink: 0;
}
.pulse { animation: blink 2s ease-in-out infinite; }
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.3} }
.banner-text {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--text-2);
flex: 1;
min-width: 160px;
}
.muted {
color: #7a8e88;
font-size: 0.85rem;
}
button {
font: inherit;
padding: 0.4rem 0.8rem;
border: 1px solid #2a3a35;
background: transparent;
color: #d8eee5;
.banner-label { font-weight: 500; color: var(--text); }
.ver { font-family: var(--mono); font-size: 11px; color: var(--accent); }
.from { font-size: 11px; color: var(--text-3); }
.banner-hint { font-size: 11px; color: var(--text-3); }
.btn {
padding: 4px 12px;
border-radius: var(--r-sm);
font-family: var(--sans);
font-size: 11px;
font-weight: 500;
cursor: pointer;
border-radius: 4px;
font-size: 0.85rem;
transition: all 80ms;
white-space: nowrap;
border: 1px solid transparent;
background: var(--accent);
color: var(--accent-text);
}
button:hover {
border-color: #4a8;
}
button.primary {
background: #4a8;
border-color: #4a8;
color: #0e1a16;
}
button.primary:hover {
background: #5b9;
border-color: #5b9;
.btn:hover { background: var(--accent-hover); }
.btn.ghost {
background: transparent;
border-color: var(--border-2);
color: var(--text-2);
}
.btn.ghost:hover { border-color: var(--border-3); color: var(--text); }
</style>
+27 -1
View File
@@ -38,12 +38,15 @@ export type UpdatesConfig = {
check_on_launch: boolean
}
export type Theme = "dark" | "light"
export type Config = {
export: ExportConfig
capture: CaptureConfig
hotkeys: HotkeyConfig
updates: UpdatesConfig
output_dir: string | null
theme: Theme
}
export type DownloadProgress = {
@@ -109,6 +112,7 @@ export type ExportRequest = {
trim_start_secs?: number | null
trim_end_secs?: number | null
output_path?: string | null
crop?: CaptureRect | null
}
export type ExportResult = {
@@ -116,10 +120,28 @@ export type ExportResult = {
size_bytes: number
}
export type HotkeyRegistrationResult = {
start_ok: boolean | null
stop_ok: boolean | null
pause_ok: boolean | null
}
export type SaveConfigResult = {
hotkey_result: HotkeyRegistrationResult
}
export type EncodeProgress = {
pass: number
total_passes: number
percent: number
}
export type AudioFailed = string
export const api = {
getStatus: () => invoke<AppStatus>("get_status"),
getConfig: () => invoke<Config>("get_config"),
saveConfig: (config: Config) => invoke<void>("save_config", { config }),
saveConfig: (config: Config) => invoke<SaveConfigResult>("save_config", { config }),
downloadFfmpeg: () => invoke<void>("download_ffmpeg"),
onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise<UnlistenFn> =>
listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)),
@@ -158,6 +180,10 @@ export const api = {
listen<UpdateDownloadProgress>("update-download-progress", (e) =>
handler(e.payload),
),
onEncodeProgress: (handler: (p: EncodeProgress) => void): Promise<UnlistenFn> =>
listen<EncodeProgress>("encode-progress", (e) => handler(e.payload)),
onAudioFailed: (handler: (msg: string) => void): Promise<UnlistenFn> =>
listen<string>("audio-failed", (e) => handler(e.payload)),
}
export function formatBytes(n: number): string {
+1
View File
@@ -1,4 +1,5 @@
import { mount } from "svelte"
import "./app.css"
import Overlay from "./lib/Overlay.svelte"
const app = mount(Overlay, {
+1
View File
@@ -1,4 +1,5 @@
import { mount } from "svelte"
import "./app.css"
import Picker from "./lib/Picker.svelte"
const app = mount(Picker, {