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",
)
last_vars: dict[str, str] = {}
color_mtime = 0
color_vars: dict[str, str] = {}
hypr_socket_dir = ""
def css_vars() -> dict[str, str]:
global color_mtime, color_vars
config_home = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
path = config_home / "ironbar" / "nugu.css"
mtime = path.stat().st_mtime_ns
if mtime == color_mtime:
return color_vars
colors: dict[str, str] = {}
for line in path.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
color_mtime = mtime
color_vars = colors
return colors
def hypr_dir() -> str:
global hypr_socket_dir
if hypr_socket_dir:
return hypr_socket_dir
sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
if not sig:
result = subprocess.run(("hyprctl", "instances", "-j"), text=True, capture_output=True, check=False)
instances = json.loads(result.stdout or "[]")
sig = instances[0]["instance"]
hypr_socket_dir = f"{os.environ['XDG_RUNTIME_DIR']}/hypr/{sig}"
return hypr_socket_dir
def hypr_cmd(command: str) -> str:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(1)
sock.connect(f"{hypr_dir()}/.socket.sock")
sock.sendall(command.encode())
chunks: list[bytes] = []
while True:
chunk = sock.recv(65536)
if not chunk:
break
chunks.append(chunk)
return b"".join(chunks).decode("utf-8", "replace")
def event_socket_path() -> str:
return f"{hypr_dir()}/.socket2.sock"
def markup(ws_id: str, icon: str, active: str, occupied: set[str], colors: dict[str, str]) -> str:
label = f"{ws_id} {icon}"
if ws_id == active:
return '<span foreground="{}">{}</span>'.format(colors["important-global"], label)
if ws_id in occupied:
return '<span foreground="{}">{}</span>'.format(colors["fg"], label)
return '<span foreground="{}">{}</span>'.format(colors["muted"], label)
def hypr_state() -> tuple[str, set[str]]:
active = json.loads(hypr_cmd("j/activeworkspace") or "{}")
workspaces = json.loads(hypr_cmd("j/workspaces") 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:
if last_vars.get(name) == value:
return
result = subprocess.run(("ironbar", "var", "set", name, value), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
if result.returncode == 0:
last_vars[name] = value
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 watch() -> None:
global hypr_socket_dir
while True:
update()
try:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.connect(event_socket_path())
pending = b""
while True:
ready, _, _ = select.select([sock], [], [], 10)
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:
hypr_socket_dir = ""
time.sleep(1)
if __name__ == "__main__":
watch()