use crate::Color;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
pub const EXPORT_DIR: &str = "/var/lib/hyprforge/greet";
pub const EXPORT_DIR_ENV: &str = "HYPRFORGE_GREET_DIR";
pub fn export_dir() -> PathBuf {
std::env::var_os(EXPORT_DIR_ENV)
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(EXPORT_DIR))
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ThemeError {
#[error("couldn't read {path}: {source}")]
Read {
path: String,
#[source]
source: std::io::Error,
},
#[error("couldn't write {path}: {source}")]
Write {
path: String,
#[source]
source: std::io::Error,
},
#[error("couldn't parse {path}: {source}")]
Parse {
path: String,
#[source]
source: toml::de::Error,
},
#[error("couldn't serialize the theme: {0}")]
Serialize(#[from] toml::ser::Error),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Theme {
pub wallpaper: Option<PathBuf>,
pub background: Color,
pub surface: Color,
pub foreground: Color,
pub accent: Color,
pub error: Color,
pub font: String,
pub mono_font: String,
pub font_size: f32,
pub clock_format: String,
pub date_format: String,
pub rounding: u32,
pub dim: f32,
pub blur: u32,
pub font_scale: f32,
pub warning: Color,
pub success: Color,
pub info: Color,
pub surfaces: Surfaces,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Surfaces {
pub root: Color,
pub sidebar: Color,
pub card: Color,
pub card_border: Color,
pub row: Color,
pub text: Color,
pub text_dim: Color,
}
impl Default for Surfaces {
fn default() -> Self {
Surfaces {
root: Color::rgba(0x19, 0x1a, 0x21, 0xff),
sidebar: Color::rgba(0x12, 0x13, 0x19, 0xff),
card: Color::rgba(0x25, 0x27, 0x31, 0xff),
card_border: Color::rgba(0x37, 0x3a, 0x47, 0xff),
row: Color::rgba(0x1f, 0x21, 0x29, 0xff),
text: Color::rgba(0xe9, 0xea, 0xef, 0xff),
text_dim: Color::rgba(0x92, 0x96, 0xa4, 0xff),
}
}
}
impl Default for Theme {
fn default() -> Self {
Theme {
wallpaper: None,
background: Color::rgba(0x16, 0x16, 0x1e, 0xff),
surface: Color::rgba(0x26, 0x26, 0x3a, 0xff),
foreground: Color::rgba(0xf8, 0xf8, 0xf2, 0xff),
accent: Color::rgba(0xbd, 0x93, 0xf9, 0xff),
error: Color::rgba(0xff, 0x55, 0x55, 0xff),
font: "Sans".into(),
mono_font: String::new(),
font_size: 15.0,
clock_format: "%H:%M".into(),
date_format: "%A, %e %B".into(),
rounding: 12,
dim: 0.35,
blur: 0,
font_scale: 1.0,
warning: Color::rgba(0xf5, 0xb9, 0x42, 0xff),
success: Color::rgba(0x3e, 0xcf, 0x8e, 0xff),
info: Color::rgba(0x8b, 0xe9, 0xfd, 0xff),
surfaces: Surfaces::default(),
}
}
}
impl Theme {
pub fn drawable_font_size(&self) -> f32 {
match self.font_size.is_finite() {
true => self.font_size.clamp(6.0, 48.0),
false => Theme::default().font_size,
}
}
pub fn corner_radius(&self) -> f32 {
const MAX_ROUNDING: u32 = 64;
self.rounding.min(MAX_ROUNDING) as f32
}
pub fn load(path: &Path) -> Result<Theme, ThemeError> {
if !path.exists() {
return Ok(Theme::default());
}
let contents = std::fs::read_to_string(path).map_err(|source| ThemeError::Read {
path: path.display().to_string(),
source,
})?;
toml::from_str(&contents).map_err(|source| ThemeError::Parse {
path: path.display().to_string(),
source,
})
}
pub fn load_exported() -> Theme {
Theme::load_exported_from(&export_dir())
}
pub fn load_exported_from(dir: &Path) -> Theme {
Theme::load(&dir.join("theme.toml")).unwrap_or_default()
}
pub fn save(&self, path: &Path) -> Result<(), ThemeError> {
let contents = toml::to_string_pretty(self)?;
hyprforge_paths::write_atomic(path, &contents).map_err(|source| ThemeError::Write {
path: path.display().to_string(),
source,
})
}
pub fn export(&self, dir: &Path) -> Result<Theme, ThemeError> {
std::fs::create_dir_all(dir).map_err(|source| ThemeError::Write {
path: dir.display().to_string(),
source,
})?;
let mut exported = self.clone();
exported.wallpaper = match &self.wallpaper {
Some(source) if source.is_file() => {
let extension = source
.extension()
.and_then(|e| e.to_str())
.unwrap_or("img");
let destination = dir.join(format!("wallpaper.{extension}"));
std::fs::copy(source, &destination).map_err(|source| ThemeError::Write {
path: destination.display().to_string(),
source,
})?;
Some(destination)
}
_ => None,
};
let contents = toml::to_string_pretty(&exported)?;
let theme_path = dir.join("theme.toml");
hyprforge_paths::write_atomic(&theme_path, &contents).map_err(|source| {
ThemeError::Write {
path: theme_path.display().to_string(),
source,
}
})?;
Ok(exported)
}
}
#[cfg(test)]
mod tests {
#[test]
fn a_font_size_that_cannot_be_drawn_is_brought_into_range() {
let sized = |size: f32| Theme { font_size: size, ..Theme::default() }.drawable_font_size();
assert_eq!(sized(15.0), 15.0, "an ordinary size is left alone");
assert_eq!(sized(0.0), 6.0);
assert_eq!(sized(4000.0), 48.0);
assert_eq!(sized(-3.0), 6.0);
assert_eq!(sized(f32::NAN), Theme::default().font_size, "not a number at all");
assert_eq!(sized(f32::INFINITY), Theme::default().font_size);
}
#[test]
fn rounding_is_bounded_to_something_still_shaped_like_a_popup() {
let rounded = |r: u32| Theme { rounding: r, ..Theme::default() }.corner_radius();
assert_eq!(rounded(12), 12.0);
assert_eq!(rounded(0), 0.0, "square corners are a choice");
assert_eq!(rounded(9999), 64.0);
}
use super::*;
fn theme_with_wallpaper(path: &Path) -> Theme {
Theme {
wallpaper: Some(path.to_path_buf()),
accent: Color::rgba(0xbd, 0x93, 0xf9, 0xff),
..Theme::default()
}
}
#[test]
fn a_theme_round_trips_through_toml() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("theme.toml");
let theme = Theme { rounding: 20, dim: 0.5, ..Theme::default() };
std::fs::write(&path, toml::to_string_pretty(&theme).unwrap()).unwrap();
assert_eq!(Theme::load(&path).unwrap(), theme);
}
#[test]
fn a_missing_theme_file_is_the_default_not_an_error() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(Theme::load(&dir.path().join("nope.toml")).unwrap(), Theme::default());
}
#[test]
fn an_unreadable_export_degrades_to_plain_rather_than_failing() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(Theme::load_exported_from(dir.path()), Theme::default());
std::fs::write(dir.path().join("theme.toml"), "accent = [not toml").unwrap();
assert_eq!(Theme::load_exported_from(dir.path()), Theme::default());
}
#[test]
fn a_partial_theme_file_fills_in_the_rest() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("theme.toml");
std::fs::write(&path, "rounding = 4\n").unwrap();
let theme = Theme::load(&path).unwrap();
assert_eq!(theme.rounding, 4);
assert_eq!(theme.accent, Theme::default().accent, "the rest defaults");
}
#[test]
fn exporting_copies_the_wallpaper_and_repoints_at_the_copy() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home/Pictures");
std::fs::create_dir_all(&home).unwrap();
let original = home.join("Dracula.png");
std::fs::write(&original, b"not really a png").unwrap();
let export = dir.path().join("export");
let exported = theme_with_wallpaper(&original).export(&export).unwrap();
let copy = exported.wallpaper.clone().unwrap();
assert!(copy.starts_with(&export), "the copy must live in the export: {copy:?}");
assert_ne!(copy, original, "the path must be rewritten");
assert_eq!(std::fs::read(©).unwrap(), b"not really a png");
assert!(original.exists(), "the original is left alone");
}
#[test]
fn the_exported_file_is_what_gets_loaded_back() {
let dir = tempfile::tempdir().unwrap();
let source = dir.path().join("w.png");
std::fs::write(&source, b"x").unwrap();
let export = dir.path().join("export");
let mut theme = theme_with_wallpaper(&source);
theme.rounding = 8;
let exported = theme.export(&export).unwrap();
assert_eq!(Theme::load(&export.join("theme.toml")).unwrap(), exported);
}
#[test]
fn a_missing_wallpaper_is_dropped_rather_than_exported_dangling() {
let dir = tempfile::tempdir().unwrap();
let theme = theme_with_wallpaper(&dir.path().join("gone.png"));
let exported = theme.export(&dir.path().join("export")).unwrap();
assert_eq!(exported.wallpaper, None);
}
#[test]
fn exporting_again_replaces_the_previous_wallpaper() {
let dir = tempfile::tempdir().unwrap();
let export = dir.path().join("export");
let first = dir.path().join("first.png");
let second = dir.path().join("second.png");
std::fs::write(&first, b"one").unwrap();
std::fs::write(&second, b"two").unwrap();
theme_with_wallpaper(&first).export(&export).unwrap();
let exported = theme_with_wallpaper(&second).export(&export).unwrap();
assert_eq!(std::fs::read(exported.wallpaper.unwrap()).unwrap(), b"two");
let images: Vec<_> = std::fs::read_dir(&export)
.unwrap()
.flatten()
.filter(|e| e.path().extension().is_some_and(|x| x == "png"))
.collect();
assert_eq!(images.len(), 1, "only one wallpaper should remain");
}
#[test]
fn colours_are_written_as_rgba_strings() {
let text = toml::to_string(&Theme::default()).unwrap();
assert!(text.contains(r#"accent = "rgba(bd93f9ff)""#), "{text}");
assert!(text.contains(r#"background = "rgba(16161eff)""#), "{text}");
assert!(text.contains(r#"card = "rgba(252731ff)""#), "{text}");
}
#[test]
fn the_default_theme_is_usable_without_any_file() {
let theme = Theme::default();
assert!(theme.wallpaper.is_none());
assert!(theme.font_size > 0.0);
assert_eq!(theme.background.a, 0xff, "a transparent background shows nothing");
assert_eq!(theme.foreground.a, 0xff, "transparent text shows nothing");
assert_ne!(theme.background, theme.foreground, "text must be legible");
assert!((0.0..=1.0).contains(&theme.dim));
}
}
#[cfg(test)]
mod shared_look {
use super::*;
#[test]
fn every_host_reads_the_accent_from_the_same_place() {
let theme = Theme {
accent: Color::rgba(0x12, 0x34, 0x56, 0xff),
..Theme::default()
};
assert_eq!(theme.accent, Color::parse("rgba(123456ff)").unwrap());
let round_tripped: Theme = toml::from_str(&toml::to_string(&theme).unwrap()).unwrap();
assert_eq!(round_tripped.accent, theme.accent);
}
}
#[cfg(test)]
mod info_role {
use super::*;
#[test]
fn a_theme_file_written_before_info_existed_still_parses() {
let older = r#"
background = "rgba(16161eff)"
accent = "rgba(bd93f9ff)"
font_size = 15.0
"#;
let theme: Theme = toml::from_str(older).expect("an older theme file must still load");
assert_eq!(theme.accent, Color::rgba(0xbd, 0x93, 0xf9, 0xff), "what it did say is kept");
assert_eq!(theme.info, Theme::default().info, "what it did not say gets the default");
}
#[test]
fn every_state_colour_is_distinguishable_from_the_others() {
let t = Theme::default();
let states = [("accent", t.accent), ("error", t.error), ("warning", t.warning), ("success", t.success), ("info", t.info)];
for (i, (name_a, a)) in states.iter().enumerate() {
for (name_b, b) in &states[i + 1..] {
assert_ne!(a, b, "{name_a} and {name_b} are the same colour, so neither means anything");
}
}
}
}