Files
dotfiles/scripts/daynight-hooks.py
T

124 lines
4.0 KiB
Python

"""Follow Plasma's light/dark switch.
On start and on every xdg-portal colour-scheme change:
* points each activity's slideshow at the matching light/ or dark/ wallpaper folder
* sets Konsole's default profile (konsole-daynight only reacts to changes, not boot)
Activities and folders come from ~/.config/dotfiles/activities.json (written by home-manager).
"""
import json
import os
import subprocess
import sys
from pathlib import Path
from gi.repository import GLib
from pydbus import SessionBus
CONFIG = Path.home() / ".config/dotfiles/activities.json"
def current_scheme(bus) -> str:
portal = bus.get("org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop")
try:
value = portal.ReadOne("org.freedesktop.appearance", "color-scheme")
except Exception:
value = portal.Read("org.freedesktop.appearance", "color-scheme")
# 1 = prefer dark, 2 = prefer light, 0 = no preference (treat as light)
return "dark" if int(value) == 1 else "light"
def plasma_script(js: str) -> None:
for qdbus in ("qdbus6", "qdbus"):
try:
subprocess.run(
[qdbus, "org.kde.plasmashell", "/PlasmaShell", "org.kde.PlasmaShell.evaluateScript", js],
check=True,
capture_output=True,
)
return
except FileNotFoundError:
continue
def apply(scheme: str) -> None:
cfg = json.loads(CONFIG.read_text())
activities = []
for name, a in cfg["activities"].items():
folder = Path(os.path.expanduser(a["wallpapers"]))
sub = folder / scheme
# Fall back to the whole folder until `dot wallpapers` has sorted it.
paths = [str(sub)] if sub.is_dir() and any(sub.iterdir()) else [str(folder)]
activities.append({"name": name, "paths": paths, "interval": a["interval"]})
js = """
const wanted = %s;
for (const id of activities()) {
const name = activityName(id);
const w = wanted.find(x => x.name === name);
if (!w) continue;
for (const d of desktopsForActivity(id)) {
d.wallpaperPlugin = "org.kde.slideshow";
d.currentConfigGroup = ["Wallpaper", "org.kde.slideshow", "General"];
d.writeConfig("SlidePaths", w.paths);
d.writeConfig("SlideInterval", w.interval);
d.writeConfig("SlideshowMode", "Random");
d.writeConfig("FillMode", 2);
d.reloadConfig();
}
}
""" % json.dumps(activities)
plasma_script(js)
profile = cfg.get("konsole", {}).get(scheme)
if profile:
subprocess.run(
["kwriteconfig6", "--file", "konsolerc", "--group", "Desktop Entry", "--key", "DefaultProfile", f"{profile}.profile"],
check=False,
)
print(f"applied {scheme}", flush=True)
def ensure_activities(bus) -> None:
"""Create the configured activities; the stock "Default" one becomes the first."""
names = list(json.loads(CONFIG.read_text())["activities"])
am = bus.get("org.kde.ActivityManager", "/ActivityManager/Activities")
existing = {am.ActivityName(i): i for i in am.ListActivities()}
for name in names:
if name in existing:
continue
if "Default" in existing and names[0] == name:
am.SetActivityName(existing.pop("Default"), name)
else:
am.AddActivity(name)
def main() -> None:
bus = SessionBus()
try:
ensure_activities(bus)
except Exception as exc: # activity manager may not be up yet on a cold login
print(f"activities: {exc}", flush=True)
last = current_scheme(bus)
apply(last)
if "--once" in sys.argv:
return
portal = bus.get("org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop")
def changed(namespace, key, value):
nonlocal last
if namespace == "org.freedesktop.appearance" and key == "color-scheme":
scheme = "dark" if int(value) == 1 else "light"
if scheme != last:
last = scheme
apply(scheme)
portal.SettingChanged.connect(changed)
GLib.MainLoop().run()
if __name__ == "__main__":
main()