feat(auto-theme): add palette extraction, theme generation, and DE detection
Rust module auto_theme/ with: - K-means clustering (k=6) on downsampled images for palette extraction - CSS variable generator producing all ~40 required theme tokens - WCAG AA contrast enforcement for text and accent colors - Desktop environment detection (GNOME, KDE Plasma, COSMIC, XFCE, Cinnamon) - Wallpaper path retrieval per DE (gsettings, Plasma config, COSMIC config) - System accent color retrieval (GNOME 47+, KDE, COSMIC) cc
This commit is contained in:
5 files changed
+1394
No files matched your search
@@ -0,0 +1,299 @@
|
||||
//! Generate a complete set of CSS custom properties from a ThemePalette.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{GeneratedTheme, PaletteColor, ThemePalette};
|
||||
|
||||
/// Generate a full CSS theme from an extracted palette.
|
||||
pub fn generate_theme(palette: &ThemePalette, source: &str) -> GeneratedTheme {
|
||||
let mut vars = HashMap::new();
|
||||
|
||||
// Backgrounds
|
||||
vars.insert("--bg-primary".into(), palette.bg_primary.to_hex());
|
||||
vars.insert("--bg-secondary".into(), palette.bg_secondary.to_hex());
|
||||
vars.insert("--bg-tertiary".into(), palette.bg_tertiary.to_hex());
|
||||
vars.insert("--bg-hover".into(), palette.bg_hover.to_hex());
|
||||
|
||||
// Text colors
|
||||
let (text_primary, text_secondary, text_muted, text_disabled) = if palette.is_dark {
|
||||
(
|
||||
PaletteColor::new(255, 255, 255),
|
||||
PaletteColor::new(204, 204, 204),
|
||||
PaletteColor::new(136, 136, 136),
|
||||
PaletteColor::new(85, 85, 85),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
PaletteColor::new(15, 15, 15),
|
||||
PaletteColor::new(68, 68, 68),
|
||||
PaletteColor::new(102, 102, 102),
|
||||
PaletteColor::new(153, 153, 153),
|
||||
)
|
||||
};
|
||||
|
||||
// Adjust text-primary for contrast if needed
|
||||
let text_primary = ensure_text_contrast(text_primary, &palette.bg_primary, palette.is_dark);
|
||||
|
||||
vars.insert("--text-primary".into(), text_primary.to_hex());
|
||||
vars.insert("--text-secondary".into(), text_secondary.to_hex());
|
||||
vars.insert("--text-muted".into(), text_muted.to_hex());
|
||||
vars.insert("--text-disabled".into(), text_disabled.to_hex());
|
||||
|
||||
// Accent
|
||||
vars.insert("--accent-primary".into(), palette.accent.to_hex());
|
||||
vars.insert(
|
||||
"--accent-hover".into(),
|
||||
palette.accent.shift_lightness(0.10).to_hex(),
|
||||
);
|
||||
vars.insert(
|
||||
"--accent-active".into(),
|
||||
palette.accent.shift_lightness(-0.10).to_hex(),
|
||||
);
|
||||
|
||||
// Button text: white if accent is dark, black if light
|
||||
let btn_text = if palette.accent.luminance() < 0.5 {
|
||||
PaletteColor::new(255, 255, 255)
|
||||
} else {
|
||||
PaletteColor::new(0, 0, 0)
|
||||
};
|
||||
vars.insert("--btn-primary-text".into(), btn_text.to_hex());
|
||||
|
||||
// Status colors (fixed safe values, consistent with existing themes)
|
||||
if palette.is_dark {
|
||||
vars.insert("--danger".into(), "#ef4444".into());
|
||||
vars.insert("--danger-bg".into(), "rgba(239, 68, 68, 0.1)".into());
|
||||
vars.insert("--danger-border".into(), "rgba(239, 68, 68, 0.3)".into());
|
||||
vars.insert("--danger-hover".into(), "rgba(239, 68, 68, 0.2)".into());
|
||||
|
||||
vars.insert("--warning".into(), "#fbbf24".into());
|
||||
vars.insert("--warning-bg".into(), "rgba(251, 191, 36, 0.1)".into());
|
||||
vars.insert("--warning-border".into(), "rgba(251, 191, 36, 0.3)".into());
|
||||
vars.insert("--warning-hover".into(), "rgba(251, 191, 36, 0.2)".into());
|
||||
} else {
|
||||
vars.insert("--danger".into(), "#dc2626".into());
|
||||
vars.insert("--danger-bg".into(), "rgba(220, 38, 38, 0.1)".into());
|
||||
vars.insert("--danger-border".into(), "rgba(220, 38, 38, 0.3)".into());
|
||||
vars.insert("--danger-hover".into(), "rgba(220, 38, 38, 0.15)".into());
|
||||
|
||||
vars.insert("--warning".into(), "#d97706".into());
|
||||
vars.insert("--warning-bg".into(), "rgba(217, 119, 6, 0.1)".into());
|
||||
vars.insert("--warning-border".into(), "rgba(217, 119, 6, 0.3)".into());
|
||||
vars.insert("--warning-hover".into(), "rgba(217, 119, 6, 0.15)".into());
|
||||
}
|
||||
|
||||
// Borders: subtle shifts from bg_primary
|
||||
let border_subtle = if palette.is_dark {
|
||||
palette.bg_primary.shift_lightness(0.08)
|
||||
} else {
|
||||
palette.bg_primary.shift_lightness(-0.08)
|
||||
};
|
||||
let border_strong = if palette.is_dark {
|
||||
palette.bg_primary.shift_lightness(0.14)
|
||||
} else {
|
||||
palette.bg_primary.shift_lightness(-0.14)
|
||||
};
|
||||
vars.insert("--border-subtle".into(), border_subtle.to_hex());
|
||||
vars.insert("--border-strong".into(), border_strong.to_hex());
|
||||
|
||||
// Alpha tokens: white-based for dark, black-based for light
|
||||
let alpha_base = if palette.is_dark {
|
||||
(255, 255, 255)
|
||||
} else {
|
||||
(0, 0, 0)
|
||||
};
|
||||
|
||||
let alpha_levels: &[(f64, &str)] = &[
|
||||
(0.04, "--alpha-4"),
|
||||
(0.05, "--alpha-5"),
|
||||
(0.06, "--alpha-6"),
|
||||
(0.08, "--alpha-8"),
|
||||
(0.10, "--alpha-10"),
|
||||
(0.15, "--alpha-15"),
|
||||
(0.18, "--alpha-18"),
|
||||
(0.20, "--alpha-20"),
|
||||
(0.25, "--alpha-25"),
|
||||
(0.30, "--alpha-30"),
|
||||
(0.35, "--alpha-35"),
|
||||
(0.40, "--alpha-40"),
|
||||
(0.45, "--alpha-45"),
|
||||
(0.50, "--alpha-50"),
|
||||
(0.60, "--alpha-60"),
|
||||
(0.70, "--alpha-70"),
|
||||
(0.80, "--alpha-80"),
|
||||
(0.85, "--alpha-85"),
|
||||
(0.90, "--alpha-90"),
|
||||
(0.95, "--alpha-95"),
|
||||
];
|
||||
|
||||
for (alpha, name) in alpha_levels {
|
||||
vars.insert(
|
||||
name.to_string(),
|
||||
format!(
|
||||
"rgba({}, {}, {}, {})",
|
||||
alpha_base.0, alpha_base.1, alpha_base.2, alpha
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
GeneratedTheme {
|
||||
variables: vars,
|
||||
is_dark: palette.is_dark,
|
||||
source: source.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensure text has at least WCAG AA contrast (4.5:1) against the background.
|
||||
fn ensure_text_contrast(
|
||||
text: PaletteColor,
|
||||
bg: &PaletteColor,
|
||||
is_dark: bool,
|
||||
) -> PaletteColor {
|
||||
if text.contrast_ratio(bg) >= 4.5 {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Shift text toward white (dark theme) or black (light theme) until contrast is met
|
||||
let (h, s, l) = text.to_hsl();
|
||||
let direction = if is_dark { 0.05 } else { -0.05 };
|
||||
let mut new_l = l;
|
||||
|
||||
for _ in 0..20 {
|
||||
new_l = (new_l + direction).clamp(0.0, 1.0);
|
||||
let candidate = PaletteColor::from_hsl(h, s, new_l);
|
||||
if candidate.contrast_ratio(bg) >= 4.5 {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
// Absolute fallback
|
||||
if is_dark {
|
||||
PaletteColor::new(255, 255, 255)
|
||||
} else {
|
||||
PaletteColor::new(0, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_generate_theme_dark() {
|
||||
let palette = ThemePalette {
|
||||
bg_primary: PaletteColor::new(15, 15, 20),
|
||||
bg_secondary: PaletteColor::new(26, 26, 30),
|
||||
bg_tertiary: PaletteColor::new(42, 42, 48),
|
||||
bg_hover: PaletteColor::new(31, 31, 35),
|
||||
accent: PaletteColor::new(66, 133, 244),
|
||||
is_dark: true,
|
||||
all_colors: vec![],
|
||||
};
|
||||
|
||||
let theme = generate_theme(&palette, "test");
|
||||
|
||||
assert!(theme.is_dark);
|
||||
assert_eq!(theme.source, "test");
|
||||
assert!(theme.variables.contains_key("--bg-primary"));
|
||||
assert!(theme.variables.contains_key("--accent-primary"));
|
||||
assert!(theme.variables.contains_key("--alpha-50"));
|
||||
assert!(theme.variables.contains_key("--danger"));
|
||||
assert!(theme.variables.contains_key("--border-subtle"));
|
||||
|
||||
// Dark theme should have white-based alphas
|
||||
let alpha50 = theme.variables.get("--alpha-50").unwrap();
|
||||
assert!(alpha50.starts_with("rgba(255, 255, 255"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_theme_light() {
|
||||
let palette = ThemePalette {
|
||||
bg_primary: PaletteColor::new(245, 245, 245),
|
||||
bg_secondary: PaletteColor::new(235, 235, 235),
|
||||
bg_tertiary: PaletteColor::new(220, 220, 220),
|
||||
bg_hover: PaletteColor::new(240, 240, 240),
|
||||
accent: PaletteColor::new(26, 115, 232),
|
||||
is_dark: false,
|
||||
all_colors: vec![],
|
||||
};
|
||||
|
||||
let theme = generate_theme(&palette, "test-light");
|
||||
|
||||
assert!(!theme.is_dark);
|
||||
|
||||
// Light theme should have black-based alphas
|
||||
let alpha50 = theme.variables.get("--alpha-50").unwrap();
|
||||
assert!(alpha50.starts_with("rgba(0, 0, 0"));
|
||||
|
||||
// Text should be dark
|
||||
let text = theme.variables.get("--text-primary").unwrap();
|
||||
assert!(text.starts_with("#0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_all_required_tokens_present() {
|
||||
let palette = ThemePalette {
|
||||
bg_primary: PaletteColor::new(20, 20, 25),
|
||||
bg_secondary: PaletteColor::new(30, 30, 35),
|
||||
bg_tertiary: PaletteColor::new(45, 45, 50),
|
||||
bg_hover: PaletteColor::new(35, 35, 40),
|
||||
accent: PaletteColor::new(100, 200, 100),
|
||||
is_dark: true,
|
||||
all_colors: vec![],
|
||||
};
|
||||
|
||||
let theme = generate_theme(&palette, "completeness-test");
|
||||
|
||||
let required = [
|
||||
"--bg-primary",
|
||||
"--bg-secondary",
|
||||
"--bg-tertiary",
|
||||
"--bg-hover",
|
||||
"--text-primary",
|
||||
"--text-secondary",
|
||||
"--text-muted",
|
||||
"--text-disabled",
|
||||
"--accent-primary",
|
||||
"--accent-hover",
|
||||
"--accent-active",
|
||||
"--btn-primary-text",
|
||||
"--danger",
|
||||
"--danger-bg",
|
||||
"--danger-border",
|
||||
"--danger-hover",
|
||||
"--warning",
|
||||
"--warning-bg",
|
||||
"--warning-border",
|
||||
"--warning-hover",
|
||||
"--border-subtle",
|
||||
"--border-strong",
|
||||
"--alpha-4",
|
||||
"--alpha-5",
|
||||
"--alpha-6",
|
||||
"--alpha-8",
|
||||
"--alpha-10",
|
||||
"--alpha-15",
|
||||
"--alpha-18",
|
||||
"--alpha-20",
|
||||
"--alpha-25",
|
||||
"--alpha-30",
|
||||
"--alpha-35",
|
||||
"--alpha-40",
|
||||
"--alpha-45",
|
||||
"--alpha-50",
|
||||
"--alpha-60",
|
||||
"--alpha-70",
|
||||
"--alpha-80",
|
||||
"--alpha-85",
|
||||
"--alpha-90",
|
||||
"--alpha-95",
|
||||
];
|
||||
|
||||
for key in &required {
|
||||
assert!(
|
||||
theme.variables.contains_key(*key),
|
||||
"Missing required token: {}",
|
||||
key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! Auto-theme generation from images and system wallpapers.
|
||||
//!
|
||||
//! Extracts dominant colors via k-means clustering, then maps them
|
||||
//! to the full set of CSS custom properties expected by the QBZ frontend.
|
||||
|
||||
pub mod generator;
|
||||
pub mod palette;
|
||||
pub mod system;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// A single RGB color.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
pub struct PaletteColor {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
}
|
||||
|
||||
impl PaletteColor {
|
||||
pub fn new(r: u8, g: u8, b: u8) -> Self {
|
||||
Self { r, g, b }
|
||||
}
|
||||
|
||||
/// Relative luminance (ITU-R BT.709) in [0.0, 1.0].
|
||||
pub fn luminance(&self) -> f64 {
|
||||
fn linearize(c: u8) -> f64 {
|
||||
let s = c as f64 / 255.0;
|
||||
if s <= 0.04045 {
|
||||
s / 12.92
|
||||
} else {
|
||||
((s + 0.055) / 1.055).powf(2.4)
|
||||
}
|
||||
}
|
||||
0.2126 * linearize(self.r) + 0.7152 * linearize(self.g) + 0.0722 * linearize(self.b)
|
||||
}
|
||||
|
||||
/// HSL saturation in [0.0, 1.0].
|
||||
pub fn saturation(&self) -> f64 {
|
||||
let (r, g, b) = (self.r as f64 / 255.0, self.g as f64 / 255.0, self.b as f64 / 255.0);
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let delta = max - min;
|
||||
if delta < 1e-6 {
|
||||
return 0.0;
|
||||
}
|
||||
let l = (max + min) / 2.0;
|
||||
if l <= 0.5 {
|
||||
delta / (max + min)
|
||||
} else {
|
||||
delta / (2.0 - max - min)
|
||||
}
|
||||
}
|
||||
|
||||
/// WCAG contrast ratio against another color (range [1, 21]).
|
||||
pub fn contrast_ratio(&self, other: &PaletteColor) -> f64 {
|
||||
let l1 = self.luminance();
|
||||
let l2 = other.luminance();
|
||||
let (lighter, darker) = if l1 > l2 { (l1, l2) } else { (l2, l1) };
|
||||
(lighter + 0.05) / (darker + 0.05)
|
||||
}
|
||||
|
||||
/// Shift lightness by `amount` (-1.0 to 1.0) in HSL space. Returns a new color.
|
||||
pub fn shift_lightness(&self, amount: f64) -> PaletteColor {
|
||||
let (h, s, l) = self.to_hsl();
|
||||
let new_l = (l + amount).clamp(0.0, 1.0);
|
||||
PaletteColor::from_hsl(h, s, new_l)
|
||||
}
|
||||
|
||||
/// Convert to HSL (h in [0, 360), s and l in [0, 1]).
|
||||
pub fn to_hsl(&self) -> (f64, f64, f64) {
|
||||
let (r, g, b) = (self.r as f64 / 255.0, self.g as f64 / 255.0, self.b as f64 / 255.0);
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let l = (max + min) / 2.0;
|
||||
let delta = max - min;
|
||||
|
||||
if delta < 1e-6 {
|
||||
return (0.0, 0.0, l);
|
||||
}
|
||||
|
||||
let s = if l <= 0.5 {
|
||||
delta / (max + min)
|
||||
} else {
|
||||
delta / (2.0 - max - min)
|
||||
};
|
||||
|
||||
let h = if (max - r).abs() < 1e-6 {
|
||||
((g - b) / delta) % 6.0
|
||||
} else if (max - g).abs() < 1e-6 {
|
||||
(b - r) / delta + 2.0
|
||||
} else {
|
||||
(r - g) / delta + 4.0
|
||||
};
|
||||
let h = (h * 60.0 + 360.0) % 360.0;
|
||||
|
||||
(h, s, l)
|
||||
}
|
||||
|
||||
/// Construct from HSL values.
|
||||
pub fn from_hsl(h: f64, s: f64, l: f64) -> PaletteColor {
|
||||
if s < 1e-6 {
|
||||
let v = (l * 255.0).round() as u8;
|
||||
return PaletteColor::new(v, v, v);
|
||||
}
|
||||
|
||||
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
|
||||
let h_prime = h / 60.0;
|
||||
let x = c * (1.0 - (h_prime % 2.0 - 1.0).abs());
|
||||
let m = l - c / 2.0;
|
||||
|
||||
let (r1, g1, b1) = match h_prime as u32 {
|
||||
0 => (c, x, 0.0),
|
||||
1 => (x, c, 0.0),
|
||||
2 => (0.0, c, x),
|
||||
3 => (0.0, x, c),
|
||||
4 => (x, 0.0, c),
|
||||
_ => (c, 0.0, x),
|
||||
};
|
||||
|
||||
PaletteColor::new(
|
||||
((r1 + m) * 255.0).round() as u8,
|
||||
((g1 + m) * 255.0).round() as u8,
|
||||
((b1 + m) * 255.0).round() as u8,
|
||||
)
|
||||
}
|
||||
|
||||
/// CSS hex string (#rrggbb).
|
||||
pub fn to_hex(&self) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
|
||||
}
|
||||
|
||||
/// CSS rgba() string with given alpha (0.0 to 1.0).
|
||||
pub fn to_rgba(&self, alpha: f64) -> String {
|
||||
format!("rgba({}, {}, {}, {})", self.r, self.g, self.b, alpha)
|
||||
}
|
||||
|
||||
/// Euclidean distance in RGB space.
|
||||
pub fn distance(&self, other: &PaletteColor) -> f64 {
|
||||
let dr = self.r as f64 - other.r as f64;
|
||||
let dg = self.g as f64 - other.g as f64;
|
||||
let db = self.b as f64 - other.b as f64;
|
||||
(dr * dr + dg * dg + db * db).sqrt()
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracted palette from an image.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ThemePalette {
|
||||
pub bg_primary: PaletteColor,
|
||||
pub bg_secondary: PaletteColor,
|
||||
pub bg_tertiary: PaletteColor,
|
||||
pub bg_hover: PaletteColor,
|
||||
pub accent: PaletteColor,
|
||||
pub is_dark: bool,
|
||||
pub all_colors: Vec<PaletteColor>,
|
||||
}
|
||||
|
||||
/// A fully generated theme ready for CSS injection.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GeneratedTheme {
|
||||
/// CSS variable name (e.g. "--bg-primary") to value (e.g. "#0f0f0f").
|
||||
pub variables: HashMap<String, String>,
|
||||
pub is_dark: bool,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_luminance_black() {
|
||||
let black = PaletteColor::new(0, 0, 0);
|
||||
assert!((black.luminance() - 0.0).abs() < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_luminance_white() {
|
||||
let white = PaletteColor::new(255, 255, 255);
|
||||
assert!((white.luminance() - 1.0).abs() < 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_contrast_ratio_bw() {
|
||||
let black = PaletteColor::new(0, 0, 0);
|
||||
let white = PaletteColor::new(255, 255, 255);
|
||||
let ratio = black.contrast_ratio(&white);
|
||||
assert!((ratio - 21.0).abs() < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hsl_roundtrip() {
|
||||
let c = PaletteColor::new(66, 133, 244); // Google Blue
|
||||
let (h, s, l) = c.to_hsl();
|
||||
let back = PaletteColor::from_hsl(h, s, l);
|
||||
assert!((c.r as i16 - back.r as i16).unsigned_abs() <= 1);
|
||||
assert!((c.g as i16 - back.g as i16).unsigned_abs() <= 1);
|
||||
assert!((c.b as i16 - back.b as i16).unsigned_abs() <= 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_saturation_gray() {
|
||||
let gray = PaletteColor::new(128, 128, 128);
|
||||
assert!(gray.saturation() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hex_format() {
|
||||
let c = PaletteColor::new(15, 15, 15);
|
||||
assert_eq!(c.to_hex(), "#0f0f0f");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
//! K-means palette extraction from images.
|
||||
|
||||
use image::GenericImageView;
|
||||
use std::path::Path;
|
||||
|
||||
use super::PaletteColor;
|
||||
use super::ThemePalette;
|
||||
|
||||
/// Load an image, downsample, and extract dominant colors via k-means.
|
||||
pub fn extract_palette(image_path: &str) -> Result<ThemePalette, String> {
|
||||
let path = Path::new(image_path);
|
||||
if !path.exists() {
|
||||
return Err(format!("Image not found: {}", image_path));
|
||||
}
|
||||
|
||||
let img = image::open(path).map_err(|e| format!("Failed to open image: {}", e))?;
|
||||
|
||||
// Downsample to ~100x100 for fast processing
|
||||
let thumb = img.resize_exact(100, 100, image::imageops::FilterType::Lanczos3);
|
||||
|
||||
let mut pixels: Vec<[f64; 3]> = Vec::with_capacity(10_000);
|
||||
for (_x, _y, rgba) in thumb.pixels() {
|
||||
// Skip semi-transparent pixels
|
||||
if rgba[3] < 200 {
|
||||
continue;
|
||||
}
|
||||
pixels.push([rgba[0] as f64, rgba[1] as f64, rgba[2] as f64]);
|
||||
}
|
||||
|
||||
if pixels.is_empty() {
|
||||
return Err("Image contains no opaque pixels".to_string());
|
||||
}
|
||||
|
||||
let clusters = kmeans(&pixels, 6, 25);
|
||||
|
||||
if clusters.is_empty() {
|
||||
return Err("K-means produced no clusters".to_string());
|
||||
}
|
||||
|
||||
build_palette(clusters)
|
||||
}
|
||||
|
||||
/// Extract palette directly from raw RGB pixel data (for testing or custom sources).
|
||||
pub fn extract_palette_from_pixels(pixels: &[[f64; 3]]) -> Result<ThemePalette, String> {
|
||||
if pixels.is_empty() {
|
||||
return Err("No pixels provided".to_string());
|
||||
}
|
||||
let clusters = kmeans(pixels, 6, 25);
|
||||
if clusters.is_empty() {
|
||||
return Err("K-means produced no clusters".to_string());
|
||||
}
|
||||
build_palette(clusters)
|
||||
}
|
||||
|
||||
/// A cluster result: centroid + pixel count.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Cluster {
|
||||
centroid: [f64; 3],
|
||||
count: usize,
|
||||
}
|
||||
|
||||
/// Simple k-means clustering on RGB values.
|
||||
fn kmeans(pixels: &[[f64; 3]], k: usize, max_iters: usize) -> Vec<Cluster> {
|
||||
let n = pixels.len();
|
||||
if n == 0 || k == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let k = k.min(n);
|
||||
|
||||
// Initialize centroids by evenly sampling from the pixel list
|
||||
let mut centroids: Vec<[f64; 3]> = Vec::with_capacity(k);
|
||||
let step = n / k;
|
||||
for i in 0..k {
|
||||
centroids.push(pixels[i * step]);
|
||||
}
|
||||
|
||||
let mut assignments = vec![0usize; n];
|
||||
|
||||
for _ in 0..max_iters {
|
||||
let mut changed = false;
|
||||
|
||||
// Assignment step
|
||||
for (idx, pixel) in pixels.iter().enumerate() {
|
||||
let mut best_cluster = 0;
|
||||
let mut best_dist = f64::MAX;
|
||||
for (ci, centroid) in centroids.iter().enumerate() {
|
||||
let dist = rgb_dist_sq(pixel, centroid);
|
||||
if dist < best_dist {
|
||||
best_dist = dist;
|
||||
best_cluster = ci;
|
||||
}
|
||||
}
|
||||
if assignments[idx] != best_cluster {
|
||||
assignments[idx] = best_cluster;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !changed {
|
||||
break;
|
||||
}
|
||||
|
||||
// Update step
|
||||
let mut sums = vec![[0.0f64; 3]; k];
|
||||
let mut counts = vec![0usize; k];
|
||||
for (idx, pixel) in pixels.iter().enumerate() {
|
||||
let ci = assignments[idx];
|
||||
sums[ci][0] += pixel[0];
|
||||
sums[ci][1] += pixel[1];
|
||||
sums[ci][2] += pixel[2];
|
||||
counts[ci] += 1;
|
||||
}
|
||||
|
||||
for ci in 0..k {
|
||||
if counts[ci] > 0 {
|
||||
centroids[ci][0] = sums[ci][0] / counts[ci] as f64;
|
||||
centroids[ci][1] = sums[ci][1] / counts[ci] as f64;
|
||||
centroids[ci][2] = sums[ci][2] / counts[ci] as f64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build final clusters
|
||||
let mut counts = vec![0usize; k];
|
||||
for &a in &assignments {
|
||||
counts[a] += 1;
|
||||
}
|
||||
|
||||
centroids
|
||||
.into_iter()
|
||||
.zip(counts.into_iter())
|
||||
.filter(|(_, count)| *count > 0)
|
||||
.map(|(centroid, count)| Cluster { centroid, count })
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rgb_dist_sq(a: &[f64; 3], b: &[f64; 3]) -> f64 {
|
||||
let dr = a[0] - b[0];
|
||||
let dg = a[1] - b[1];
|
||||
let db = a[2] - b[2];
|
||||
dr * dr + dg * dg + db * db
|
||||
}
|
||||
|
||||
/// Build a ThemePalette from k-means clusters.
|
||||
fn build_palette(mut clusters: Vec<Cluster>) -> Result<ThemePalette, String> {
|
||||
// Sort by pixel count (dominant first)
|
||||
clusters.sort_by(|a, b| b.count.cmp(&a.count));
|
||||
|
||||
let all_colors: Vec<PaletteColor> = clusters
|
||||
.iter()
|
||||
.map(|c| {
|
||||
PaletteColor::new(
|
||||
c.centroid[0].round() as u8,
|
||||
c.centroid[1].round() as u8,
|
||||
c.centroid[2].round() as u8,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let dominant = all_colors[0];
|
||||
let is_dark = dominant.luminance() < 0.5;
|
||||
|
||||
// Check if the image is monochromatic (all clusters very similar)
|
||||
let max_distance = all_colors
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|c| dominant.distance(c))
|
||||
.fold(0.0f64, f64::max);
|
||||
|
||||
let is_monochrome = max_distance < 40.0;
|
||||
|
||||
// Assign background roles from dominant color with lightness shifts
|
||||
let (bg_primary, bg_secondary, bg_tertiary, bg_hover) = if is_dark {
|
||||
(
|
||||
dominant.shift_lightness(-0.05), // slightly darker
|
||||
dominant.shift_lightness(0.03),
|
||||
dominant.shift_lightness(0.08),
|
||||
dominant.shift_lightness(0.02),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
dominant.shift_lightness(0.05), // slightly lighter
|
||||
dominant.shift_lightness(-0.03),
|
||||
dominant.shift_lightness(-0.08),
|
||||
dominant.shift_lightness(-0.02),
|
||||
)
|
||||
};
|
||||
|
||||
// Find best accent: most saturated cluster with WCAG AA contrast (4.5:1) against bg_primary
|
||||
let accent = if is_monochrome {
|
||||
// Monochrome fallback: use a standard accent
|
||||
if is_dark {
|
||||
PaletteColor::new(66, 133, 244) // blue
|
||||
} else {
|
||||
PaletteColor::new(26, 115, 232) // darker blue
|
||||
}
|
||||
} else {
|
||||
find_best_accent(&all_colors, &bg_primary, is_dark)
|
||||
};
|
||||
|
||||
Ok(ThemePalette {
|
||||
bg_primary,
|
||||
bg_secondary,
|
||||
bg_tertiary,
|
||||
bg_hover,
|
||||
accent,
|
||||
is_dark,
|
||||
all_colors,
|
||||
})
|
||||
}
|
||||
|
||||
/// Find the best accent color: prioritize saturation, then ensure WCAG AA contrast.
|
||||
fn find_best_accent(
|
||||
colors: &[PaletteColor],
|
||||
bg: &PaletteColor,
|
||||
is_dark: bool,
|
||||
) -> PaletteColor {
|
||||
// Sort candidates by saturation (highest first), skip the dominant (index 0)
|
||||
let mut candidates: Vec<(usize, f64)> = colors
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(1)
|
||||
.map(|(i, c)| (i, c.saturation()))
|
||||
.collect();
|
||||
candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
|
||||
|
||||
for (idx, _sat) in &candidates {
|
||||
let color = colors[*idx];
|
||||
let ratio = color.contrast_ratio(bg);
|
||||
if ratio >= 4.5 {
|
||||
return color;
|
||||
}
|
||||
// Try adjusting lightness to meet contrast
|
||||
let adjusted = adjust_for_contrast(&color, bg, is_dark);
|
||||
if adjusted.contrast_ratio(bg) >= 4.5 {
|
||||
return adjusted;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: use the most saturated and force-adjust
|
||||
if let Some((idx, _)) = candidates.first() {
|
||||
let color = colors[*idx];
|
||||
adjust_for_contrast(&color, bg, is_dark)
|
||||
} else {
|
||||
// Ultimate fallback
|
||||
if is_dark {
|
||||
PaletteColor::new(66, 133, 244)
|
||||
} else {
|
||||
PaletteColor::new(26, 115, 232)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjust a color's lightness to achieve WCAG AA contrast against a background.
|
||||
fn adjust_for_contrast(
|
||||
color: &PaletteColor,
|
||||
bg: &PaletteColor,
|
||||
is_dark: bool,
|
||||
) -> PaletteColor {
|
||||
let (h, s, l) = color.to_hsl();
|
||||
let direction = if is_dark { 0.05 } else { -0.05 };
|
||||
|
||||
let mut new_l = l;
|
||||
for _ in 0..20 {
|
||||
new_l = (new_l + direction).clamp(0.0, 1.0);
|
||||
let candidate = PaletteColor::from_hsl(h, s, new_l);
|
||||
if candidate.contrast_ratio(bg) >= 4.5 {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
PaletteColor::from_hsl(h, s, new_l)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_kmeans_basic() {
|
||||
let pixels: Vec<[f64; 3]> = vec![
|
||||
[0.0, 0.0, 0.0],
|
||||
[10.0, 10.0, 10.0],
|
||||
[5.0, 5.0, 5.0],
|
||||
[250.0, 250.0, 250.0],
|
||||
[240.0, 240.0, 240.0],
|
||||
[245.0, 245.0, 245.0],
|
||||
];
|
||||
let clusters = kmeans(&pixels, 2, 20);
|
||||
assert_eq!(clusters.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_from_pixels() {
|
||||
// A mix of dark blues and bright oranges
|
||||
let mut pixels = Vec::new();
|
||||
for _ in 0..500 {
|
||||
pixels.push([20.0, 30.0, 80.0]); // dark blue
|
||||
}
|
||||
for _ in 0..300 {
|
||||
pixels.push([240.0, 160.0, 40.0]); // orange
|
||||
}
|
||||
for _ in 0..200 {
|
||||
pixels.push([10.0, 10.0, 15.0]); // near-black
|
||||
}
|
||||
|
||||
let palette = extract_palette_from_pixels(&pixels).unwrap();
|
||||
assert!(palette.is_dark); // dominant is dark
|
||||
assert!(palette.accent.saturation() > 0.1); // accent should be saturated
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_monochrome_fallback() {
|
||||
// All pixels are very similar grays
|
||||
let pixels: Vec<[f64; 3]> = (0..1000).map(|_| [50.0, 52.0, 48.0]).collect();
|
||||
let palette = extract_palette_from_pixels(&pixels).unwrap();
|
||||
// Should still produce a valid palette with fallback accent
|
||||
assert!(palette.accent.saturation() > 0.1 || palette.accent.luminance() > 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_accent_has_contrast() {
|
||||
let mut pixels = Vec::new();
|
||||
for _ in 0..700 {
|
||||
pixels.push([15.0, 15.0, 20.0]);
|
||||
}
|
||||
for _ in 0..300 {
|
||||
pixels.push([200.0, 50.0, 80.0]);
|
||||
}
|
||||
|
||||
let palette = extract_palette_from_pixels(&pixels).unwrap();
|
||||
let ratio = palette.accent.contrast_ratio(&palette.bg_primary);
|
||||
// Should meet or approach WCAG AA
|
||||
assert!(ratio >= 3.0, "Accent contrast ratio too low: {}", ratio);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
//! Desktop environment detection, wallpaper path retrieval, and system accent color.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
use super::PaletteColor;
|
||||
|
||||
/// Supported desktop environments.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum DesktopEnvironment {
|
||||
Gnome,
|
||||
KdePlasma,
|
||||
Cosmic,
|
||||
Xfce,
|
||||
Cinnamon,
|
||||
Unknown(String),
|
||||
}
|
||||
|
||||
impl DesktopEnvironment {
|
||||
/// Human-readable name.
|
||||
pub fn display_name(&self) -> &str {
|
||||
match self {
|
||||
Self::Gnome => "GNOME",
|
||||
Self::KdePlasma => "KDE Plasma",
|
||||
Self::Cosmic => "COSMIC",
|
||||
Self::Xfce => "Xfce",
|
||||
Self::Cinnamon => "Cinnamon",
|
||||
Self::Unknown(name) => name.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Detect the current desktop environment.
|
||||
pub fn detect_desktop_environment() -> DesktopEnvironment {
|
||||
// Try each env var in priority order
|
||||
let candidates = [
|
||||
env::var("XDG_CURRENT_DESKTOP"),
|
||||
env::var("XDG_SESSION_DESKTOP"),
|
||||
env::var("DESKTOP_SESSION"),
|
||||
];
|
||||
|
||||
for candidate in &candidates {
|
||||
if let Ok(val) = candidate {
|
||||
let upper = val.to_uppercase();
|
||||
if upper.contains("GNOME") || upper.contains("UNITY") || upper.contains("UBUNTU") {
|
||||
return DesktopEnvironment::Gnome;
|
||||
}
|
||||
if upper.contains("KDE") || upper.contains("PLASMA") {
|
||||
return DesktopEnvironment::KdePlasma;
|
||||
}
|
||||
if upper.contains("COSMIC") {
|
||||
return DesktopEnvironment::Cosmic;
|
||||
}
|
||||
if upper.contains("XFCE") {
|
||||
return DesktopEnvironment::Xfce;
|
||||
}
|
||||
if upper.contains("CINNAMON") || upper.contains("X-CINNAMON") {
|
||||
return DesktopEnvironment::Cinnamon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let name = candidates
|
||||
.iter()
|
||||
.find_map(|c| c.as_ref().ok().cloned())
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
DesktopEnvironment::Unknown(name)
|
||||
}
|
||||
|
||||
/// Get the current wallpaper path for the detected DE.
|
||||
pub fn get_system_wallpaper() -> Result<String, String> {
|
||||
let de = detect_desktop_environment();
|
||||
get_wallpaper_for_de(&de)
|
||||
}
|
||||
|
||||
fn get_wallpaper_for_de(de: &DesktopEnvironment) -> Result<String, String> {
|
||||
match de {
|
||||
DesktopEnvironment::Gnome => get_gnome_wallpaper(),
|
||||
DesktopEnvironment::KdePlasma => get_kde_wallpaper(),
|
||||
DesktopEnvironment::Cosmic => get_cosmic_wallpaper(),
|
||||
DesktopEnvironment::Cinnamon => get_cinnamon_wallpaper(),
|
||||
DesktopEnvironment::Xfce => get_xfce_wallpaper(),
|
||||
DesktopEnvironment::Unknown(name) => {
|
||||
Err(format!("Unsupported desktop environment: {}", name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the system accent color for the detected DE.
|
||||
pub fn get_system_accent_color() -> Result<PaletteColor, String> {
|
||||
let de = detect_desktop_environment();
|
||||
get_accent_for_de(&de)
|
||||
}
|
||||
|
||||
fn get_accent_for_de(de: &DesktopEnvironment) -> Result<PaletteColor, String> {
|
||||
match de {
|
||||
DesktopEnvironment::Gnome => get_gnome_accent(),
|
||||
DesktopEnvironment::KdePlasma => get_kde_accent(),
|
||||
DesktopEnvironment::Cosmic => get_cosmic_accent(),
|
||||
_ => Err(format!(
|
||||
"Accent color not supported for {}",
|
||||
de.display_name()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
// --- GNOME ---
|
||||
|
||||
fn get_gnome_wallpaper() -> Result<String, String> {
|
||||
// Try dark variant first, then standard
|
||||
for key in &["picture-uri-dark", "picture-uri"] {
|
||||
let output = Command::new("gsettings")
|
||||
.args(["get", "org.gnome.desktop.background", key])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run gsettings: {}", e))?;
|
||||
|
||||
if output.status.success() {
|
||||
let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if let Some(path) = parse_gsettings_uri(&raw) {
|
||||
if PathBuf::from(&path).exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err("Could not determine GNOME wallpaper".into())
|
||||
}
|
||||
|
||||
fn get_gnome_accent() -> Result<PaletteColor, String> {
|
||||
let output = Command::new("gsettings")
|
||||
.args(["get", "org.gnome.desktop.interface", "accent-color"])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run gsettings: {}", e))?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err("gsettings accent-color not available (requires GNOME 47+)".into());
|
||||
}
|
||||
|
||||
let raw = String::from_utf8_lossy(&output.stdout)
|
||||
.trim()
|
||||
.trim_matches('\'')
|
||||
.to_lowercase();
|
||||
|
||||
// GNOME accent color names → approximate RGB values
|
||||
let color = match raw.as_str() {
|
||||
"blue" => PaletteColor::new(53, 132, 228),
|
||||
"teal" => PaletteColor::new(38, 162, 105),
|
||||
"green" => PaletteColor::new(51, 209, 122),
|
||||
"yellow" => PaletteColor::new(246, 211, 45),
|
||||
"orange" => PaletteColor::new(255, 120, 0),
|
||||
"red" => PaletteColor::new(224, 27, 36),
|
||||
"pink" => PaletteColor::new(220, 138, 221),
|
||||
"purple" => PaletteColor::new(145, 65, 172),
|
||||
"slate" => PaletteColor::new(111, 131, 150),
|
||||
_ => return Err(format!("Unknown GNOME accent color: {}", raw)),
|
||||
};
|
||||
|
||||
Ok(color)
|
||||
}
|
||||
|
||||
// --- KDE Plasma ---
|
||||
|
||||
fn get_kde_wallpaper() -> Result<String, String> {
|
||||
let home = env::var("HOME").map_err(|_| "HOME not set".to_string())?;
|
||||
let config_path = format!(
|
||||
"{}/.config/plasma-org.kde.plasma.desktop-appletsrc",
|
||||
home
|
||||
);
|
||||
|
||||
let content =
|
||||
fs::read_to_string(&config_path).map_err(|e| format!("Cannot read Plasma config: {}", e))?;
|
||||
|
||||
// Look for Image= under [Wallpaper][org.kde.image][General]
|
||||
let mut in_wallpaper_section = false;
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if trimmed.starts_with('[') {
|
||||
// Check if we're entering a wallpaper image section
|
||||
in_wallpaper_section = trimmed.contains("Wallpaper")
|
||||
&& trimmed.contains("org.kde.image")
|
||||
&& trimmed.contains("General");
|
||||
}
|
||||
|
||||
if in_wallpaper_section && trimmed.starts_with("Image=") {
|
||||
let value = trimmed.trim_start_matches("Image=").trim();
|
||||
if let Some(path) = parse_file_uri(value) {
|
||||
if PathBuf::from(&path).exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
// Try as plain path
|
||||
if PathBuf::from(value).exists() {
|
||||
return Ok(value.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err("Could not find wallpaper in Plasma config".into())
|
||||
}
|
||||
|
||||
fn get_kde_accent() -> Result<PaletteColor, String> {
|
||||
let home = env::var("HOME").map_err(|_| "HOME not set".to_string())?;
|
||||
let config_path = format!("{}/.config/kdeglobals", home);
|
||||
|
||||
let content =
|
||||
fs::read_to_string(&config_path).map_err(|e| format!("Cannot read kdeglobals: {}", e))?;
|
||||
|
||||
let mut in_general = false;
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if trimmed == "[General]" {
|
||||
in_general = true;
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with('[') {
|
||||
in_general = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if in_general && trimmed.starts_with("AccentColor=") {
|
||||
let value = trimmed.trim_start_matches("AccentColor=").trim();
|
||||
return parse_rgb_csv(value);
|
||||
}
|
||||
}
|
||||
|
||||
Err("AccentColor not found in kdeglobals".into())
|
||||
}
|
||||
|
||||
// --- COSMIC ---
|
||||
|
||||
fn get_cosmic_wallpaper() -> Result<String, String> {
|
||||
let home = env::var("HOME").map_err(|_| "HOME not set".to_string())?;
|
||||
|
||||
// COSMIC stores wallpaper config in its own config system
|
||||
let config_paths = [
|
||||
format!(
|
||||
"{}/.config/cosmic/com.system76.CosmicBackground/v1/all",
|
||||
home
|
||||
),
|
||||
format!(
|
||||
"{}/.config/cosmic/com.system76.CosmicBackground/v1/backgrounds",
|
||||
home
|
||||
),
|
||||
];
|
||||
|
||||
for config_path in &config_paths {
|
||||
if let Ok(content) = fs::read_to_string(config_path) {
|
||||
// COSMIC config may contain paths in RON format or plain text
|
||||
// Look for file paths
|
||||
if let Some(path) = extract_path_from_cosmic_config(&content) {
|
||||
if PathBuf::from(&path).exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err("Could not find wallpaper in COSMIC config".into())
|
||||
}
|
||||
|
||||
fn get_cosmic_accent() -> Result<PaletteColor, String> {
|
||||
let home = env::var("HOME").map_err(|_| "HOME not set".to_string())?;
|
||||
|
||||
// Try dark and light theme accent
|
||||
let accent_paths = [
|
||||
format!(
|
||||
"{}/.config/cosmic/com.system76.CosmicTheme.Dark/v1/accent",
|
||||
home
|
||||
),
|
||||
format!(
|
||||
"{}/.config/cosmic/com.system76.CosmicTheme.Light/v1/accent",
|
||||
home
|
||||
),
|
||||
];
|
||||
|
||||
for path in &accent_paths {
|
||||
if let Ok(content) = fs::read_to_string(path) {
|
||||
if let Some(color) = parse_cosmic_color(&content) {
|
||||
return Ok(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err("Could not read COSMIC accent color".into())
|
||||
}
|
||||
|
||||
// --- Cinnamon ---
|
||||
|
||||
fn get_cinnamon_wallpaper() -> Result<String, String> {
|
||||
let output = Command::new("gsettings")
|
||||
.args(["get", "org.cinnamon.desktop.background", "picture-uri"])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run gsettings: {}", e))?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err("Could not get Cinnamon wallpaper via gsettings".into());
|
||||
}
|
||||
|
||||
let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if let Some(path) = parse_gsettings_uri(&raw) {
|
||||
if PathBuf::from(&path).exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
|
||||
Err("Could not determine Cinnamon wallpaper".into())
|
||||
}
|
||||
|
||||
// --- XFCE ---
|
||||
|
||||
fn get_xfce_wallpaper() -> Result<String, String> {
|
||||
let output = Command::new("xfconf-query")
|
||||
.args([
|
||||
"-c",
|
||||
"xfce4-desktop",
|
||||
"-p",
|
||||
"/backdrop/screen0/monitoreDP-1/workspace0/last-image",
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to run xfconf-query: {}", e))?;
|
||||
|
||||
if output.status.success() {
|
||||
let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||
if PathBuf::from(&path).exists() {
|
||||
return Ok(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try generic monitor path
|
||||
let output = Command::new("xfconf-query")
|
||||
.args([
|
||||
"-c",
|
||||
"xfce4-desktop",
|
||||
"-l",
|
||||
"-v",
|
||||
])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to list xfce4-desktop properties: {}", e))?;
|
||||
|
||||
if output.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
for line in stdout.lines() {
|
||||
if line.contains("last-image") {
|
||||
// Format: /backdrop/.../last-image /path/to/image
|
||||
let parts: Vec<&str> = line.splitn(2, char::is_whitespace).collect();
|
||||
if parts.len() == 2 {
|
||||
let path = parts[1].trim();
|
||||
if PathBuf::from(path).exists() {
|
||||
return Ok(path.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err("Could not determine XFCE wallpaper".into())
|
||||
}
|
||||
|
||||
// --- Parsing helpers ---
|
||||
|
||||
/// Parse gsettings output like `'file:///path/to/wallpaper.jpg'` into a filesystem path.
|
||||
fn parse_gsettings_uri(raw: &str) -> Option<String> {
|
||||
let trimmed = raw.trim().trim_matches('\'').trim_matches('"');
|
||||
parse_file_uri(trimmed).or_else(|| {
|
||||
// Some gsettings return plain paths
|
||||
if PathBuf::from(trimmed).is_absolute() {
|
||||
Some(trimmed.to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Extract filesystem path from `file:///path` URI.
|
||||
fn parse_file_uri(uri: &str) -> Option<String> {
|
||||
if let Some(path) = uri.strip_prefix("file://") {
|
||||
// URL-decode basic cases (spaces as %20)
|
||||
let decoded = path.replace("%20", " ");
|
||||
Some(decoded)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse "r,g,b" CSV format (KDE).
|
||||
fn parse_rgb_csv(value: &str) -> Result<PaletteColor, String> {
|
||||
let parts: Vec<&str> = value.split(',').collect();
|
||||
if parts.len() < 3 {
|
||||
return Err(format!("Invalid RGB CSV: {}", value));
|
||||
}
|
||||
let r = parts[0]
|
||||
.trim()
|
||||
.parse::<u8>()
|
||||
.map_err(|_| format!("Invalid R value: {}", parts[0]))?;
|
||||
let g = parts[1]
|
||||
.trim()
|
||||
.parse::<u8>()
|
||||
.map_err(|_| format!("Invalid G value: {}", parts[1]))?;
|
||||
let b = parts[2]
|
||||
.trim()
|
||||
.parse::<u8>()
|
||||
.map_err(|_| format!("Invalid B value: {}", parts[2]))?;
|
||||
Ok(PaletteColor::new(r, g, b))
|
||||
}
|
||||
|
||||
/// Best-effort extraction of image path from COSMIC config content.
|
||||
fn extract_path_from_cosmic_config(content: &str) -> Option<String> {
|
||||
// COSMIC config may have paths in various formats
|
||||
// Look for common image file patterns
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim().trim_matches('"').trim_matches('\'');
|
||||
|
||||
// Check for file:// URI
|
||||
if let Some(path) = parse_file_uri(trimmed) {
|
||||
if is_image_path(&path) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for absolute path to an image
|
||||
if trimmed.starts_with('/') && is_image_path(trimmed) {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
|
||||
// Look for path embedded in the line (e.g., in RON format)
|
||||
if let Some(start) = trimmed.find('/') {
|
||||
let potential = &trimmed[start..];
|
||||
// Find end of path (before closing quote/paren)
|
||||
let end = potential
|
||||
.find(|c: char| c == '"' || c == '\'' || c == ')' || c == ',')
|
||||
.unwrap_or(potential.len());
|
||||
let path = &potential[..end];
|
||||
if is_image_path(path) && PathBuf::from(path).is_absolute() {
|
||||
return Some(path.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Parse COSMIC color format (may be RON-like with RGBA floats).
|
||||
fn parse_cosmic_color(content: &str) -> Option<PaletteColor> {
|
||||
// COSMIC accent is typically stored as float RGBA (0.0-1.0)
|
||||
// Try to extract numeric values
|
||||
let nums: Vec<f64> = content
|
||||
.split(|c: char| !c.is_ascii_digit() && c != '.' && c != '-')
|
||||
.filter_map(|s| s.parse::<f64>().ok())
|
||||
.collect();
|
||||
|
||||
if nums.len() >= 3 {
|
||||
// Check if values are in 0-1 range (float) or 0-255 range (int)
|
||||
let (r, g, b) = if nums[0] <= 1.0 && nums[1] <= 1.0 && nums[2] <= 1.0 {
|
||||
(
|
||||
(nums[0] * 255.0).round() as u8,
|
||||
(nums[1] * 255.0).round() as u8,
|
||||
(nums[2] * 255.0).round() as u8,
|
||||
)
|
||||
} else {
|
||||
(nums[0] as u8, nums[1] as u8, nums[2] as u8)
|
||||
};
|
||||
Some(PaletteColor::new(r, g, b))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_image_path(path: &str) -> bool {
|
||||
let lower = path.to_lowercase();
|
||||
lower.ends_with(".png")
|
||||
|| lower.ends_with(".jpg")
|
||||
|| lower.ends_with(".jpeg")
|
||||
|| lower.ends_with(".webp")
|
||||
|| lower.ends_with(".bmp")
|
||||
|| lower.ends_with(".tiff")
|
||||
|| lower.ends_with(".tif")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_detect_de() {
|
||||
// Just verify it doesn't panic
|
||||
let _de = detect_desktop_environment();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_gsettings_uri() {
|
||||
assert_eq!(
|
||||
parse_gsettings_uri("'file:///home/user/wallpaper.jpg'"),
|
||||
Some("/home/user/wallpaper.jpg".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_gsettings_uri("'file:///home/user/my%20wallpaper.png'"),
|
||||
Some("/home/user/my wallpaper.png".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_file_uri() {
|
||||
assert_eq!(
|
||||
parse_file_uri("file:///home/user/pic.jpg"),
|
||||
Some("/home/user/pic.jpg".to_string())
|
||||
);
|
||||
assert_eq!(parse_file_uri("/just/a/path"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_rgb_csv() {
|
||||
let color = parse_rgb_csv("66,133,244").unwrap();
|
||||
assert_eq!(color, PaletteColor::new(66, 133, 244));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_rgb_csv_with_spaces() {
|
||||
let color = parse_rgb_csv(" 66 , 133 , 244 ").unwrap();
|
||||
assert_eq!(color, PaletteColor::new(66, 133, 244));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_cosmic_color_float() {
|
||||
let color = parse_cosmic_color("(0.26, 0.52, 0.96, 1.0)").unwrap();
|
||||
assert_eq!(color.r, 66);
|
||||
assert_eq!(color.g, 133);
|
||||
assert_eq!(color.b, 245);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_image_path() {
|
||||
assert!(is_image_path("/home/user/wall.jpg"));
|
||||
assert!(is_image_path("/home/user/wall.PNG"));
|
||||
assert!(is_image_path("/home/user/wall.webp"));
|
||||
assert!(!is_image_path("/home/user/wall.mp4"));
|
||||
assert!(!is_image_path("/home/user/wall.txt"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ pub mod runtime;
|
||||
pub mod session_lifecycle;
|
||||
pub mod tauri_adapter;
|
||||
|
||||
pub mod auto_theme;
|
||||
|
||||
pub mod api;
|
||||
pub mod api_cache;
|
||||
pub mod api_server;
|
||||
|
||||
Reference in new issue
Block a user