repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
ironbar/scripts/workspaces-watch.py
RawFile outline
#!/usr/bin/env python3
import json
import os
import select
import socket
import subprocess
import time
from pathlib import Path
WORKSPACES = [
("1", ""),
("2", ""),
("3", ""),
("4", ""),
("5", ""),
("9", ""),
]
EVENT_PREFIXES = (
"workspace",
"focusedmon",
"createworkspace",
"destroyworkspace",
"moveworkspace",
"openwindow",
"closewindow",
"movewindow",
"urgent",
)
def run(*args: str) -> str:
return subprocess.run(args, text=True, capture_output=True, check=False).stdout
def css_vars() -> dict[str, str]:
config_home = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
colors: dict[str, str] = {}
for line in (config_home / "ironbar" / "nugu.css").read_text().splitlines():
if ":" not in line:
continue
name, value = line.strip().rstrip(";").split(":", 1)
name = name.strip()
value = value.strip()
if name.startswith("--") and value.startswith("#"):
colors[name[2:]] = value
return colors
def markup(ws_id: str, icon: str, active: str, occupied: set[str], colors: dict[str, str]) -> str:
if ws_id == active:
return '<span foreground="{}" background="{}" font_weight="bold"> {} </span>'.format(
colors.get("on-focus", "#121212"),
colors.get("focus", "#9aabae"),
icon,
)
if ws_id in occupied:
return '<span foreground="{}">{}</span>'.format(colors.get("fg", "#dbdbdb"), icon)
return '<span foreground="{}">{}</span>'.format(colors.get("muted", "#9d9d9d"), icon)
def hypr_state() -> tuple[str, set[str]]:
active = json.loads(run("hyprctl", "activeworkspace", "-j") or "{}")
workspaces = json.loads(run("hyprctl", "workspaces", "-j") or "[]")
return str(active.get("id", "")), {str(ws.get("id")) for ws in workspaces if ws.get("windows", 0) > 0}
def set_var(name: str, value: str) -> None:
subprocess.run(("ironbar", "var", "set", name, value), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
def update() -> None:
colors = css_vars()
active, occupied = hypr_state()
for ws_id, icon in WORKSPACES:
set_var(f"ws{ws_id}", markup(ws_id, icon, active, occupied, colors))
def socket_path() -> str:
sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
if not sig:
instances = json.loads(run("hyprctl", "instances", "-j") or "[]")
sig = instances[0]["instance"]
return f"{os.environ['XDG_RUNTIME_DIR']}/hypr/{sig}/.socket2.sock"
def watch() -> None:
while True:
update()
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect(socket_path())
pending = b""
while True:
ready, _, _ = select.select([sock], [], [], 5)
if not ready:
update()
continue
chunk = sock.recv(4096)
if not chunk:
break
pending += chunk
while b"\n" in pending:
raw, pending = pending.split(b"\n", 1)
line = raw.decode("utf-8", "replace")
if line.startswith(EVENT_PREFIXES):
update()
except Exception:
time.sleep(1)
if __name__ == "__main__":
watch()