Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

6.7 KB
Raw Blame
//! Omarchy integration: theme palette (`colors.toml`) live watcher, AC/battery power detection,
//! and `omarchy-shell background setSuspended` RAII lifecycle guard.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Instant, SystemTime};

/// Default Tokyo Night fallback palette when Omarchy's `colors.toml` is not present.
fn default_palette() -> BTreeMap<String, String> {
    let pairs = [
        ("mode", "dark"),
        ("accent", "#7aa2f7"),
        ("background", "#1a1b26"),
        ("dark_background", "#13141c"),
        ("darker_background", "#0e0e14"),
        ("lighter_background", "#24283b"),
        ("foreground", "#a9b1d6"),
        ("bright_foreground", "#c0caf5"),
        ("blue", "#7aa2f7"),
        ("cyan", "#449dab"),
        ("magenta", "#ad8ee6"),
        ("orange", "#eb927b"),
        ("yellow", "#e0af68"),
        ("green", "#9ece6a"),
        ("red", "#f7768e"),
        ("bright_cyan", "#0db9d7"),
        ("bright_blue", "#7da6ff"),
    ];
    pairs.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
}

pub fn default_colors_path() -> PathBuf {
    if let Ok(state) = std::env::var("XDG_STATE_HOME") {
        if !state.is_empty() {
            return PathBuf::from(state).join("omarchy/current/theme/colors.toml");
        }
    }
    let home = std::env::var("HOME").unwrap_or_default();
    PathBuf::from(home).join(".local/state/omarchy/current/theme/colors.toml")
}

/// Parse Omarchy's flat `key = "value"` `colors.toml` without pulling in a TOML crate.
pub fn parse_colors_toml(src: &str) -> BTreeMap<String, String> {
    let mut map = default_palette();
    for raw_line in src.lines() {
        let line = raw_line.split('#').next().unwrap_or("").trim();
        // Wait: color values contain `#` inside quotes! Parse `key = "val"` before stripping comments.
        let _ = line;
        let trimmed = raw_line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('[') {
            continue;
        }
        let Some((k, v)) = trimmed.split_once('=') else { continue };
        let key = k.trim();
        let val_part = v.trim();
        let val = if let Some(rest) = val_part.strip_prefix('"') {
            rest.split('"').next().unwrap_or("")
        } else if let Some(rest) = val_part.strip_prefix('\'') {
            rest.split('\'').next().unwrap_or("")
        } else {
            val_part.split('#').next().unwrap_or("").trim()
        };
        if !key.is_empty() && !val.is_empty() {
            map.insert(key.to_string(), val.to_string());
        }
    }
    map
}

pub fn palette_to_json(map: &BTreeMap<String, String>) -> String {
    serde_json::to_string(map).unwrap_or_else(|_| "{}".into())
}

pub struct ThemeWatcher {
    path: PathBuf,
    last_mtime: Option<SystemTime>,
    last_check: Instant,
    current_json: String,
}

impl ThemeWatcher {
    pub fn new(path: Option<PathBuf>) -> Self {
        let path = path.unwrap_or_else(default_colors_path);
        let (mtime, json) = Self::read_file(&path);
        Self {
            path,
            last_mtime: mtime,
            last_check: Instant::now(),
            current_json: json,
        }
    }

    fn read_file(path: &Path) -> (Option<SystemTime>, String) {
        let mtime = fs::metadata(path).and_then(|m| m.modified()).ok();
        let map = fs::read_to_string(path)
            .map(|s| parse_colors_toml(&s))
            .unwrap_or_else(|_| default_palette());
        (mtime, palette_to_json(&map))
    }

    pub fn current_json(&self) -> &str {
        &self.current_json
    }

    /// Check at most once per second for theme changes; returns `Some(new_json)` on change.
    pub fn poll_changed(&mut self) -> Option<String> {
        if self.last_check.elapsed().as_millis() < 1000 {
            return None;
        }
        self.last_check = Instant::now();
        let mtime = fs::metadata(&self.path).and_then(|m| m.modified()).ok();
        if mtime == self.last_mtime {
            return None;
        }
        let (new_mtime, new_json) = Self::read_file(&self.path);
        self.last_mtime = new_mtime;
        if new_json != self.current_json {
            self.current_json = new_json.clone();
            Some(new_json)
        } else {
            None
        }
    }
}

/// Detect whether the laptop is currently running on battery power (`Discharging`).
pub fn on_battery() -> bool {
    let Ok(entries) = fs::read_dir("/sys/class/power_supply") else { return false };
    let mut saw_ac = false;
    let mut ac_online = false;
    for entry in entries.flatten() {
        let p = entry.path();
        let kind = fs::read_to_string(p.join("type")).unwrap_or_default();
        match kind.trim() {
            "Battery" => {
                if let Ok(st) = fs::read_to_string(p.join("status")) {
                    if st.trim().eq_ignore_ascii_case("Discharging") {
                        return true;
                    }
                }
            }
            "Mains" => {
                saw_ac = true;
                if let Ok(on) = fs::read_to_string(p.join("online")) {
                    if on.trim() == "1" {
                        ac_online = true;
                    }
                }
            }
            _ => {}
        }
    }
    saw_ac && !ac_online
}

/// Suspends `omarchy-shell`'s static background layer once ThreeRT has presented its first frame,
/// and restores it cleanly when dropped.
pub struct OmarchySuspendGuard {
    enabled: bool,
    suspended: bool,
}

impl OmarchySuspendGuard {
    pub fn new(enabled: bool) -> Self {
        Self { enabled, suspended: false }
    }

    pub fn suspend_now(&mut self) {
        if !self.enabled || self.suspended {
            return;
        }
        let ok = Command::new("omarchy-shell")
            .args(["-q", "background", "setSuspended", "true"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|s| s.success());
        if ok {
            self.suspended = true;
            eprintln!("[threert-wallpaper] suspended omarchy-shell static background");
        }
    }

    pub fn restore_now(&mut self) {
        if !self.suspended {
            return;
        }
        let _ = Command::new("omarchy-shell")
            .args(["-q", "background", "setSuspended", "false"])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
        self.suspended = false;
        eprintln!("[threert-wallpaper] restored omarchy-shell static background");
    }
}

impl Drop for OmarchySuspendGuard {
    fn drop(&mut self) {
        self.restore_now();
    }
}