use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::rtf::ManuscriptFont;
use crate::theme::Theme;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub theme: String,
pub menu_delay_ms: u64,
pub autosave_secs: u64,
pub backup_depth: usize,
pub wrap: bool,
pub wrap_margin: usize,
pub help_level: u8,
pub spellcheck: bool,
pub typewriter: bool,
pub manuscript_font: String,
}
impl Default for Config {
fn default() -> Self {
Config {
theme: String::from("wp-blue"),
menu_delay_ms: 700,
autosave_secs: 60,
backup_depth: 10,
wrap: true,
wrap_margin: 0,
help_level: 1,
spellcheck: true,
typewriter: false,
manuscript_font: String::from("times"),
}
}
}
fn config_path() -> Option<PathBuf> {
Some(
dirs::config_dir()?
.join("perfectstar2k")
.join("config.toml"),
)
}
impl Config {
pub fn load() -> Self {
let Some(path) = config_path() else {
return Config::default();
};
match std::fs::read_to_string(&path) {
Ok(data) => toml::from_str(&data).unwrap_or_default(),
Err(_) => Config::default(),
}
}
pub fn theme(&self) -> Theme {
match self.theme.as_str() {
"wordstar" => Theme::wordstar(),
"terminal" => Theme::terminal_default(),
_ => Theme::wp_blue(),
}
}
pub fn manuscript_font(&self) -> ManuscriptFont {
match self.manuscript_font.as_str() {
"courier" => ManuscriptFont::Courier,
_ => ManuscriptFont::TimesNewRoman,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn old_config_without_backup_depth_uses_default() {
let config: Config = toml::from_str("theme = 'wordstar'\nautosave_secs = 30\n").unwrap();
assert_eq!(config.theme, "wordstar");
assert_eq!(config.autosave_secs, 30);
assert_eq!(config.backup_depth, 10);
}
#[test]
fn backup_depth_accepts_zero_to_disable_new_backups() {
let config: Config = toml::from_str("backup_depth = 0\n").unwrap();
assert_eq!(config.backup_depth, 0);
}
}