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-dialog = "2"
tauri-plugin-global-shortcut = "2" tauri-plugin-global-shortcut = "2"
windows-capture = "2.0" 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" cpal = "0.16"
tokio = { version = "1.47", features = ["full"] } tokio = { version = "1.47", features = ["full"] }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
+222 -48
View File
@@ -1,77 +1,251 @@
use std::fs::File; use std::fs::File;
use std::io::{BufWriter, Write}; use std::io::{BufWriter, Write};
use std::path::PathBuf; 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 anyhow::{bail, Context, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; 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 { pub struct AudioSession {
_stream: cpal::Stream, thread: Option<JoinHandle<Result<()>>>,
pub output_path: PathBuf, running: Arc<AtomicBool>,
output_path: PathBuf,
pub sample_rate: u32, pub sample_rate: u32,
pub channels: u16, pub channels: u16,
writer: Arc<Mutex<Option<BufWriter<File>>>>,
} }
pub fn start(output_path: PathBuf) -> Result<AudioSession> { pub fn start(output_path: PathBuf) -> Result<AudioSession> {
let host = cpal::default_host(); let running = Arc::new(AtomicBool::new(true));
let device = host let running_clone = running.clone();
.default_output_device() let path_clone = output_path.clone();
.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();
if let Some(parent) = output_path.parent() { let (init_tx, init_rx) = std::sync::mpsc::channel();
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 stream = device let thread = thread::spawn(move || {
.build_input_stream( let result = capture_thread(running_clone, path_clone, init_tx);
&stream_config, if let Err(ref e) = result {
move |data: &[f32], _info: &cpal::InputCallbackInfo| { tracing::error!("audio capture thread ended with error: {e:#}");
if let Ok(mut guard) = writer_clone.lock() { }
if let Some(w) = guard.as_mut() { result
let bytes: &[u8] = bytemuck_cast(data); });
let _ = w.write_all(bytes);
} let (sample_rate, channels) = init_rx
} .recv_timeout(std::time::Duration::from_secs(3))
}, .context("audio capture thread failed to initialize within 3 seconds")?
|err| tracing::warn!("audio capture error: {err}"), .context("audio capture initialization failed")?;
None,
)
.context("building input stream")?;
stream.play().context("starting audio stream")?;
Ok(AudioSession { Ok(AudioSession {
_stream: stream, thread: Some(thread),
running,
output_path, output_path,
sample_rate, sample_rate,
channels, channels,
writer,
}) })
} }
impl AudioSession { impl AudioSession {
pub fn stop(self) -> Result<PathBuf> { pub fn stop(self) -> Result<PathBuf> {
drop(self._stream); self.running.store(false, Ordering::Relaxed);
if let Ok(mut guard) = self.writer.lock() { if let Some(t) = self.thread {
if let Some(mut w) = guard.take() { let _ = t.join();
let _ = w.flush();
}
} }
Ok(self.output_path) Ok(self.output_path)
} }
} }
fn bytemuck_cast(data: &[f32]) -> &[u8] { fn parse_format(fmt: &WAVEFORMATEX) -> Result<(u32, u16, u16, bool)> {
let len_bytes = std::mem::size_of_val(data); // WAVEFORMATEX is repr(packed); copy fields to avoid unaligned ref UB.
unsafe { std::slice::from_raw_parts(data.as_ptr() as *const u8, len_bytes) } 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] = &[ const SOURCES: &[Source] = &[
Source { Source {
name: "GyanD", 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", asset_name_suffix: "full_build.7z",
kind: ArchiveKind::SevenZ, kind: ArchiveKind::SevenZ,
}, },
@@ -60,6 +60,7 @@ const SOURCES: &[Source] = &[
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct GithubRelease { struct GithubRelease {
tag_name: String,
assets: Vec<GithubAsset>, assets: Vec<GithubAsset>,
} }
@@ -67,8 +68,6 @@ struct GithubRelease {
struct GithubAsset { struct GithubAsset {
name: String, name: String,
browser_download_url: String, browser_download_url: String,
#[serde(default)]
digest: Option<String>,
} }
pub async fn download<F>(app_dir: &Path, mut on_progress: F) -> Result<()> 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"))) .user_agent(concat!("ByteSize/", env!("CARGO_PKG_VERSION")))
.build()?; .build()?;
let asset = pick_asset(&client, source).await?; let (asset, version) = pick_asset(&client, source).await?;
let expected = parse_sha256_digest(&asset.digest) // GyanD publishes a .sha256 file alongside each release.
.with_context(|| format!("parsing digest for {}", asset.name))?; // 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) let archive = if let Some(ref hash) = expected {
.await download_verified(&client, &asset.browser_download_url, hash, on_progress)
.with_context(|| format!("downloading {}", asset.browser_download_url))?; .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 { match source.kind {
ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?, ArchiveKind::SevenZ => extract_ffmpeg_from_7z(&archive, dest)?,
@@ -119,7 +135,65 @@ where
Ok(()) 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 let resp = client
.get(source.release_api_url) .get(source.release_api_url)
.header("Accept", "application/vnd.github+json") .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 body = resp.text().await?;
let release: GithubRelease = let release: GithubRelease =
serde_json::from_str(&body).context("parsing release metadata")?; 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 .assets
.into_iter() .into_iter()
.find(|a| a.name.ends_with(source.asset_name_suffix)) .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", "no asset matching '*{}' in release",
source.asset_name_suffix source.asset_name_suffix
) )
}) })?;
} Ok((asset, version))
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)
} }
async fn download_verified<F>( 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::process::{Child, ChildStdin, Command, Stdio};
use std::time::Instant; use std::time::Instant;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, bail, Context, Result};
use windows_capture::capture::{ use windows_capture::capture::{
CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler, CaptureControl, Context as CaptureContext, GraphicsCaptureApiHandler,
}; };
@@ -114,12 +114,14 @@ impl GraphicsCaptureApiHandler for CaptureHandler {
self.scratch.clear(); self.scratch.clear();
let bytes = buf.as_nopadding_buffer(&mut self.scratch); let bytes = buf.as_nopadding_buffer(&mut self.scratch);
let expected = (self.width as usize) * (self.height as usize) * 4; let expected = (self.width as usize) * (self.height as usize) * 4;
let slice = if bytes.len() >= expected { if bytes.len() < expected {
&bytes[..expected] tracing::warn!("frame buffer too small: got {} bytes, expected {}", bytes.len(), expected);
} else { return Ok(());
bytes }
}; stdin.write_all(&bytes[..expected]).map_err(|e| {
let _ = stdin.write_all(slice); tracing::error!("ffmpeg stdin write failed: {e} — encoder may have crashed");
anyhow!("ffmpeg encoder stopped unexpectedly: {e}")
})?;
Ok(()) Ok(())
} }
} }
@@ -153,6 +155,22 @@ pub fn primary_monitor_dims() -> Result<(u32, u32)> {
Ok((w & !1, h & !1)) 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( pub fn start(
output_path: PathBuf, output_path: PathBuf,
ffmpeg_path: PathBuf, ffmpeg_path: PathBuf,
@@ -161,7 +179,19 @@ pub fn start(
crop: Option<CaptureRect>, crop: Option<CaptureRect>,
fps: u32, fps: u32,
) -> Result<CaptureSession> { ) -> 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 let raw_width = monitor
.width() .width()
.map_err(|e| anyhow!("monitor width: {e:?}"))?; .map_err(|e| anyhow!("monitor width: {e:?}"))?;
@@ -238,6 +268,11 @@ impl CaptureSession {
self.control self.control
.stop() .stop()
.map_err(|e| anyhow!("capture stop: {e}"))?; .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) Ok(self.output_path)
} }
} }
+81 -4
View File
@@ -3,6 +3,14 @@ use std::path::{Path, PathBuf};
use anyhow::Result; use anyhow::Result;
use serde::{Deserialize, Serialize}; 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)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config { pub struct Config {
#[serde(default)] #[serde(default)]
@@ -15,6 +23,8 @@ pub struct Config {
pub updates: UpdatesConfig, pub updates: UpdatesConfig,
#[serde(default)] #[serde(default)]
pub output_dir: Option<PathBuf>, pub output_dir: Option<PathBuf>,
#[serde(default)]
pub theme: Theme,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -44,32 +54,36 @@ pub struct UpdatesConfig {
pub check_on_launch: bool, 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")] #[serde(rename_all = "lowercase")]
pub enum Format { pub enum Format {
#[default]
Gif, Gif,
Webm, Webm,
Mp4, Mp4,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum GifDither { pub enum GifDither {
#[default]
FloydSteinberg, FloydSteinberg,
Bayer, Bayer,
None, None,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum WebmCodec { pub enum WebmCodec {
#[default]
Vp9, Vp9,
Av1, Av1,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")] #[serde(rename_all = "lowercase")]
pub enum Mp4Codec { pub enum Mp4Codec {
#[default]
H264, H264,
H265, H265,
} }
@@ -82,6 +96,7 @@ impl Default for Config {
hotkeys: HotkeyConfig::default(), hotkeys: HotkeyConfig::default(),
updates: UpdatesConfig::default(), updates: UpdatesConfig::default(),
output_dir: None, output_dir: None,
theme: Theme::Dark,
} }
} }
} }
@@ -143,3 +158,65 @@ impl Config {
pub fn config_path(app_dir: &Path) -> PathBuf { pub fn config_path(app_dir: &Path) -> PathBuf {
app_dir.join("config.toml") 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::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::Command; use std::process::Command;
use std::sync::mpsc::Sender;
use std::thread;
use anyhow::{anyhow, bail, Context, Result}; use anyhow::{anyhow, bail, Context, Result};
@@ -9,7 +11,19 @@ use crate::clicks::Click;
use crate::config::{Format, GifDither, Mp4Codec, WebmCodec}; use crate::config::{Format, GifDither, Mp4Codec, WebmCodec};
use crate::CaptureRect; 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)] #[derive(Debug, Clone)]
pub struct TranscodeRequest { pub struct TranscodeRequest {
@@ -29,8 +43,13 @@ pub struct TranscodeRequest {
pub trim_start_secs: Option<f64>, pub trim_start_secs: Option<f64>,
pub trim_end_secs: Option<f64>, pub trim_end_secs: Option<f64>,
pub clicks: Vec<Click>, 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> { fn click_filters(req: &TranscodeRequest) -> Option<String> {
if req.clicks.is_empty() { if req.clicks.is_empty() {
return None; return None;
@@ -38,7 +57,15 @@ fn click_filters(req: &TranscodeRequest) -> Option<String> {
let size = 24i32; let size = 24i32;
let half = size / 2; let half = size / 2;
let mut parts: Vec<String> = Vec::new(); 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 x = click.x - half;
let y = click.y - half; let y = click.y - half;
let t1 = (click.time_secs - 0.05).max(0.0); let t1 = (click.time_secs - 0.05).max(0.0);
@@ -206,9 +233,8 @@ fn two_pass_video(
req: &TranscodeRequest, req: &TranscodeRequest,
video_codec: &str, video_codec: &str,
audio_codec: &str, audio_codec: &str,
container: &str, _container: &str,
) -> Result<()> { ) -> Result<()> {
let _ = container;
let bitrate_kbps = video_bitrate_kbps(req)?; let bitrate_kbps = video_bitrate_kbps(req)?;
let bitrate = format!("{bitrate_kbps}k"); let bitrate = format!("{bitrate_kbps}k");
@@ -245,7 +271,16 @@ fn two_pass_video(
.arg("-an") .arg("-an")
.args(["-f", "null"]) .args(["-f", "null"])
.arg(null_target); .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); let mut pass2 = Command::new(ffmpeg);
pass2 pass2
@@ -270,7 +305,7 @@ fn two_pass_video(
pass2.arg("-an"); pass2.arg("-an");
} }
pass2.arg(&req.output); 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); cleanup_pass_logs(&log_stem);
Ok(()) Ok(())
@@ -356,7 +391,15 @@ fn encode_gif(ffmpeg: &Path, req: &TranscodeRequest) -> Result<()> {
.args(["-lavfi", &use_filter]) .args(["-lavfi", &use_filter])
.args(["-loop", "0"]) .args(["-loop", "0"])
.arg(&req.output); .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); let _ = std::fs::remove_file(&palette_path);
Ok(()) Ok(())
@@ -533,6 +576,44 @@ pub fn concat_segments(ffmpeg: &Path, segments: &[PathBuf], output: &Path) -> Re
} }
fn run(cmd: &mut Command, label: &str) -> Result<()> { 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; use std::process::Stdio;
let mut printable = OsString::from(label); let mut printable = OsString::from(label);
@@ -544,14 +625,169 @@ fn run(cmd: &mut Command, label: &str) -> Result<()> {
} }
tracing::debug!("{}", printable.to_string_lossy()); tracing::debug!("{}", printable.to_string_lossy());
cmd.stdout(Stdio::null()).stderr(Stdio::piped()); let mut child = cmd
let output = cmd .stdout(Stdio::null())
.output() .stderr(Stdio::piped())
.spawn()
.with_context(|| format!("spawning ffmpeg for {label}"))?; .with_context(|| format!("spawning ffmpeg for {label}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr); // Spawn a thread to monitor stderr and emit progress.
let tail: String = stderr.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect::<Vec<_>>().join("\n"); let stderr = child.stderr.take();
bail!("ffmpeg {label} exited with {}: {}", output.status, tail); 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::path::{Path, PathBuf};
use std::sync::Mutex; use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -19,7 +18,7 @@ use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState};
use std::str::FromStr; use std::str::FromStr;
use crate::bootstrap::FfmpegStatus; use crate::bootstrap::FfmpegStatus;
use crate::config::{Config, Format, GifDither, Mp4Codec, WebmCodec}; use crate::config::{Config, Format};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CaptureRect { pub struct CaptureRect {
@@ -88,76 +87,19 @@ fn output_dir(app_dir: &Path, cfg: &Config) -> PathBuf {
} }
fn timestamp_slug() -> String { fn timestamp_slug() -> String {
let now = SystemTime::now() use windows::Win32::System::SystemInformation::GetLocalTime;
.duration_since(UNIX_EPOCH) let st = unsafe { GetLocalTime() };
.map(|d| d.as_secs())
.unwrap_or(0);
let local = chrono_like(now);
format!( format!(
"{:04}{:02}{:02}-{:02}{:02}{:02}", "{: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 { fn ext_for(format: Format) -> &'static str {
match format { match format {
Format::Gif => "gif", Format::Gif => "gif",
@@ -190,37 +132,61 @@ fn parse_shortcut(s: &str) -> Option<Shortcut> {
Shortcut::from_str(s).ok() 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 = app.global_shortcut();
let _ = gs.unregister_all(); 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) { let start_ok = cfg
registered.push((s, "start")); .hotkeys
} .start
if let Some(s) = cfg.hotkeys.stop.as_deref().and_then(parse_shortcut) { .as_deref()
registered.push((s, "stop")); .and_then(parse_shortcut)
} .map(|sc| gs.register(sc).is_ok());
if let Some(s) = cfg.hotkeys.pause.as_deref().and_then(parse_shortcut) { let stop_ok = cfg
registered.push((s, "pause")); .hotkeys
} .stop
for (sc, _) in &registered { .as_deref()
if let Err(e) = gs.register(*sc) { .and_then(parse_shortcut)
tracing::warn!("registering shortcut failed: {e}"); .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] #[tauri::command]
fn save_config( fn save_config(
app: AppHandle, app: AppHandle,
state: State<'_, AppState>, state: State<'_, AppState>,
config: Config, config: Config,
) -> Result<(), String> { ) -> Result<SaveConfigResult, String> {
let path = config::config_path(&state.app_dir); let path = config::config_path(&state.app_dir);
config.save(&path).map_err(|e| format!("{e:#}"))?; config.save(&path).map_err(|e| format!("{e:#}"))?;
*state.config.lock().expect("config mutex") = config.clone(); *state.config.lock().expect("config mutex") = config.clone();
register_hotkeys(&app, &config); let hotkey_result = register_hotkeys(&app, &config);
Ok(()) Ok(SaveConfigResult { hotkey_result })
} }
#[derive(Clone, Serialize)] #[derive(Clone, Serialize)]
@@ -320,6 +286,31 @@ fn clear_temp_segments(app_dir: &Path) {
let _ = std::fs::remove_file(temp.join("audio-concat.pcm")); 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) { fn set_overlay_clickthrough(app: &AppHandle, enabled: bool) {
if let Some(win) = app.get_webview_window("overlay") { if let Some(win) = app.get_webview_window("overlay") {
let _ = win.set_ignore_cursor_events(enabled); let _ = win.set_ignore_cursor_events(enabled);
@@ -370,6 +361,7 @@ fn start_capture(
Ok(s) => Some(s), Ok(s) => Some(s),
Err(e) => { Err(e) => {
tracing::warn!("audio capture failed to start: {e:#}"); tracing::warn!("audio capture failed to start: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None None
} }
} }
@@ -461,7 +453,7 @@ fn pause_capture(state: State<'_, AppState>) -> Result<(), String> {
} }
#[tauri::command] #[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"); let slot = state.capture.lock().expect("capture mutex");
if slot.is_some() { if slot.is_some() {
@@ -496,6 +488,7 @@ fn resume_capture(state: State<'_, AppState>) -> Result<(), String> {
Ok(s) => Some(s), Ok(s) => Some(s),
Err(e) => { Err(e) => {
tracing::warn!("audio resume failed: {e:#}"); tracing::warn!("audio resume failed: {e:#}");
let _ = app.emit("audio-failed", e.to_string());
None None
} }
} }
@@ -590,6 +583,13 @@ fn stop_capture(app: AppHandle, state: State<'_, AppState>) -> Result<RecordedCl
let audio_concat = temp.join("audio-concat.pcm"); let audio_concat = temp.join("audio-concat.pcm");
encode::concat_pcm(&ss.audio_segments, &audio_concat) encode::concat_pcm(&ss.audio_segments, &audio_concat)
.map_err(|e| format!("audio concat: {e:#}"))?; .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( encode::mux_with_audio(
&ffmpeg, &ffmpeg,
&video_concat, &video_concat,
@@ -641,6 +641,8 @@ pub struct ExportRequest {
pub trim_end_secs: Option<f64>, pub trim_end_secs: Option<f64>,
#[serde(default)] #[serde(default)]
pub output_path: Option<String>, pub output_path: Option<String>,
#[serde(default)]
pub crop: Option<CaptureRect>,
} }
#[tauri::command] #[tauri::command]
@@ -679,19 +681,20 @@ fn render_preview(
return Err("ffmpeg.exe not found".to_string()); return Err("ffmpeg.exe not found".to_string());
} }
let target_width: u32 = match request.format { let target_width: u32 = if request.format == Format::Gif {
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 frames = (request.fps as f64 * clip.duration_secs).max(1.0);
let budget = (request.target_bytes as f64) / (frames * 0.5); let budget = (request.target_bytes as f64) / (frames * 0.5);
let aspect = if clip.height == 0 { let aspect = if clip.height == 0 {
16.0 / 9.0 16.0 / 9.0
} else { } else {
clip.width as f64 / clip.height as f64 clip.width as f64 / clip.height as f64
}; };
let w = (budget * aspect).sqrt(); let w = (budget * aspect).sqrt();
(w.clamp(120.0, clip.width as f64) as u32 / 2) * 2 (w.clamp(120.0, clip.width as f64) as u32 / 2) * 2
} } else {
_ => clip.width, // 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"); let preview_path = temp_dir(&state.app_dir).join("preview.png");
@@ -727,9 +730,98 @@ pub struct ExportResult {
pub size_bytes: u64, 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; 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> { fn mark_overlay_excluded_from_capture(win: &tauri::WebviewWindow) -> Result<(), String> {
use windows::Win32::Foundation::HWND; use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{ 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())?; .ok_or_else(|| "overlay window not found".to_string())?;
win.show().map_err(|e| e.to_string())?; win.show().map_err(|e| e.to_string())?;
let _ = mark_overlay_excluded_from_capture(&win); let _ = mark_overlay_excluded_from_capture(&win);
let _ = apply_overlay_region(&win);
win.set_focus().map_err(|e| e.to_string()) 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 = let final_h =
height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0); height as f64 + OVERLAY_TITLEBAR_LOGICAL_PX + (OVERLAY_BORDER_LOGICAL_PX * 2.0);
win.set_size(Size::Logical(LogicalSize::new(final_w, final_h))) 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] #[tauri::command]
@@ -815,7 +910,7 @@ fn open_window_picker(
picker picker
.set_position(Position::Physical(PhysicalPosition::new(0, 0))) .set_position(Position::Physical(PhysicalPosition::new(0, 0)))
.map_err(|e| e.to_string())?; .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); let _ = picker.set_always_on_top(true);
picker.show().map_err(|e| e.to_string())?; picker.show().map_err(|e| e.to_string())?;
if let Ok(h) = picker.hwnd() { 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] #[tauri::command]
fn set_overlay_to_window( fn set_overlay_to_window(
app: AppHandle, app: AppHandle,
@@ -906,7 +1029,11 @@ fn set_overlay_to_window(
let win = app let win = app
.get_webview_window("overlay") .get_webview_window("overlay")
.ok_or_else(|| "overlay window not found".to_string())?; .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 border_phys = (OVERLAY_BORDER_LOGICAL_PX * scale).round() as i32;
let titlebar_phys = (OVERLAY_TITLEBAR_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}"))?; .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); let _ = (visible_left, visible_top, visible_w, visible_h, scale, border_phys, titlebar_phys);
Ok(()) Ok(())
} }
@@ -1051,7 +1179,7 @@ fn open_url(url: String) -> Result<(), String> {
} }
#[tauri::command] #[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 cfg = state.config.lock().expect("config mutex").clone();
let clip = state let clip = state
.last_clip .last_clip
@@ -1125,14 +1253,35 @@ fn export(state: State<'_, AppState>, request: ExportRequest) -> Result<ExportRe
webm_codec: cfg.export.webm_codec, webm_codec: cfg.export.webm_codec,
mp4_codec: cfg.export.mp4_codec, mp4_codec: cfg.export.mp4_codec,
scratch_dir: temp_dir(&state.app_dir), scratch_dir: temp_dir(&state.app_dir),
crop: None, crop: request.crop,
deleted_frame_indices: request.deleted_frame_indices, deleted_frame_indices: request.deleted_frame_indices,
trim_start_secs: trim_start, trim_start_secs: trim_start,
trim_end_secs: trim_end, trim_end_secs: trim_end,
clicks: transformed_clicks, 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) let size_bytes = std::fs::metadata(&out_path)
.map(|m| m.len()) .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() { pub fn run() {
tracing_subscriber::fmt::init(); tracing_subscriber::fmt::init();
@@ -1237,7 +1380,8 @@ pub fn run() {
let cfg = st.config.lock().expect("config mutex").clone(); let cfg = st.config.lock().expect("config mutex").clone();
(cfg.updates.check_on_launch, cfg) (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 { if check_on_launch {
let handle = app.handle().clone(); let handle = app.handle().clone();
tauri::async_runtime::spawn(async move { 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); c.resize(max, 0);
l > c 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, "csp": null,
"assetProtocol": { "assetProtocol": {
"enable": true, "enable": true,
"scope": ["**/*"] "scope": ["$APPDIR/**", "$TEMP/**"]
} }
} }
}, },
+31 -13
View File
@@ -17,11 +17,16 @@
let status: AppStatus let status: AppStatus
try { try {
status = await api.getStatus() status = await api.getStatus()
} catch (e) { } catch {
console.error("get_status failed", e)
view = "bootstrap" view = "bootstrap"
return 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" if (status.ffmpeg === "missing") view = "bootstrap"
else if (status.needs_first_run) view = "first-run" else if (status.needs_first_run) view = "first-run"
else view = "main" else view = "main"
@@ -32,14 +37,27 @@
<UpdateBanner /> <UpdateBanner />
{#if view === "loading"} <div class="view-stage" class:shift={view !== "loading"}>
<Loading /> {#if view === "loading"}
{:else if view === "bootstrap"} <Loading />
<Bootstrap onReady={refresh} /> {:else if view === "bootstrap"}
{:else if view === "first-run"} <Bootstrap onReady={refresh} />
<FirstRun onDone={refresh} /> {:else if view === "first-run"}
{:else if view === "settings"} <FirstRun onDone={refresh} />
<Settings onClose={() => view = "main"} /> {:else if view === "settings"}
{:else} <Settings onClose={() => view = "main"} />
<Main onSettings={() => view = "settings"} /> {:else}
{/if} <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; 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; box-sizing: border-box;
} }
html {
font-family: var(--sans);
font-size: 14px;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body { body {
margin: 0; margin: 0;
background: var(--bg);
color: var(--text);
min-height: 100vh; 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() let { onReady }: { onReady: () => void } = $props()
type Phase = "idle" | "downloading" | "error" type Phase = "idle" | "downloading" | "error"
let phase: Phase = $state("idle") let phase: Phase = $state("idle")
let progress: DownloadProgress | null = $state(null) let progress = $state<DownloadProgress | null>(null)
let errMsg: string | null = $state(null) let errMsg = $state<string | null>(null)
async function start() { async function start() {
phase = "downloading" phase = "downloading"; errMsg = null; progress = null
errMsg = null const unlisten = await api.onFfmpegProgress((p) => { progress = p })
progress = null
const unlisten = await api.onFfmpegProgress((p) => {
progress = p
})
try { try {
await api.downloadFfmpeg() await api.downloadFfmpeg()
unlisten() unlisten()
@@ -27,115 +23,216 @@
} }
</script> </script>
<main> <div class="stage">
<header> <div class="card">
<h1>ByteSize</h1> <div class="card-head">
<p class="sub">set up encoder</p> <div class="logo">BYTESIZE</div>
</header> <div class="tag">encoder setup</div>
</div>
{#if phase === "idle"} {#if phase === "idle"}
<p> <div class="body">
ByteSize needs ffmpeg to encode video. The download is around 30 MB and <p class="copy">
is verified against a published SHA-256 checksum. ByteSize needs <strong>ffmpeg</strong> to encode video. Download is ~30 MB and verified against a published SHA-256 checksum.
</p> </p>
<div class="row"> <button class="btn-primary" onclick={start}>Download ffmpeg</button>
<button class="primary" onclick={start}>download ffmpeg</button> <p class="manual">
</div> Already have ffmpeg? Drop <code>ffmpeg.exe</code> into the <code>bin/</code> folder, then
<p class="hint"> <button class="link" onclick={onReady}>use it</button>.
Already have ffmpeg? Drop <code>ffmpeg.exe</code> into the </p>
<code>bin/</code> folder next to the app, then click below. </div>
</p>
<div class="row"> {:else if phase === "downloading"}
<button onclick={onReady}>i added it manually</button> <div class="body">
</div> <p class="status">Downloading ffmpeg</p>
{:else if phase === "downloading"} {#if progress?.total}
<p>downloading ffmpeg...</p> <div class="track">
<progress <div class="fill" style="width:{Math.min(100, (progress.downloaded / progress.total) * 100)}%"></div>
value={progress?.downloaded ?? 0} </div>
max={progress?.total ?? undefined} <p class="prog-text">
></progress> {formatBytes(progress.downloaded)} / {formatBytes(progress.total)}
<p class="hint"> </p>
{#if progress && progress.total} {:else if progress}
{formatBytes(progress.downloaded)} / {formatBytes(progress.total)} <p class="prog-text">{formatBytes(progress.downloaded)} downloaded</p>
{:else if progress} {:else}
{formatBytes(progress.downloaded)} downloaded <p class="prog-text">Connecting</p>
{/if} {/if}
</p> </div>
{:else}
<p class="err">download failed</p> {:else}
<pre>{errMsg}</pre> <div class="body">
<div class="row"> <div class="err" role="alert">
<button onclick={start}>retry</button> <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round">
<button onclick={onReady}>i added it manually</button> <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"/>
</div> </svg>
{/if} Download failed
</main> </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> <style>
main { .stage {
padding: 2rem; min-height: 100vh;
max-width: 560px; display: grid;
margin: 0 auto; place-items: center;
padding: 24px;
background: var(--bg);
} }
header h1 {
margin: 0 0 0.25rem; .card {
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 {
width: 100%; 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; .card-head {
padding: 0.75rem; padding: 28px 24px 20px;
border-radius: 4px; border-bottom: 1px solid var(--border);
overflow-x: auto; text-align: center;
font-size: 0.8rem;
color: #ec9a9a;
} }
.err {
color: #ec9a9a; .logo {
font-family: var(--mono);
font-size: 13px;
font-weight: 500;
letter-spacing: 0.12em;
color: var(--accent);
} }
button {
font: inherit; .tag {
padding: 0.5rem 1rem; margin-top: 6px;
border: 1px solid #444; font-size: 12px;
background: transparent; color: var(--text-3);
color: inherit; 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; cursor: pointer;
border-radius: 4px; transition: background 80ms;
} }
button:hover { .btn-primary:hover { background: var(--accent-hover); }
border-color: #888;
.manual {
margin: 0;
font-size: 12px;
color: var(--text-3);
text-align: center;
line-height: 1.5;
} }
button.primary {
background: #4a8; .manual code {
border-color: #4a8; font-family: var(--mono);
color: #111; font-size: 11px;
color: var(--text-2);
background: var(--bg-3);
padding: 1px 5px;
border-radius: var(--r-sm);
} }
button.primary:hover {
background: #5b9; .link {
border-color: #5b9; 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> </style>
+147 -89
View File
@@ -5,121 +5,179 @@
let { onDone }: { onDone: () => void } = $props() let { onDone }: { onDone: () => void } = $props()
let start: string | null = $state(null) 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 pause: string | null = $state(null)
let saving: boolean = $state(false) let saving: boolean = $state(false)
let warnings: string[] = $state([])
async function save() { async function save() {
saving = true saving = true
warnings = []
try { try {
const cfg = await api.getConfig() const cfg = await api.getConfig()
cfg.hotkeys.start = start cfg.hotkeys.start = start
cfg.hotkeys.stop = stop cfg.hotkeys.stop = stop
cfg.hotkeys.pause = pause cfg.hotkeys.pause = pause
await api.saveConfig(cfg) const result = await api.saveConfig(cfg)
onDone() const failed: string[] = []
} finally { if (result.hotkey_result.start_ok === false) failed.push("start")
saving = false 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) let valid = $derived(!!start && !!stop && !!pause)
</script> </script>
<main> <div class="stage">
<header> <div class="card">
<h1>ByteSize</h1> <div class="card-head">
<p class="sub">assign your hotkeys</p> <div class="logo">BYTESIZE</div>
</header> <div class="tag">assign your hotkeys</div>
<p> </div>
ByteSize doesn't ship default hotkeys. Pick combinations that won't clash
with apps you use. You can change these later in settings. <div class="body">
</p> <p class="copy">
<div class="form"> No defaults are shipped. Pick combos that work for you - you can change these later in settings.
<label> </p>
<span>start</span>
<HotkeyInput bind:value={start} placeholder="e.g. F9" /> <div class="fields">
</label> <label class="field">
<label> <span class="field-label">Start recording</span>
<span>stop</span> <HotkeyInput bind:value={start} placeholder="e.g. F9" />
<HotkeyInput bind:value={stop} placeholder="e.g. F9" /> </label>
</label> <label class="field">
<label> <span class="field-label">Stop recording</span>
<span>pause</span> <HotkeyInput bind:value={stop} placeholder="e.g. F10" />
<HotkeyInput bind:value={pause} placeholder="e.g. F10" /> </label>
</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>
<div class="row"> </div>
<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>
<style> <style>
main { .stage {
padding: 2rem; min-height: 100vh;
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 {
display: grid; display: grid;
gap: 0.75rem; place-items: center;
margin: 1.25rem 0; padding: 24px;
background: var(--bg);
} }
label {
display: grid; .card {
grid-template-columns: 80px 1fr; width: 100%;
align-items: center; max-width: 400px;
gap: 0.75rem; background: var(--bg-2);
border: 1px solid var(--border);
border-radius: var(--r-md);
overflow: hidden;
} }
label span {
color: #aaa; .card-head {
font-size: 0.875rem; 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; display: flex;
gap: 0.5rem; flex-direction: column;
margin: 1rem 0; gap: 16px;
} }
.hint {
color: #888; .copy {
font-size: 0.85rem; margin: 0;
font-size: 13px;
line-height: 1.6;
color: var(--text-2);
text-align: center;
} }
button {
font: inherit; .fields {
padding: 0.5rem 1rem; display: flex;
border: 1px solid #444; flex-direction: column;
background: transparent; gap: 14px;
color: inherit; }
.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; cursor: pointer;
border-radius: 4px; transition: background 80ms;
} }
button:hover:not(:disabled) { .btn-primary:hover:not(:disabled) { background: var(--accent-hover); }
border-color: #888; .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; .warn {
border-color: #4a8; padding: 10px 14px;
color: #111; background: var(--err-dim);
} border: 1px solid var(--err-border);
button.primary:disabled { border-radius: var(--r-sm);
background: #333; text-align: center;
border-color: #333;
color: #666;
cursor: not-allowed;
} }
.warn p { margin: 0; font-size: 12px; color: var(--err); }
</style> </style>
+74 -56
View File
@@ -1,36 +1,34 @@
<script lang="ts"> <script lang="ts">
let { let {
value = $bindable(), value = $bindable(),
placeholder = "click to assign", placeholder = "press a key...",
}: { }: {
value: string | null value: string | null
placeholder?: string placeholder?: string
} = $props() } = $props()
let capturing: boolean = $state(false) let capturing = $state(false)
let buttonEl: HTMLButtonElement | null = $state(null) 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 capturing = true
buttonEl?.focus() btn?.focus()
} }
function handleKeydown(e: KeyboardEvent) { function keydown(e: KeyboardEvent) {
if (!capturing) return if (!capturing) return
e.preventDefault() e.preventDefault()
e.stopPropagation()
if (e.key === "Escape") { if (e.key === "Escape") {
capturing = false capturing = false
buttonEl?.blur() btn?.blur()
return
}
if (MODIFIER_KEYS.has(e.key)) {
return return
} }
if (MODIFIERS.has(e.key)) return
const parts: string[] = [] const parts: string[] = []
if (e.ctrlKey) parts.push("Ctrl") if (e.ctrlKey) parts.push("Ctrl")
@@ -45,11 +43,7 @@
parts.push(key) parts.push(key)
value = parts.join("+") value = parts.join("+")
capturing = false capturing = false
buttonEl?.blur() btn?.blur()
}
function handleBlur() {
capturing = false
} }
function clear(e: MouseEvent) { function clear(e: MouseEvent) {
@@ -61,65 +55,89 @@
<div class="row"> <div class="row">
<button <button
bind:this={buttonEl} bind:this={btn}
class="key"
class:capturing class:capturing
onclick={startCapture} onclick={start}
onkeydown={handleKeydown} onkeydown={keydown}
onblur={handleBlur} onblur={() => { capturing = false }}
type="button" type="button"
aria-label={capturing ? "recording shortcut - press a key combo" : "click to assign shortcut"}
> >
{#if capturing} {#if capturing}
press a combo (Esc to cancel) <span class="blink">type a combo</span>
{:else if value} {:else if value}
{value} <span class="val">{value}</span>
{:else} {:else}
{placeholder} <span class="ph">{placeholder}</span>
{/if} {/if}
</button> </button>
{#if value && !capturing} {#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} {/if}
</div> </div>
<style> <style>
.row { .row {
display: flex; display: flex;
gap: 0.4rem; gap: 4px;
align-items: stretch; align-items: stretch;
} }
button {
font: inherit; .key {
padding: 0.45rem 0.7rem;
border: 1px solid #444;
background: #222;
color: inherit;
border-radius: 4px;
cursor: pointer;
text-align: left;
flex: 1; 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; .val { color: var(--text); }
background: #1a2a24; .ph { color: var(--text-3); font-style: italic; font-family: var(--sans); font-weight: 400; }
color: #4a8; .blink { animation: blink 1s step-end infinite; color: var(--accent); }
outline: none;
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
} }
button:focus {
outline: none; .x {
border-color: #4a8; display: grid;
} place-items: center;
button.clear { width: 34px;
flex: 0 0 auto; height: 34px;
padding: 0.45rem 0.7rem;
color: #888;
background: transparent; background: transparent;
border-color: #2a2a2a; border: 1px solid var(--border);
} color: var(--text-3);
button.clear:hover { border-radius: var(--r-sm);
color: #ec9a9a; cursor: pointer;
border-color: #ec9a9a; flex-shrink: 0;
transition: color 80ms, border-color 80ms;
} }
.x:hover { color: var(--err); border-color: var(--err-border); }
</style> </style>
+36 -6
View File
@@ -1,14 +1,44 @@
<main class="center"> <script lang="ts">
<p class="muted">loading...</p> // Minimal loading state - a single breathing mark.
</main> </script>
<div class="stage">
<div class="mark">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</div>
</div>
<style> <style>
main.center { .stage {
min-height: 100vh; min-height: 100vh;
display: grid; display: grid;
place-items: center; 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> </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" import { invoke } from "@tauri-apps/api/core"
const win = getCurrentWebviewWindow() 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 height: number = $state(0)
let phase: "idle" | "recording" | "paused" = $state("idle") let phase: "idle" | "recording" | "paused" = $state("idle")
let fps: number = $state(30) let fps: number = $state(30)
let elapsed: number = $state(0) let elapsed: number = $state(0)
let timer: number | null = null let timer: number | null = null
onMount(() => { onMount(() => {
const updateSize = async () => { const updateSize = async () => {
const size = await win.innerSize() const sz = await win.innerSize()
const scale = await win.scaleFactor() const sf = await win.scaleFactor()
width = Math.round(size.width / scale) width = Math.round(sz.width / sf)
height = Math.round(size.height / scale) height = Math.round(sz.height / sf)
} }
updateSize() updateSize()
const unlistenResize = win.onResized(updateSize) const rp = win.onResized(updateSize)
const unlistenStatePromise = listen<{ let rp2: Promise<() => void> | null = null
phase: "idle" | "recording" | "paused" void (async () => {
fps: number rp2 = listen<{ phase: "idle"|"recording"|"paused"; fps: number }>(
}>("recording-state", (e) => { "recording-state", (e) => {
const next = e.payload.phase fps = e.payload.fps
fps = e.payload.fps if (e.payload.phase === "recording") {
if (next === "recording") { if (phase !== "recording") elapsed = 0
if (phase === "idle") elapsed = 0 startTimer()
startTimer() } else {
} else { stopTimer()
stopTimer() }
} if (e.payload.phase === "idle") { elapsed = 0; phase = "idle" }
if (next === "idle") elapsed = 0 phase = e.payload.phase
phase = next }
}) )
})()
return () => { let rp3: Promise<() => void> | null = null
stopTimer() void (async () => {
unlistenResize.then((fn) => fn()) rp3 = listen<Rect>("picker-pick", async (e: { payload: Rect }) => {
unlistenStatePromise.then((fn) => fn()) 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() { function startTimer() {
if (timer !== null) return if (timer !== null) return
timer = window.setInterval(() => { timer = window.setInterval(() => { elapsed += 0.1 }, 100)
elapsed += 0.1
}, 100)
} }
function stopTimer() { function stopTimer() {
if (timer !== null) { if (timer !== null) { clearInterval(timer); timer = null }
clearInterval(timer)
timer = null
}
} }
function startDrag(e: MouseEvent) { function drag(e: MouseEvent) {
if (e.button === 0) { if (e.button === 0) void win.startDragging()
e.preventDefault()
void win.startDragging().catch((err) => console.error("startDragging", err))
}
} }
async function openPicker() { async function openPicker() {
try { try { await invoke("open_window_picker") } catch (err) { console.error(err) }
await invoke("open_window_picker")
} catch (e) {
console.error("open_window_picker", e)
}
} }
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> </script>
<div class="frame"> <div class="overlay">
<div <div class="titlebar" onmousedown={drag} role="presentation">
class="titlebar" <span class="grip" aria-hidden="true">::</span>
data-tauri-drag-region <span class="dims" aria-label="dimensions">{width} x {height}</span>
onmousedown={startDrag} <button class="pick-btn" onclick={openPicker} title="snap to window" aria-label="snap capture frame to a window">
role="presentation" <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"/>
<span class="grip" data-tauri-drag-region>⠿</span> <rect x="7" y="1" width="4" height="4" rx="0.5"/>
<span class="dim" data-tauri-drag-region>{width} x {height}</span> <rect x="1" y="7" width="4" height="4" rx="0.5"/>
<button <rect x="7" y="7" width="4" height="4" rx="0.5"/>
class="pick-btn" </svg>
onclick={openPicker} </button>
onmousedown={(e) => e.stopPropagation()}
title="snap to window"
type="button"
>▦</button>
{#if phase !== "idle"} {#if phase !== "idle"}
<span class="status" class:rec={phase === "recording"}> <span class="status" class:recording={phase === "recording"}>
{phase === "recording" ? "REC" : "PAUSE"} · {elapsed.toFixed(1)}s · {fps}fps {phase === "recording" ? "REC" : "PAUSE"}
<span class="sep">/</span>
{elapsed.toFixed(1)}s
<span class="sep">/</span>
{fps}fps
</span> </span>
{/if} {/if}
</div> </div>
@@ -135,72 +100,71 @@
<style> <style>
:global(html), :global(body), :global(#overlay) { :global(html), :global(body), :global(#overlay) {
margin: 0; margin: 0; padding: 0;
padding: 0;
background: transparent; background: transparent;
height: 100vh; height: 100vh; width: 100vw;
width: 100vw;
overflow: hidden; overflow: hidden;
} }
.frame { .overlay {
box-sizing: border-box; box-sizing: border-box;
height: 100vh; height: 100vh; width: 100vw;
width: 100vw; border: 2px solid #14B8A6;
border: 2px solid #4a8; display: flex; flex-direction: column;
display: flex;
flex-direction: column;
background: transparent; background: transparent;
border-radius: var(--r-sm);
} }
.titlebar { .titlebar {
height: 22px; height: 24px;
background: rgba(74, 170, 136, 0.85); background: rgba(9, 9, 11, 0.92);
color: #0e1a16; backdrop-filter: blur(8px);
display: flex; color: rgba(228, 228, 231, 0.7);
align-items: center; display: flex; align-items: center; gap: 8px;
gap: 8px;
padding: 0 8px; padding: 0 8px;
font: 11px ui-monospace, monospace; font: 10px/1 var(--mono, 'JetBrains Mono', monospace);
cursor: grab; cursor: grab;
flex-shrink: 0; flex-shrink: 0;
user-select: none; user-select: none;
border-bottom: 1px solid rgba(20, 184, 166, 0.2);
border-radius: 2px 2px 0 0;
} }
.titlebar:active { .titlebar:active { cursor: grabbing; }
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; .pick-btn {
opacity: 0.7; display: grid; place-items: center;
} width: 20px; height: 20px;
.dim { background: rgba(20, 184, 166, 0.1);
font-variant-numeric: tabular-nums; 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 { .status {
margin-left: auto; 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; padding: 1px 6px;
border-radius: 999px; border-radius: 2px;
background: rgba(0, 0, 0, 0.25);
color: #eee;
} }
.status.rec { .status.recording {
background: #c33; background: rgba(34, 197, 94, 0.15);
color: #fff; color: #22C55E;
}
.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;
} }
.sep { opacity: 0.3; }
</style> </style>
+82 -82
View File
@@ -1,138 +1,138 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte" import { onMount } from "svelte"
import { listen } from "@tauri-apps/api/event"
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow" import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow"
import { listen } from "@tauri-apps/api/event"
type Rect = { type Rect = { x: number; y: number; width: number; height: number }
x: number
y: number
width: number
height: number
}
let hover: Rect | null = $state(null) let hover: Rect | null = $state(null)
let scale: number = $state(1) let originX = 0, originY = 0, scale = 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)
onMount(() => { onMount(() => {
const win = getCurrentWebviewWindow() const win = getCurrentWebviewWindow()
let unlistenHover: (() => void) | null = null let unlisten: (() => void)[] = []
let unlistenMoved: (() => void) | null = null
const refreshOrigin = async () => { const refresh = async () => {
scale = await win.scaleFactor() scale = await win.scaleFactor()
const pos = await win.innerPosition() const pos = await win.innerPosition()
originX = pos.x originX = pos.x; originY = pos.y
originY = pos.y
dpr = window.devicePixelRatio
innerW = window.innerWidth
innerH = window.innerHeight
} }
void (async () => { void (async () => {
await refreshOrigin() await refresh()
unlistenMoved = await win.onMoved(refreshOrigin) unlisten.push(await win.onMoved(refresh))
unlistenHover = await listen<Rect>("picker-hover", (e) => { unlisten.push(await listen<Rect>("picker-hover", (e) => { hover = e.payload }))
hover = e.payload
})
})() })()
return () => { return () => unlisten.forEach(fn => fn())
unlistenHover?.()
unlistenMoved?.()
}
}) })
let style = $derived.by(() => { let rectStyle = $derived.by(() => {
if (!hover) return "" if (!hover) return ""
const left = (hover.x - originX) / scale const l = (hover.x - originX) / scale
const top = (hover.y - originY) / scale const t = (hover.y - originY) / scale
const width = hover.width / scale const w = hover.width / scale
const height = hover.height / scale const h = hover.height / scale
return `left: ${left}px; top: ${top}px; width: ${width}px; height: ${height}px;` return `left:${l}px;top:${t}px;width:${w}px;height:${h}px`
}) })
</script> </script>
<main> <div class="picker" aria-label="window picker - click a window to capture it, Esc to cancel">
<div class="dim"></div> <div class="dim" aria-hidden="true"></div>
{#if hover} {#if hover}
<div class="frame" style={style}> <div class="frame" style={rectStyle} aria-hidden="true">
<div class="dims">{hover.width} x {hover.height}</div> <span class="frame-label">{hover.width} x {hover.height}</span>
</div> </div>
{/if} {/if}
<div class="hint">
origin=({originX},{originY}) scale={scale} dpr={dpr} inner={innerW}x{innerH} · <div class="hint" aria-live="polite">
{#if hover} {#if hover}
hover {hover.width}x{hover.height} @ ({hover.x},{hover.y}) click to capture - <kbd>{hover.width}x{hover.height}</kbd>
{:else} {:else}
move mouse over a window. Esc to cancel. move mouse over a window to select it - <kbd>Esc</kbd> to cancel
{/if} {/if}
</div> </div>
</main> </div>
<style> <style>
:global(html), :global(body), :global(#picker) { :global(html), :global(body), :global(#picker) {
margin: 0; margin: 0; padding: 0;
padding: 0;
background: transparent; background: transparent;
height: 100vh; height: 100vh; width: 100vw;
width: 100vw;
overflow: hidden; overflow: hidden;
cursor: crosshair; cursor: crosshair;
} }
main {
.picker {
position: relative; position: relative;
width: 100vw; width: 100vw; height: 100vh;
height: 100vh; font-family: var(--mono, 'JetBrains Mono', monospace);
} }
.dim { .dim {
position: absolute; position: absolute; inset: 0;
inset: 0; background: rgba(9, 9, 11, 0.15);
background: rgba(10, 14, 12, 0.15);
} }
.frame { .frame {
position: absolute; position: absolute;
pointer-events: none; pointer-events: none;
background-color: transparent; border: 2px solid #14B8A6;
background: transparent;
background-image: background-image:
linear-gradient(90deg, #4a8 50%, transparent 50%), repeating-linear-gradient(90deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px),
linear-gradient(90deg, #4a8 50%, transparent 50%), repeating-linear-gradient(0deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px),
linear-gradient(0deg, #4a8 50%, transparent 50%), repeating-linear-gradient(90deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px),
linear-gradient(0deg, #4a8 50%, transparent 50%); repeating-linear-gradient(0deg, #14B8A6 0px, #14B8A6 8px, transparent 8px, transparent 12px);
background-position: 0 0, 0 100%, 0 0, 100% 0; background-position: 0 0, 0 0, 0 100%, 100% 0;
background-repeat: repeat-x, repeat-x, repeat-y, repeat-y; background-size: 12px 2px, 2px 12px, 12px 2px, 2px 12px;
background-size: 12px 2px, 12px 2px, 2px 12px, 2px 12px; background-repeat: repeat-x, repeat-y, repeat-x, repeat-y;
animation: march 0.4s linear infinite; 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 { @keyframes march {
to { to { background-position: 12px 0, 0 12px, -12px 100%, 100% -12px; }
background-position: 12px 0, -12px 100%, 0 -12px, 100% 12px;
}
} }
.dims {
.frame-label {
position: absolute; position: absolute;
top: -22px; top: -20px; left: 0;
left: 0; padding: 2px 6px;
padding: 1px 6px; background: #14B8A6;
background: #4a8; color: #020617;
color: #0e1a16; font-size: 9px;
font: 11px ui-monospace, monospace; font-weight: 600;
border-radius: 3px; font-family: var(--mono, 'JetBrains Mono', monospace);
letter-spacing: 0.04em;
border-radius: 2px;
white-space: nowrap;
} }
.hint { .hint {
position: absolute; position: fixed;
bottom: 20px; bottom: 20px; left: 50%; transform: translateX(-50%);
left: 50%; padding: 7px 18px;
transform: translateX(-50%); background: rgba(9, 9, 11, 0.9);
padding: 6px 14px; backdrop-filter: blur(10px);
background: rgba(0, 0, 0, 0.7); color: rgba(228, 228, 231, 0.85);
color: #fff; font-size: 12px;
font-family: var(--sans, system-ui, sans-serif);
border: 1px solid rgba(20, 184, 166, 0.2);
border-radius: 999px; border-radius: 999px;
font: 13px ui-monospace, monospace; white-space: nowrap;
pointer-events: none; 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> </style>
+419 -201
View File
@@ -8,250 +8,468 @@
let cfg: Config | null = $state(null) let cfg: Config | null = $state(null)
let saving: boolean = $state(false) let saving: boolean = $state(false)
let hotkeyWarnings: string[] = $state([])
let showAdvanced: boolean = $state(false)
let activeTab: string = $state("capture")
onMount(async () => { const TABS = [
cfg = await api.getConfig() { 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() { async function save() {
if (!cfg) return if (!cfg) return
saving = true saving = true
hotkeyWarnings = []
try { try {
await api.saveConfig(cfg) const result = await api.saveConfig(cfg)
onClose() const failed: string[] = []
} finally { if (result.hotkey_result.start_ok === false) failed.push("start")
saving = false 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() { async function pickOutputDir() {
if (!cfg) return if (!cfg) return
const picked = await open({ const picked = await open({ directory: true, defaultPath: cfg.output_dir ?? undefined })
directory: true, if (typeof picked === "string") cfg.output_dir = picked
defaultPath: cfg.output_dir ?? undefined,
})
if (typeof picked === "string") {
cfg.output_dir = picked
}
} }
</script> </script>
<main> <div class="settings">
<header> <header class="settings-header">
<h1>settings</h1> <div class="header-left">
<button class="back" onclick={onClose}>← back</button> <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> </header>
{#if cfg} {#if cfg}
<section> <div class="settings-body">
<h2>capture</h2> <!-- Tab nav -->
<label> <nav class="tab-nav" aria-label="settings categories">
<span>default fps</span> {#each TABS as t}
<select bind:value={cfg.capture.default_fps}> <button
<option value={15}>15</option> class="tab"
<option value={24}>24</option> class:active={activeTab === t.id}
<option value={30}>30</option> onclick={() => activeTab = t.id}
<option value={60}>60</option> >{t.label}</button>
</select> {/each}
</label> </nav>
<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>
<section> <!-- Tab content -->
<h2>export defaults</h2> <div class="tab-content">
<label> {#if activeTab === "capture"}
<span>default format</span> <div class="tab-panel">
<select bind:value={cfg.export.default_format}> <div class="panel-head">
<option value="gif">GIF</option> <h2>Capture</h2>
<option value="webm">WebM</option> <p class="panel-desc">Recording behavior and defaults</p>
<option value="mp4">MP4</option> </div>
</select> <div class="field-list">
</label> <label class="field">
<label> <span class="field-label">Default FPS</span>
<span>GIF dithering</span> <select bind:value={cfg.capture.default_fps}>
<select bind:value={cfg.export.gif_dither}> {#each [15,24,30,60] as f}<option value={f}>{f} fps</option>{/each}
<option value="floyd_steinberg">Floyd-Steinberg</option> </select>
<option value="bayer">Bayer</option> </label>
<option value="none">none</option> <label class="field-check">
</select> <input type="checkbox" bind:checked={cfg.capture.capture_cursor} />
</label> <span>Capture cursor</span>
<label> </label>
<span>WebM codec</span> <label class="field-check">
<select bind:value={cfg.export.webm_codec}> <input type="checkbox" bind:checked={cfg.capture.capture_audio} />
<option value="vp9">VP9 (default)</option> <span>Capture system audio</span>
<option value="av1">AV1 (smaller, slower)</option> </label>
</select> </div>
</label> </div>
<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>
<section> {:else if activeTab === "export"}
<h2>hotkeys</h2> <div class="tab-panel">
<label> <div class="panel-head">
<span>start</span> <h2>Export</h2>
<HotkeyInput bind:value={cfg.hotkeys.start} placeholder="click to assign" /> <p class="panel-desc">Default format and encoding options</p>
</label> </div>
<label> <div class="field-list">
<span>stop</span> <label class="field">
<HotkeyInput bind:value={cfg.hotkeys.stop} placeholder="click to assign" /> <span class="field-label">Default format</span>
</label> <select bind:value={cfg.export.default_format}>
<label> <option value="gif">GIF</option>
<span>pause</span> <option value="webm">WebM</option>
<HotkeyInput bind:value={cfg.hotkeys.pause} placeholder="click to assign" /> <option value="mp4">MP4</option>
</label> </select>
</section> </label>
<section> <button class="advanced-toggle" onclick={() => showAdvanced = !showAdvanced} aria-expanded={showAdvanced}>
<h2>output</h2> <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}>
<label> <polyline points="2,3 5,6 8,3"/>
<span>save folder</span> </svg>
<div class="path-input"> Advanced codecs
<input </button>
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>
<section> {#if showAdvanced}
<h2>updates</h2> <label class="field">
<label class="check"> <span class="field-label">GIF dithering</span>
<input type="checkbox" bind:checked={cfg.updates.check_on_launch} /> <select bind:value={cfg.export.gif_dither}>
<span>check for updates on launch</span> <option value="floyd_steinberg">Floyd-Steinberg</option>
</label> <option value="bayer">Bayer</option>
</section> <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"> {:else if activeTab === "hotkeys"}
<button class="primary" disabled={saving} onclick={save}> <div class="tab-panel">
{saving ? "saving..." : "save"} <div class="panel-head">
</button> <h2>Hotkeys</h2>
<button onclick={onClose}>cancel</button> <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> </div>
{/if} {/if}
</main> </div>
<style> <style>
main { .settings {
padding: 2rem; min-height: 100vh;
max-width: 720px; background: var(--bg);
margin: 0 auto;
}
header {
display: flex; display: flex;
justify-content: space-between; flex-direction: column;
align-items: center;
margin-bottom: 1.5rem;
} }
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; margin: 0;
font-size: 1.5rem; font-size: 14px;
font-weight: 600;
color: var(--text);
letter-spacing: -0.01em; letter-spacing: -0.01em;
} }
section {
margin: 1.5rem 0; .settings-body {
padding-top: 1rem; flex: 1;
border-top: 1px solid #2a2a2a; display: grid;
grid-template-columns: 160px 1fr;
max-width: 640px;
width: 100%;
margin: 0 auto;
min-height: 0;
} }
h2 {
margin: 0 0 0.75rem; @media (max-width: 560px) {
font-size: 0.85rem; .settings-body { grid-template-columns: 1fr; }
color: #888; }
font-weight: normal;
/* 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; text-transform: uppercase;
letter-spacing: 0.05em; letter-spacing: 0.06em;
color: var(--text-3);
} }
label {
display: grid; .field-check {
grid-template-columns: 180px 1fr; display: flex;
gap: 1rem;
align-items: center; align-items: center;
margin: 0.75rem 0; gap: 10px;
font-size: 0.9rem; font-size: 13px;
color: var(--text-2);
cursor: pointer;
} }
label span { .field-check input[type="checkbox"] {
color: #aaa; width: 14px; height: 14px;
accent-color: var(--accent);
cursor: pointer;
} }
label.check {
grid-template-columns: 20px 1fr; select, .path-input {
} padding: 8px 10px;
select, input[type="text"] { background: var(--bg-2);
font: inherit; border: 1px solid var(--border);
padding: 0.4rem 0.6rem; color: var(--text);
border: 1px solid #444; border-radius: var(--r-sm);
background: #222; font-size: 13px;
color: inherit;
border-radius: 4px;
}
select:focus, input[type="text"]:focus {
outline: none; outline: none;
border-color: #4a8;
}
.path-input {
display: grid;
grid-template-columns: 1fr auto;
gap: 0.4rem;
width: 100%; width: 100%;
} }
.small { select:focus, .path-input:focus { border-color: var(--accent); }
padding: 0.25rem 0.5rem; select { cursor: pointer; font-family: var(--sans); }
font-size: 0.8rem;
} .advanced-toggle {
.row {
display: flex; display: flex;
gap: 0.5rem; align-items: center;
margin-top: 2rem; gap: 6px;
}
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 {
background: transparent; background: transparent;
border: none; border: none;
padding: 0.25rem 0.5rem; color: var(--text-3);
color: #aaa; font-size: 12px;
font-size: 0.9rem; 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; 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> </style>
+100 -148
View File
@@ -2,8 +2,7 @@
import { onMount } from "svelte" import { onMount } from "svelte"
import { api, formatBytes, type UpdateInfo, type UpdateDownloadProgress } from "./api" 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 info: UpdateInfo | null = $state(null)
let phase: Phase = $state("info") let phase: Phase = $state("info")
let progress: UpdateDownloadProgress | null = $state(null) let progress: UpdateDownloadProgress | null = $state(null)
@@ -11,113 +10,72 @@
onMount(() => { onMount(() => {
let unlistenInfo: (() => void) | null = null let unlistenInfo: (() => void) | null = null
let unlistenProgress: (() => void) | null = null let unlistenProg: (() => void) | null = null
void (async () => { void (async () => {
unlistenInfo = await api.onUpdateAvailable((i) => { unlistenInfo = await api.onUpdateAvailable((i) => { info = i; phase = "info" })
info = i unlistenProg = await api.onUpdateDownloadProgress((p) => { progress = p })
phase = "info" if (await api.pendingUpdate()) phase = "ready"
})
unlistenProgress = await api.onUpdateDownloadProgress((p) => {
progress = p
})
if (await api.pendingUpdate()) {
phase = "ready-to-apply"
}
})() })()
return () => { return () => { unlistenInfo?.(); unlistenProg?.() }
unlistenInfo?.()
unlistenProgress?.()
}
}) })
function dismiss() { function dismiss() { info = null; errMsg = null; phase = "info" }
info = null function viewRelease() { if (info) void api.openUrl(info.release_url) }
phase = "info"
errMsg = null
}
function viewRelease() {
if (info) void api.openUrl(info.release_url)
}
async function download() { async function download() {
if (!info?.download_url) { if (!info?.download_url) { errMsg = "no downloadable exe in this release"; phase = "error"; return }
errMsg = "this release has no downloadable exe asset" phase = "downloading"; progress = null; errMsg = null
phase = "error" try { await api.downloadUpdate(info.download_url); phase = "ready" }
return catch (e) { errMsg = String(e); phase = "error" }
}
phase = "downloading"
progress = null
errMsg = null
try {
await api.downloadUpdate(info.download_url)
phase = "ready-to-apply"
} catch (e) {
errMsg = String(e)
phase = "error"
}
} }
async function apply() { async function apply() { try { await api.applyUpdate() } catch (e) { errMsg = String(e); phase = "error" } }
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)
})
</script> </script>
{#if info || phase === "ready-to-apply"} {#if info || phase === "ready"}
<div class="banner"> <div class="banner" role="status" aria-live="polite">
<div class="text"> <div class="banner-main">
{#if phase === "ready-to-apply"} {#if phase === "ready"}
<strong>update ready to apply</strong> <span class="dot" style="background:var(--recording)"></span>
{#if info} <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> <span class="ver">v{info.version}</span>
{/if} <span class="from">v{info.current_version}</span>
<p class="body">click apply to swap and restart, or dismiss to keep the current version.</p> </span>
{: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}
{#if info.download_url} {#if info.download_url}
<button class="primary" onclick={download}>download</button> <button class="btn" onclick={download}>Download</button>
{/if} {/if}
<button onclick={viewRelease}>view release</button> <button class="btn ghost" onclick={viewRelease}>Notes</button>
<button onclick={dismiss}>dismiss</button> <button class="btn ghost" onclick={dismiss}>Dismiss</button>
{/if} {/if}
</div> </div>
</div> </div>
@@ -125,66 +83,60 @@
<style> <style>
.banner { .banner {
background: linear-gradient(180deg, #1f2e2a, #1a2522); background: var(--bg-2);
border-bottom: 1px solid #4a8; border-bottom: 1px solid var(--border);
padding: 0.75rem 1.25rem; }
.banner-main {
display: flex; display: flex;
gap: 1rem;
align-items: center; align-items: center;
justify-content: space-between; gap: 12px;
padding: 8px 20px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.text {
flex: 1; .dot {
min-width: 240px; width: 6px; height: 6px;
color: #d8eee5; border-radius: 50%;
font-size: 0.9rem; background: var(--accent);
}
.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;
flex-shrink: 0; 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; align-items: center;
gap: 8px;
font-size: 12px;
color: var(--text-2);
flex: 1;
min-width: 160px;
} }
.muted {
color: #7a8e88; .banner-label { font-weight: 500; color: var(--text); }
font-size: 0.85rem; .ver { font-family: var(--mono); font-size: 11px; color: var(--accent); }
} .from { font-size: 11px; color: var(--text-3); }
button { .banner-hint { font-size: 11px; color: var(--text-3); }
font: inherit;
padding: 0.4rem 0.8rem; .btn {
border: 1px solid #2a3a35; padding: 4px 12px;
background: transparent; border-radius: var(--r-sm);
color: #d8eee5; font-family: var(--sans);
font-size: 11px;
font-weight: 500;
cursor: pointer; cursor: pointer;
border-radius: 4px; transition: all 80ms;
font-size: 0.85rem; white-space: nowrap;
border: 1px solid transparent;
background: var(--accent);
color: var(--accent-text);
} }
button:hover { .btn:hover { background: var(--accent-hover); }
border-color: #4a8; .btn.ghost {
} background: transparent;
button.primary { border-color: var(--border-2);
background: #4a8; color: var(--text-2);
border-color: #4a8;
color: #0e1a16;
}
button.primary:hover {
background: #5b9;
border-color: #5b9;
} }
.btn.ghost:hover { border-color: var(--border-3); color: var(--text); }
</style> </style>
+27 -1
View File
@@ -38,12 +38,15 @@ export type UpdatesConfig = {
check_on_launch: boolean check_on_launch: boolean
} }
export type Theme = "dark" | "light"
export type Config = { export type Config = {
export: ExportConfig export: ExportConfig
capture: CaptureConfig capture: CaptureConfig
hotkeys: HotkeyConfig hotkeys: HotkeyConfig
updates: UpdatesConfig updates: UpdatesConfig
output_dir: string | null output_dir: string | null
theme: Theme
} }
export type DownloadProgress = { export type DownloadProgress = {
@@ -109,6 +112,7 @@ export type ExportRequest = {
trim_start_secs?: number | null trim_start_secs?: number | null
trim_end_secs?: number | null trim_end_secs?: number | null
output_path?: string | null output_path?: string | null
crop?: CaptureRect | null
} }
export type ExportResult = { export type ExportResult = {
@@ -116,10 +120,28 @@ export type ExportResult = {
size_bytes: number 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 = { export const api = {
getStatus: () => invoke<AppStatus>("get_status"), getStatus: () => invoke<AppStatus>("get_status"),
getConfig: () => invoke<Config>("get_config"), 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"), downloadFfmpeg: () => invoke<void>("download_ffmpeg"),
onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise<UnlistenFn> => onFfmpegProgress: (handler: (p: DownloadProgress) => void): Promise<UnlistenFn> =>
listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)), listen<DownloadProgress>("ffmpeg-progress", (e) => handler(e.payload)),
@@ -158,6 +180,10 @@ export const api = {
listen<UpdateDownloadProgress>("update-download-progress", (e) => listen<UpdateDownloadProgress>("update-download-progress", (e) =>
handler(e.payload), 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 { export function formatBytes(n: number): string {
+1
View File
@@ -1,4 +1,5 @@
import { mount } from "svelte" import { mount } from "svelte"
import "./app.css"
import Overlay from "./lib/Overlay.svelte" import Overlay from "./lib/Overlay.svelte"
const app = mount(Overlay, { const app = mount(Overlay, {
+1
View File
@@ -1,4 +1,5 @@
import { mount } from "svelte" import { mount } from "svelte"
import "./app.css"
import Picker from "./lib/Picker.svelte" import Picker from "./lib/Picker.svelte"
const app = mount(Picker, { const app = mount(Picker, {