123 lines
4.6 KiB
Rust
123 lines
4.6 KiB
Rust
//! The desktop's colours: Caelestia's scheme or KDE's accent, and a watch that notices when they change.
|
|
|
|
use crate::theme::{self, lightness};
|
|
use eframe::egui::{Color32, Context};
|
|
use std::path::PathBuf;
|
|
use std::sync::atomic::{AtomicBool, Ordering};
|
|
use std::sync::{Arc, Weak};
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
const CHECK_EVERY: Duration = Duration::from_secs(1);
|
|
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
|
pub struct Desktop {
|
|
pub seed: Option<Color32>,
|
|
pub dark: Option<bool>,
|
|
}
|
|
|
|
/// Where the desktop keeps its colours.
|
|
#[derive(Clone, Debug)]
|
|
pub struct Sources {
|
|
pub caelestia: PathBuf,
|
|
pub kde: PathBuf,
|
|
}
|
|
|
|
impl Sources {
|
|
pub fn detect() -> Sources {
|
|
Sources {
|
|
caelestia: dirs::state_dir().unwrap_or_default().join("caelestia/scheme.json"),
|
|
kde: dirs::config_dir().unwrap_or_default().join("kdeglobals"),
|
|
}
|
|
}
|
|
|
|
/// Caelestia wins over KDE.
|
|
pub fn read(&self) -> Desktop {
|
|
let caelestia = std::fs::read(&self.caelestia).ok().and_then(|b| from_caelestia(&b));
|
|
let kde = std::fs::read_to_string(&self.kde).map(|t| from_kde(&t)).unwrap_or_default();
|
|
let first = caelestia.unwrap_or_default();
|
|
Desktop { seed: first.seed.or(kde.seed), dark: first.dark.or(kde.dark) }
|
|
}
|
|
|
|
fn stamp(&self) -> [Option<SystemTime>; 2] {
|
|
[&self.caelestia, &self.kde].map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
|
|
}
|
|
}
|
|
|
|
fn from_caelestia(bytes: &[u8]) -> Option<Desktop> {
|
|
let v: serde_json::Value = serde_json::from_slice(bytes).ok()?;
|
|
let seed = theme::hex(v["colours"]["primary"].as_str()?)?;
|
|
Some(Desktop { seed: Some(seed), dark: Some(v["mode"].as_str() != Some("light")) })
|
|
}
|
|
|
|
fn from_kde(text: &str) -> Desktop {
|
|
let rgb = |s: &str| {
|
|
let v: Vec<u8> = s.split(',').take(3).filter_map(|x| x.trim().parse().ok()).collect();
|
|
(v.len() == 3).then(|| Color32::from_rgb(v[0], v[1], v[2]))
|
|
};
|
|
let (mut section, mut accent, mut selection, mut window) = ("", None, None, None);
|
|
for line in text.lines().map(str::trim) {
|
|
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
|
|
section = name;
|
|
} else if let Some((key, value)) = line.split_once('=') {
|
|
match (section, key.trim()) {
|
|
("General", "AccentColor") => accent = rgb(value),
|
|
("Colors:Selection", "BackgroundNormal") => selection = rgb(value),
|
|
("Colors:Window", "BackgroundNormal") => window = rgb(value),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
Desktop { seed: accent.or(selection), dark: window.map(|w| lightness(w) < 0.6) }
|
|
}
|
|
|
|
/// Looks at the files once a second in its own thread and asks for a frame only when one changed.
|
|
pub struct Watch {
|
|
changed: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl Watch {
|
|
pub fn start(sources: Sources, ctx: &Context) -> Watch {
|
|
let changed = Arc::new(AtomicBool::new(false));
|
|
let (flag, ctx) = (Arc::downgrade(&changed), ctx.clone());
|
|
let mut last = sources.stamp();
|
|
let started = std::thread::Builder::new().name("desktop-colours".into()).spawn(move || {
|
|
loop {
|
|
std::thread::sleep(CHECK_EVERY);
|
|
let Some(flag) = Weak::upgrade(&flag) else { return };
|
|
let now = sources.stamp();
|
|
if now != last {
|
|
last = now;
|
|
flag.store(true, Ordering::Release);
|
|
ctx.request_repaint();
|
|
}
|
|
}
|
|
});
|
|
if let Err(e) = started {
|
|
log::warn!("the desktop's colours are not watched: {e}");
|
|
}
|
|
Watch { changed }
|
|
}
|
|
|
|
/// Did the colours change since the last call?
|
|
pub fn take(&self) -> bool {
|
|
self.changed.swap(false, Ordering::Acquire)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn reads_caelestia_then_kde() {
|
|
let c = from_caelestia(br#"{"mode": "light", "colours": {"primary": "f5b2e1"}}"#).unwrap();
|
|
assert_eq!(c, Desktop { seed: Some(Color32::from_rgb(0xf5, 0xb2, 0xe1)), dark: Some(false) });
|
|
for bad in ["", "{", "{}", r#"{"colours": {"primary": "zz"}}"#] {
|
|
assert_eq!(from_caelestia(bad.as_bytes()), None);
|
|
}
|
|
let k = from_kde("[General]\nAccentColor=1,2,3\n[Colors:Selection]\nBackgroundNormal=9,9,9\n[Colors:Window]\nBackgroundNormal=20,20,20\n");
|
|
assert_eq!(k, Desktop { seed: Some(Color32::from_rgb(1, 2, 3)), dark: Some(true) });
|
|
assert_eq!(from_kde("[Colors:Selection]\nBackgroundNormal=9,9,9").seed, Some(Color32::from_rgb(9, 9, 9)));
|
|
assert_eq!(from_kde("AccentColor=1,2\n[Gen"), Desktop::default());
|
|
}
|
|
}
|