use std::path::{Path, PathBuf}; use anyhow::Result; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Theme { #[default] Dark, Light, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Config { #[serde(default)] pub export: ExportConfig, #[serde(default)] pub capture: CaptureConfig, #[serde(default)] pub hotkeys: HotkeyConfig, #[serde(default)] pub updates: UpdatesConfig, #[serde(default)] pub output_dir: Option, #[serde(default)] pub theme: Theme, } // Every persisted section carries a container-level `serde(default)`, so a // config.toml written by an older build still loads once a field is added. The // outer Config already defaulted its own fields; without the same treatment here // a single unknown field made the whole file fail to parse, and the recovery // path backs it up and rewrites defaults - losing the user's hotkeys and // dropping them back into first-run. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct ExportConfig { pub default_format: Format, pub gif_dither: GifDither, pub webm_codec: WebmCodec, pub mp4_codec: Mp4Codec, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum CaptureQuality { /// Cap the capture/encode width at 1920px (downscales larger monitors). /// Lower CPU and disk during recording; the default. #[default] Auto, /// Record at the monitor's native resolution (capped at 3840px to bound /// CPU). Sharp text on 4K screens at the cost of more encode load. Full, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct CaptureConfig { pub default_fps: u32, pub capture_cursor: bool, pub capture_audio: bool, pub capture_quality: CaptureQuality, /// Opt in to recording at `default_fps` instead of the panel's refresh rate. /// Off by default, and a config written before this field existed gets false /// through the container `serde(default)` - so nobody's capture changes until /// they turn it on. pub limit_capture_fps: bool, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct HotkeyConfig { pub start: Option, pub stop: Option, pub pause: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct UpdatesConfig { pub check_on_launch: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Format { #[default] Gif, Webm, Mp4, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum GifBudgetMode { #[default] Balanced, Resolution, Framerate, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "snake_case")] pub enum GifDither { #[default] FloydSteinberg, Bayer, None, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum WebmCodec { #[default] Vp9, Av1, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum Mp4Codec { #[default] H264, H265, } impl Default for Config { fn default() -> Self { Self { export: ExportConfig::default(), capture: CaptureConfig::default(), hotkeys: HotkeyConfig::default(), updates: UpdatesConfig::default(), output_dir: None, theme: Theme::Dark, } } } impl Default for ExportConfig { fn default() -> Self { Self { default_format: Format::Gif, gif_dither: GifDither::FloydSteinberg, webm_codec: WebmCodec::Vp9, mp4_codec: Mp4Codec::H264, } } } impl Default for CaptureConfig { fn default() -> Self { Self { default_fps: 30, capture_cursor: true, capture_audio: false, capture_quality: CaptureQuality::Auto, limit_capture_fps: false, } } } impl Default for UpdatesConfig { fn default() -> Self { Self { check_on_launch: true, } } } impl Config { pub fn load_or_create(path: &Path) -> Result { sweep_stale_backups(path); if !path.exists() { let cfg = Self::default(); cfg.save(path)?; return Ok(cfg); } let raw = std::fs::read_to_string(path)?; match toml::from_str::(&raw) { Ok(cfg) => Ok(cfg), Err(e) => { // Use a timestamped backup so successive corruptions don't // clobber each other. Falls back to .toml.bak if the // timestamped name collides for some reason. let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); let stem = path .file_stem() .and_then(|s| s.to_str()) .unwrap_or("config"); let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("toml"); let backup = path.with_file_name(format!("{stem}-{ts}.{ext}.bak")); let backup = if backup.exists() { path.with_extension("toml.bak") } else { backup }; tracing::warn!( "config.toml is corrupt ({}), backing up to {:?} and using defaults", e, backup ); drop(std::fs::copy(path, &backup)); let cfg = Self::default(); cfg.save(path)?; Ok(cfg) } } } pub fn save(&self, path: &Path) -> Result<()> { let serialized = toml::to_string_pretty(self)?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } std::fs::write(path, serialized)?; Ok(()) } pub fn needs_first_run(&self) -> bool { self.hotkeys.start.is_none() || self.hotkeys.stop.is_none() || self.hotkeys.pause.is_none() } } pub(crate) fn config_path(app_dir: &Path) -> PathBuf { app_dir.join("config.toml") } /// Remove config backup files older than 30 days. Corruption handling writes /// `config-{unix_secs}.toml.bak` (plus a `config.toml.bak` fallback) and never /// cleaned them up, so a long-lived install could accumulate a pile. Parses /// the embedded timestamp; anything unparsable is left alone (the fallback /// name has no timestamp and is kept as the most recent safety net). fn sweep_stale_backups(config_path: &Path) { const MAX_AGE_SECS: u64 = 30 * 24 * 3600; let Some(dir) = config_path.parent() else { return; }; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); let Ok(entries) = std::fs::read_dir(dir) else { return; }; for entry in entries.flatten() { let name = entry.file_name(); let Some(name) = name.to_str() else { continue }; // Match config-{digits}.toml.bak - extract the unix secs and age it out. if let Some(rest) = name .strip_prefix("config-") .and_then(|s| s.strip_suffix(".toml.bak")) { if let Ok(ts) = rest.parse::() { if now.saturating_sub(ts) > MAX_AGE_SECS { drop(std::fs::remove_file(entry.path())); } } } } } #[cfg(test)] mod tests { // Tests fail by panicking, which is the harness contract; unwrap and expect // are denied to keep panics out of the shipping paths. #![allow(clippy::unwrap_used, reason = "a failing test is meant to panic")] 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, capture_quality: CaptureQuality::Full, limit_capture_fps: 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(format!("bytesize-test-{}", std::process::id())); drop(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!(loaded.capture.limit_capture_fps); assert_eq!(loaded.hotkeys.start, Some("F9".to_string())); assert_eq!(loaded.output_dir, Some(PathBuf::from("./custom"))); assert_eq!(loaded.theme, Theme::Light); drop(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()); } }