User requested a checkpoint and stopped all agents. Deployed artifacts remain the last verified releases; unfinished settings/categories/forums are preserved as WIP. See TODO/roadmap for verification and remaining release/updater work.
210 lines
7 KiB
Rust
210 lines
7 KiB
Rust
use std::io::Read;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use super::{MAX_CSS_BYTES, ThemeSpec, parse_css};
|
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct AppearancePreferences {
|
|
pub mode: String,
|
|
pub custom_css: String,
|
|
pub font_size: f32,
|
|
}
|
|
|
|
impl Default for AppearancePreferences {
|
|
fn default() -> Self {
|
|
Self {
|
|
mode: "black".into(),
|
|
custom_css: ThemeSpec::builtin("black").to_css(),
|
|
font_size: 16.0,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn config_directory() -> PathBuf {
|
|
dirs::config_dir()
|
|
.unwrap_or_else(|| PathBuf::from("."))
|
|
.join("vnox")
|
|
}
|
|
|
|
pub fn default_theme_path() -> PathBuf {
|
|
config_directory().join("custom-theme.css")
|
|
}
|
|
|
|
impl AppearancePreferences {
|
|
pub fn load() -> Self {
|
|
Self::load_from(&config_directory().join("appearance.json")).unwrap_or_default()
|
|
}
|
|
|
|
fn load_from(path: &Path) -> anyhow::Result<Self> {
|
|
let prefs: Self = serde_json::from_slice(&std::fs::read(path)?)?;
|
|
prefs.resolve().map_err(anyhow::Error::msg)?;
|
|
if prefs.custom_css.len() > MAX_CSS_BYTES {
|
|
anyhow::bail!("Theme file is too large");
|
|
}
|
|
Ok(prefs)
|
|
}
|
|
|
|
pub fn resolve(&self) -> Result<ThemeSpec, String> {
|
|
if self.mode != "custom" && !super::BUILTIN_THEME_IDS.contains(&self.mode.as_str()) {
|
|
return Err(crate::ui::i18n::text("Unknown theme."));
|
|
}
|
|
if !self.font_size.is_finite() || !(12.0..=22.0).contains(&self.font_size) {
|
|
return Err(crate::ui::i18n::text(
|
|
"Text size must be between 12px and 22px.",
|
|
));
|
|
}
|
|
let mut theme = if self.mode == "custom" {
|
|
parse_css(&self.custom_css)?
|
|
} else {
|
|
ThemeSpec::builtin(&self.mode)
|
|
};
|
|
theme.font_size = self.font_size;
|
|
Ok(theme)
|
|
}
|
|
|
|
pub fn save(&self) -> anyhow::Result<()> {
|
|
self.save_to(&config_directory().join("appearance.json"))
|
|
}
|
|
|
|
fn save_to(&self, path: &Path) -> anyhow::Result<()> {
|
|
self.resolve().map_err(anyhow::Error::msg)?;
|
|
if let Some(parent) = path.parent() {
|
|
std::fs::create_dir_all(parent)?;
|
|
}
|
|
let temporary = path.with_extension(format!("{}.tmp", uuid::Uuid::new_v4()));
|
|
std::fs::write(&temporary, serde_json::to_vec_pretty(self)?)?;
|
|
if let Err(error) = std::fs::rename(&temporary, path) {
|
|
let _ = std::fs::remove_file(&temporary);
|
|
return Err(error.into());
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
fn check_css_path(path: &Path) -> Result<(), String> {
|
|
if path
|
|
.extension()
|
|
.and_then(|s| s.to_str())
|
|
.is_none_or(|ext| !ext.eq_ignore_ascii_case("css"))
|
|
{
|
|
return Err(crate::ui::i18n::text("Enter a file path ending in .css."));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub fn import_css(path: &Path) -> Result<String, String> {
|
|
check_css_path(path)?;
|
|
let file = std::fs::File::open(path).map_err(|error| {
|
|
crate::ui::i18n::format(
|
|
"Could not open theme: {error}",
|
|
&[("error", error.to_string())],
|
|
)
|
|
})?;
|
|
let mut css = String::new();
|
|
file.take(MAX_CSS_BYTES as u64 + 1)
|
|
.read_to_string(&mut css)
|
|
.map_err(|error| {
|
|
crate::ui::i18n::format(
|
|
"Could not read CSS: {error}",
|
|
&[("error", error.to_string())],
|
|
)
|
|
})?;
|
|
parse_css(&css)?;
|
|
Ok(css)
|
|
}
|
|
|
|
pub fn export_css(path: &Path, theme: &ThemeSpec) -> Result<(), String> {
|
|
check_css_path(path)?;
|
|
// The path is explicitly provided by the local export action. No network I/O.
|
|
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
|
std::fs::create_dir_all(parent).map_err(|e| {
|
|
crate::ui::i18n::format(
|
|
"Could not create theme directory: {e}",
|
|
&[("e", e.to_string())],
|
|
)
|
|
})?;
|
|
}
|
|
std::fs::write(path, theme.to_css()).map_err(|error| {
|
|
crate::ui::i18n::format(
|
|
"Could not save CSS: {error}",
|
|
&[("error", error.to_string())],
|
|
)
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn new_profiles_default_to_extra_dark_and_explicit_choices_survive() {
|
|
assert_eq!(AppearancePreferences::default().mode, "black");
|
|
assert_eq!(
|
|
serde_json::from_str::<AppearancePreferences>("{}")
|
|
.unwrap()
|
|
.mode,
|
|
"black"
|
|
);
|
|
for id in super::super::BUILTIN_THEME_IDS
|
|
.into_iter()
|
|
.chain(["custom"])
|
|
{
|
|
let json = serde_json::json!({"mode": id}).to_string();
|
|
let prefs: AppearancePreferences = serde_json::from_str(&json).unwrap();
|
|
assert_eq!(prefs.mode, id);
|
|
assert!(prefs.resolve().is_ok(), "{id}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn saved_custom_palette_and_text_size_survive_reload() {
|
|
let directory = std::env::temp_dir().join(format!("vnox-theme-{}", uuid::Uuid::new_v4()));
|
|
let path = directory.join("appearance.json");
|
|
let preferences = AppearancePreferences {
|
|
mode: "custom".into(),
|
|
custom_css: ":root { --vnox-bg: #101010; --vnox-accent: #aabbcc; }".into(),
|
|
font_size: 18.0,
|
|
};
|
|
preferences.save_to(&path).unwrap();
|
|
let loaded = AppearancePreferences::load_from(&path).unwrap();
|
|
assert_eq!(loaded.mode, "custom");
|
|
assert_eq!(loaded.custom_css, preferences.custom_css);
|
|
assert_eq!(loaded.resolve().unwrap(), preferences.resolve().unwrap());
|
|
std::fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn local_theme_import_export_validates_content_and_extension() {
|
|
let directory =
|
|
std::env::temp_dir().join(format!("vnox-theme-file-{}", uuid::Uuid::new_v4()));
|
|
std::fs::create_dir_all(&directory).unwrap();
|
|
let path = directory.join("theme.css");
|
|
let theme = ThemeSpec::builtin("light");
|
|
export_css(&path, &theme).unwrap();
|
|
assert_eq!(parse_css(&import_css(&path).unwrap()).unwrap(), theme);
|
|
std::fs::write(&path, "body { display: none; }").unwrap();
|
|
assert!(import_css(&path).is_err());
|
|
assert!(export_css(&directory.join("theme.json"), &theme).is_err());
|
|
std::fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_persisted_preferences_are_rejected() {
|
|
let directory =
|
|
std::env::temp_dir().join(format!("vnox-theme-invalid-{}", uuid::Uuid::new_v4()));
|
|
std::fs::create_dir_all(&directory).unwrap();
|
|
let path = directory.join("appearance.json");
|
|
for content in [
|
|
"{\"mode\":\"unsupported\"}",
|
|
"{\"font_size\":200}",
|
|
"{\"mode\":\"custom\",\"custom_css\":\"@import 'x'\"}",
|
|
] {
|
|
std::fs::write(&path, content).unwrap();
|
|
assert!(AppearancePreferences::load_from(&path).is_err());
|
|
}
|
|
std::fs::remove_dir_all(directory).unwrap();
|
|
}
|
|
}
|