Theme presets, and make the bar itself actually re-theme (colors + opacity)

Presets (theme/presets.py): named snapshots of the whole palette, saved/loaded/
deleted from a new bookmark button on the theme widget. Stored outside the
repo in ~/.local/share/quickshell/theme-presets/ (JSON, per-machine data, same
precedent as the wallpaper history). A built-in Default entry can't be
overwritten or deleted.

Wiring that up exposed a real gap: the bar's own colors were hand-matched
hardcoded QML literals, not actually driven by theme/colors.toml, and opacity
wasn't themeable anywhere yet. Fixed both:
- colors.toml gains bar_color/pill_color/popup_color (paired with the existing
  *_opacity floats) plus generic opacity support in render.py (--set now
  accepts a 0-1 float, not just #rrggbb)
- Bar.qml now fetches the palette via render.py --dump and rebinds every
  matching hardcoded hex literal (accent, foreground, color1/2/3/5/6/8/12,
  the bar/pill/popup backgrounds, the logo tint and the bar's bottom border)
  to it; kitty's background_opacity is template-driven instead of a second
  hardcoded line fighting the themed one
- both the bar and the widget listen on their own Quickshell IPC target
  (render.py/presets.py ping both after every change) so edits reload with no
  restart, matching the "instant" promise the color editor already had
- the theme widget's color popup gained a slider + matching color swatch per
  surface (Bar/Pills/Popups/Terminal) below the existing role list, and its
  role labels now say what each color actually paints instead of "Color N"
  (verified against the templates and Bar.qml's literals, not guessed) with
  unused roles honestly marked as such
- the CPU pill's icon color is deliberately hardcoded again after this -
  it coincidentally shared color12's hex value with the help icon/detail
  text, so theming color12 was recoloring it too

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dujsk9jYfxUVLtb5B8eC94
This commit is contained in:
nico
2026-09-28 22:45:09 +02:00
parent e66691b469
commit 63a56f4a01
10 changed files with 813 additions and 124 deletions

View File

@@ -29,3 +29,15 @@ color12 = "#7aa2f7"
color13 = "#cba6f7"
color14 = "#89dceb"
color15 = "#ffffff"
# Bar/pill/popup background colors (the terminal's is "background" above, already shared
# with mako) - each paired with the matching *_opacity float below for its transparency
bar_color = "#12131b"
pill_color = "#1a1b26"
popup_color = "#1a1b26"
# Opacity (0-1) for the bar itself, its pills, its popups, and the terminal background
bar_opacity = 0.18
pill_opacity = 0.85
popup_opacity = 0.9
terminal_opacity = 0.85

119
theme/presets.py Executable file
View File

@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Named snapshots of the whole palette (theme/colors.toml) - save, load, delete.
presets.py list JSON array of saved presets: [{name, current}, ...]
presets.py default JSON of the built-in Default baseline + whether it's active
presets.py save <name> snapshot the current palette under <name> (overwrites if it exists)
presets.py load <name> apply a saved preset (or "Default") as the active palette,
re-render every themed app's config and reload it
presets.py delete <name> remove a saved preset ("Default" can't be deleted)
Presets are per-machine user data, not project config, so - like the wallpaper history -
they live outside the dotfiles repo, in ~/.local/share/quickshell/theme-presets/.
"""
import json
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import render # noqa: E402 - theme/render.py: load_colors, render_all, reload_apps, COLORS
STORE = os.path.expanduser("~/.local/share/quickshell/theme-presets")
NAME_RE = re.compile(r"^[A-Za-z0-9 _-]{1,40}$")
DEFAULT_NAME = "Default"
DEFAULT_PALETTE = {
"accent": "#1793d1", "cursor": "#c0caf5",
"foreground": "#c0caf5", "background": "#1a1b26",
"selection_foreground": "#1a1b26", "selection_background": "#c0caf5",
"color0": "#1a1b26", "color1": "#f7768e", "color2": "#a6e3a1", "color3": "#f9e2af",
"color4": "#1793d1", "color5": "#cba6f7", "color6": "#89dceb", "color7": "#c0caf5",
"color8": "#565f89", "color9": "#f7768e", "color10": "#a6e3a1", "color11": "#f9e2af",
"color12": "#7aa2f7", "color13": "#cba6f7", "color14": "#89dceb", "color15": "#ffffff",
"bar_color": "#12131b", "pill_color": "#1a1b26", "popup_color": "#1a1b26",
"bar_opacity": 0.18, "pill_opacity": 0.85, "popup_opacity": 0.90, "terminal_opacity": 0.85,
}
def validate_name(name):
if name == DEFAULT_NAME:
sys.exit("presets.py: 'Default' is built in, can't save/delete over it")
if not NAME_RE.match(name):
sys.exit("presets.py: preset names may only use letters, digits, spaces, '-' and '_' "
"(max 40 characters)")
def path_for(name):
return os.path.join(STORE, f"{name}.json")
def list_names():
if not os.path.isdir(STORE):
return []
return sorted(f[:-5] for f in os.listdir(STORE) if f.endswith(".json"))
def load_preset(name):
try:
return json.load(open(path_for(name)))
except OSError:
sys.exit(f"presets.py: no preset named '{name}'")
def cmd_list():
current = render.load_colors()
out = [{"name": n, "current": load_preset(n) == current} for n in list_names()]
print(json.dumps(out))
def cmd_default():
current = render.load_colors()
print(json.dumps({"name": DEFAULT_NAME, "current": DEFAULT_PALETTE == current}))
def cmd_save(name):
validate_name(name)
os.makedirs(STORE, exist_ok=True)
json.dump(render.load_colors(), open(path_for(name), "w"), indent=1)
def cmd_load(name):
palette = DEFAULT_PALETTE if name == DEFAULT_NAME else load_preset(name)
current = render.load_colors()
if palette.keys() - current.keys():
sys.exit(f"presets.py: '{name}' has keys colors.toml doesn't know about "
f"({', '.join(sorted(palette.keys() - current.keys()))})")
# Reuses colors.toml's own regex-substitution updater (same one --set uses) instead of
# rewriting the file, so the comments/section headers a human wrote stay intact.
render.set_colors([(k, str(v)) for k, v in palette.items()])
render.render_all(render.load_colors())
render.reload_apps()
def cmd_delete(name):
validate_name(name)
path = path_for(name)
if not os.path.isfile(path):
sys.exit(f"presets.py: no preset named '{name}'")
os.remove(path)
def main():
args = sys.argv[1:]
if args[:1] == ["list"] and len(args) == 1:
cmd_list()
elif args[:1] == ["default"] and len(args) == 1:
cmd_default()
elif args[:1] == ["save"] and len(args) == 2:
cmd_save(args[1])
elif args[:1] == ["load"] and len(args) == 2:
cmd_load(args[1])
elif args[:1] == ["delete"] and len(args) == 2:
cmd_delete(args[1])
else:
sys.exit(__doc__)
if __name__ == "__main__":
main()

View File

@@ -5,7 +5,7 @@
render.py --no-reload same, but skip reloading apps (used right after --set, which reloads itself)
render.py --dump print every color as JSON (used by ThemeWidget.qml)
render.py --get KEY print one color (e.g. for shell scripts)
render.py --set KEY VALUE [KEY VALUE ...] change one or more colors in colors.toml, re-render, reload
render.py --set KEY VALUE [KEY VALUE ...] change one or more colors/opacities in colors.toml, re-render, reload
Templates live in theme/templates/<app>/{config.json,template}: config.json names the
template file and the destination it gets rendered to (~ expanded). Placeholders in a
@@ -42,7 +42,9 @@ def substitute(text, colors):
sys.exit(f"render.py: unknown color key '{key}' in template")
value = colors[key]
if fmt is None:
return value
return str(value)
if not isinstance(value, str):
sys.exit(f"render.py: '.{fmt}' needs a #rrggbb color, '{key}' is {value!r}")
if fmt == "strip":
return value.lstrip("#")
if fmt == "rgba":
@@ -70,6 +72,13 @@ def reload_apps():
subprocess.run(["hyprctl", "reload"], check=False, capture_output=True)
subprocess.run(["makoctl", "reload"], check=False, capture_output=True)
subprocess.run(["pkill", "--signal", "USR1", "-x", "kitty"], check=False, capture_output=True)
# Best-effort: tell the running shell (bar + theme widget, two separate IPC targets
# since they're two separate top-level QML components) to re-fetch the palette, for
# the bits of it (pill/popup/bar opacity) that only live in QML, not another app's
# config file. A no-op if quickshell isn't running.
for target in ("theme", "theme-widget"):
subprocess.run(["quickshell", "-c", "default", "ipc", "call", target, "changed"],
check=False, capture_output=True, timeout=3)
def set_colors(pairs):
@@ -78,12 +87,24 @@ def set_colors(pairs):
for key, value in pairs:
if key not in colors:
sys.exit(f"render.py: unknown color key '{key}'")
if not re.fullmatch(r"#[0-9a-fA-F]{6}", value):
sys.exit(f"render.py: '{value}' is not a #rrggbb color")
new_text, n = re.subn(rf"(?m)^{re.escape(key)}\s*=\s*\"#[0-9a-fA-F]{{6}}\"",
f'{key} = "{value.lower()}"', text)
if isinstance(colors[key], str):
if not re.fullmatch(r"#[0-9a-fA-F]{6}", value):
sys.exit(f"render.py: '{value}' is not a #rrggbb color")
literal = f'"{value.lower()}"'
pattern = r'"#[0-9a-fA-F]{6}"'
else:
try:
v = float(value)
except ValueError:
sys.exit(f"render.py: '{value}' is not a number (expected 0-1, for '{key}')")
if not 0 <= v <= 1:
sys.exit(f"render.py: '{value}' is out of range (expected 0-1, for '{key}')")
literal = repr(v)
pattern = r"[0-9]*\.?[0-9]+"
new_text, n = re.subn(rf"(?m)^{re.escape(key)}\s*=\s*{pattern}",
f"{key} = {literal}", text)
if n != 1:
sys.exit(f"render.py: could not find a single '{key} = \"...\"' line to replace")
sys.exit(f"render.py: could not find a single '{key} = ...' line to replace")
text = new_text
open(COLORS, "w").write(text)

View File

@@ -3,3 +3,4 @@
background {background}
foreground {foreground}
cursor {cursor}
background_opacity {terminal_opacity}