nixos/shared/modules/services/theme_switcher/apply_themes.py
2026-01-23 13:44:07 -07:00

244 lines
8.6 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Apply Themes Script - Applies GTK/Kvantum/Helix themes after pywal runs.
This script:
1. Links GTK CSS files from pywal cache
2. Sets GTK color scheme preference based on light/dark mode
3. Copies and applies Kvantum theme
4. Copies Helix theme to config directory
5. Optionally runs color_mapper.py for semantic color mapping
"""
import json
import shutil
import subprocess
import sys
from pathlib import Path
import logging
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s: %(message)s'
)
logger = logging.getLogger(__name__)
class ThemeApplicator:
"""Applies themes after pywal has generated color palette."""
def __init__(self):
self.home = Path.home()
self.cache_dir = self.home / ".cache/wal"
self.config_dir = self.home / ".config"
def is_light_mode(self) -> bool:
"""
Determine if current theme is light mode by checking pywal cache.
Returns:
True if light mode, False if dark mode
"""
colors_json = self.cache_dir / "colors.json"
if not colors_json.exists():
logger.warning("colors.json not found, assuming dark mode")
return False
try:
with open(colors_json) as f:
data = json.load(f)
return data.get("special", {}).get("light", False)
except (json.JSONDecodeError, KeyError) as e:
logger.warning(f"Failed to parse colors.json: {e}, assuming dark mode")
return False
def setup_gtk_themes(self) -> None:
"""Link GTK CSS files from pywal cache."""
gtk3_dir = self.config_dir / "gtk-3.0"
gtk4_dir = self.config_dir / "gtk-4.0"
# Ensure directories exist
gtk3_dir.mkdir(parents=True, exist_ok=True)
gtk4_dir.mkdir(parents=True, exist_ok=True)
# Link GTK 3.0 CSS
gtk3_source = self.cache_dir / "gtk-3.0.css"
gtk3_target = gtk3_dir / "gtk.css"
if gtk3_source.exists():
# Remove old symlink/file
if gtk3_target.exists() or gtk3_target.is_symlink():
gtk3_target.unlink()
gtk3_target.symlink_to(gtk3_source)
logger.info(f"Linked GTK 3.0 theme: {gtk3_target}")
else:
logger.warning(f"GTK 3.0 CSS not found: {gtk3_source}")
# Link GTK 4.0 CSS
gtk4_source = self.cache_dir / "gtk-4.0.css"
gtk4_target = gtk4_dir / "gtk.css"
if gtk4_source.exists():
# Remove old symlink/file
if gtk4_target.exists() or gtk4_target.is_symlink():
gtk4_target.unlink()
gtk4_target.symlink_to(gtk4_source)
logger.info(f"Linked GTK 4.0 theme: {gtk4_target}")
else:
logger.warning(f"GTK 4.0 CSS not found: {gtk4_source}")
def set_gtk_color_scheme(self, is_light: bool) -> None:
"""
Set GTK color scheme preference using gsettings.
Args:
is_light: True for light mode, False for dark mode
"""
scheme = "prefer-light" if is_light else "prefer-dark"
try:
subprocess.run(
['gsettings', 'set', 'org.gnome.desktop.interface', 'color-scheme', scheme],
check=True,
timeout=5,
capture_output=True
)
logger.info(f"Set GTK color scheme to: {scheme}")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError) as e:
logger.warning(f"Failed to set GTK color scheme (this is normal if not using GNOME): {e}")
def setup_kvantum_theme(self) -> None:
"""Copy and apply Kvantum theme from pywal cache."""
kvantum_dir = self.config_dir / "Kvantum/PywalTheme"
kvantum_dir.mkdir(parents=True, exist_ok=True)
# Copy Kvantum config
kvantum_source = self.cache_dir / "PywalTheme.kvconfig"
kvantum_target = kvantum_dir / "PywalTheme.kvconfig"
if kvantum_source.exists():
shutil.copy2(kvantum_source, kvantum_target)
logger.info(f"Copied Kvantum theme: {kvantum_target}")
# Apply Kvantum theme
try:
subprocess.run(
['kvantummanager', '--set', 'PywalTheme'],
check=True,
timeout=5,
capture_output=True
)
logger.info("Applied Kvantum theme: PywalTheme")
except FileNotFoundError:
logger.warning("kvantummanager not found, skipping Kvantum theme application")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
logger.warning(f"Failed to apply Kvantum theme: {e}")
else:
logger.warning(f"Kvantum theme not found: {kvantum_source}")
def setup_helix_theme(self) -> None:
"""Copy Helix theme from pywal cache to config directory."""
helix_themes_dir = self.config_dir / "helix/themes"
helix_themes_dir.mkdir(parents=True, exist_ok=True)
# Copy minimal Helix theme
helix_source = self.cache_dir / "helix_minimal.toml"
helix_target = helix_themes_dir / "pywal_minimal.toml"
if helix_source.exists():
shutil.copy2(helix_source, helix_target)
logger.info(f"Updated Helix theme: pywal_minimal")
else:
logger.warning(f"Helix theme not found: {helix_source}")
# Copy semantic Helix theme if it exists
helix_semantic_source = self.cache_dir / "helix_semantic.toml"
helix_semantic_target = helix_themes_dir / "pywal_semantic.toml"
if helix_semantic_source.exists():
shutil.copy2(helix_semantic_source, helix_semantic_target)
logger.info(f"Updated Helix semantic theme: pywal_semantic")
def run_color_mapper(self) -> None:
"""
Run color_mapper.py to generate semantic color mappings.
This is optional and will only run if the script exists.
"""
# Look for color_mapper.py in the same directory as this script
script_dir = Path(__file__).parent
color_mapper = script_dir / "color_mapper.py"
if not color_mapper.exists():
logger.debug(f"color_mapper.py not found at {color_mapper}, skipping")
return
try:
result = subprocess.run(
['python3', str(color_mapper)],
capture_output=True,
text=True,
timeout=10,
check=True
)
logger.info("Applied semantic color mapping")
# Log color mapper output for debugging
if result.stdout:
for line in result.stdout.strip().split('\n'):
logger.debug(f"color_mapper: {line}")
except FileNotFoundError:
logger.warning("python3 not found, skipping color mapper")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
logger.warning(f"Failed to run color_mapper.py: {e}")
def run(self) -> int:
"""
Execute theme application process.
Returns:
Exit code (0 for success, 1 for failure)
"""
try:
# Check if pywal has been run
if not self.cache_dir.exists():
logger.error(f"Pywal cache not found: {self.cache_dir}")
logger.error("Please run pywal first")
return 1
# Determine mode
is_light = self.is_light_mode()
mode = "light" if is_light else "dark"
logger.info(f"Applying {mode} mode themes")
# Setup GTK themes
self.setup_gtk_themes()
self.set_gtk_color_scheme(is_light)
# Setup Kvantum theme
self.setup_kvantum_theme()
# Setup Helix theme
self.setup_helix_theme()
# Run color mapper for semantic themes
self.run_color_mapper()
logger.info("All themes applied successfully")
return 0
except Exception as e:
logger.error(f"Theme application failed: {e}", exc_info=True)
return 1
def main():
"""Main entry point."""
applicator = ThemeApplicator()
return applicator.run()
if __name__ == '__main__':
sys.exit(main())