92 lines
2.0 KiB
Rust
92 lines
2.0 KiB
Rust
use std::{fmt::Display, path::PathBuf};
|
|
|
|
use anyhow::Result;
|
|
use figment::{
|
|
providers::{Env, Format, Toml},
|
|
Figment,
|
|
};
|
|
use log::{debug, error, trace, warn};
|
|
use serde::{Deserialize, Serialize};
|
|
use tauri::api::path::config_dir;
|
|
|
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
|
pub struct Config {
|
|
#[serde(default)]
|
|
pub background_color: BGColor,
|
|
#[serde(default = "default_interval")]
|
|
pub blink_interval: u64,
|
|
#[serde(default = "default_sens")]
|
|
pub mic_sens: f32,
|
|
}
|
|
|
|
#[inline(always)]
|
|
fn default_interval() -> u64 {
|
|
1500
|
|
}
|
|
|
|
#[inline(always)]
|
|
fn default_sens() -> f32 {
|
|
1.0
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum BGColor {
|
|
Transparent,
|
|
Green,
|
|
Blue,
|
|
Pink,
|
|
Custom(String),
|
|
}
|
|
|
|
impl Default for BGColor {
|
|
fn default() -> Self {
|
|
Self::Transparent
|
|
}
|
|
}
|
|
|
|
impl Display for BGColor {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
Self::Custom(c) => {
|
|
write!(f, "{}", c)
|
|
}
|
|
_ => {
|
|
write!(f, "{}", self.to_string().to_lowercase())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
pub fn get_config_dir() -> PathBuf {
|
|
config_dir()
|
|
.expect("Unable to get config directory")
|
|
.join("cathode")
|
|
}
|
|
|
|
pub fn load_config() -> Config {
|
|
Figment::new()
|
|
.merge(Toml::file(get_config_dir().join("config.toml")))
|
|
.merge(Env::prefixed("CATHODE_"))
|
|
.extract()
|
|
.unwrap_or_else(|e| {
|
|
error!("Error while loading config: {e}");
|
|
Config::default()
|
|
})
|
|
}
|
|
|
|
pub fn save_config(config: &Config) -> Result<()> {
|
|
use std::fs;
|
|
let raw = toml::to_string_pretty(config)?;
|
|
let dir = get_config_dir();
|
|
if !dir.exists() {
|
|
fs::create_dir_all(&dir)?;
|
|
}
|
|
debug!("Writing config");
|
|
trace!("Config: {}", raw);
|
|
let path = dir.join("config.toml");
|
|
fs::write(&path, raw)?;
|
|
Ok(())
|
|
}
|