Files
skygqts/workspace-badge/Compositor.qml
T
2026-10-19 23:36:47 -04:00

273 lines
8.7 KiB
QML

import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Hyprland
// Tracks the active workspace on each monitor and renames workspaces.
// Reads go through the command line tools, like the workspace manager.
Item {
id: root
// "niri", "hyprland" or "" when neither was detected.
readonly property string kind: {
if (Quickshell.env("NIRI_SOCKET"))
return "niri";
if (Quickshell.env("HYPRLAND_INSTANCE_SIGNATURE"))
return "hyprland";
return "";
}
// Output name -> { id, idx, name } of the workspace active there.
// Built from parsed JSON, so this stays an untyped object.
property var outputs: ({})
// Name of the focused output, empty when unknown.
property string focusedOutput: ""
property bool refreshQueued: false
// Argv lists waiting to run, one after another. A list of lists, so untyped.
property var actionQueue: []
Component.onCompleted: {
if (root.kind === "niri")
niriEvents.running = true;
root.refresh();
}
function asString(value): string {
if (value === null || value === undefined)
return "";
return String(value);
}
function asNumber(value, fallback: int): int {
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
function refresh(): void {
if (root.kind === "")
return;
if (query.running) {
root.refreshQueued = true;
return;
}
if (root.kind === "niri")
query.command = ["niri", "msg", "--json", "workspaces"];
else
query.command = ["hyprctl", "-j", "monitors"];
query.running = true;
}
// niri may wrap replies as {"Ok": {"Workspaces": [...]}}.
function unwrap(parsed): var {
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
return parsed;
if ("Err" in parsed) {
console.warn("workspace-badge: compositor error:", parsed.Err);
return [];
}
if (!("Ok" in parsed))
return parsed;
const inner = parsed.Ok;
if (inner && typeof inner === "object" && !Array.isArray(inner)) {
const keys = Object.keys(inner);
if (keys.length === 1)
return inner[keys[0]];
}
return inner;
}
function parseNiri(list): void {
const map = {};
let focused = "";
for (let i = 0; i < list.length; i++) {
const ws = list[i];
if (ws.is_active !== true)
continue;
const output = root.asString(ws.output);
if (output.length === 0)
continue;
map[output] = {
id: root.asNumber(ws.id, -1),
idx: root.asNumber(ws.idx, -1),
name: root.asString(ws.name)
};
if (ws.is_focused === true)
focused = output;
}
root.outputs = map;
root.focusedOutput = focused;
}
function parseHyprland(list): void {
const map = {};
let focused = "";
for (let i = 0; i < list.length; i++) {
const mon = list[i];
const output = root.asString(mon.name);
if (output.length === 0)
continue;
const active = mon.activeWorkspace ?? {};
const id = root.asNumber(active.id, -1);
const name = root.asString(active.name);
map[output] = {
id: id,
idx: id,
// Hyprland uses the id as the name when there is none.
name: name === String(id) ? "" : name
};
if (mon.focused === true)
focused = output;
}
root.outputs = map;
root.focusedOutput = focused;
}
// Names that are only digits would be read by niri as an index.
function niriCanUseName(name: string): bool {
return name.length > 0 && !/^\d+$/.test(name);
}
// Rename the workspace that is active on this output. An empty name
// clears it.
function rename(output: string, id: int, oldName: string, newName: string): void {
const name = newName.trim();
if (root.kind === "niri") {
if (root.niriCanUseName(oldName)) {
if (name.length > 0)
root.runAll([["niri", "msg", "action", "set-workspace-name", "--workspace", oldName, name]]);
else
root.runAll([["niri", "msg", "action", "unset-workspace-name", oldName]]);
return;
}
if (oldName.length === 0 && name.length === 0)
return;
// No name to point at, and niri has no way to point at an id,
// so focus the monitor and rename its active workspace.
const step = name.length > 0 ? ["niri", "msg", "action", "set-workspace-name", name] : ["niri", "msg", "action", "unset-workspace-name"];
root.runAll([["niri", "msg", "action", "focus-monitor", output], step]);
} else if (root.kind === "hyprland") {
if (id < 0)
return;
const idText = String(id);
// Hyprland has no "clear name", so fall back to the numeric id.
const label = name.length > 0 ? name : idText;
root.runAll([["hyprctl", "dispatch", "hl.dsp.workspace.rename({ workspace = " + idText + ", name = " + root.luaString(label) + " })"]]);
}
}
// Quote a string for a Lua expression (Hyprland 0.55+ takes Lua).
function luaString(text: string): string {
return "\"" + text.replace(/[\r\n]+/g, " ").replace(/[\\"]/g, "\\$&") + "\"";
}
function runAll(commands): void {
root.actionQueue = root.actionQueue.concat(commands);
if (!action.running)
root.runNext();
}
function runNext(): void {
if (root.actionQueue.length === 0) {
refreshTimer.restart();
return;
}
action.command = root.actionQueue[0];
root.actionQueue = root.actionQueue.slice(1);
action.running = true;
}
// Many events can arrive at once, so wait a moment and read once.
Timer {
id: refreshTimer
interval: 50
onTriggered: root.refresh()
}
Process {
id: query
running: false
onExited: {
if (!root.refreshQueued)
return;
root.refreshQueued = false;
refreshTimer.restart();
}
stdout: StdioCollector {
onStreamFinished: {
let parsed = null;
try {
parsed = root.unwrap(JSON.parse(this.text));
} catch (e) {
console.warn("workspace-badge: could not read workspace data:", e);
return;
}
const list = Array.isArray(parsed) ? parsed : [];
if (root.kind === "niri")
root.parseNiri(list);
else
root.parseHyprland(list);
}
}
}
Process {
id: action
running: false
onExited: root.runNext()
// hyprctl prints its errors on stdout and says "ok" on success.
stdout: StdioCollector {
onStreamFinished: {
const text = this.text.trim();
if (text.length > 0 && text !== "ok")
console.warn("workspace-badge:", text);
}
}
stderr: StdioCollector {
onStreamFinished: {
if (this.text.trim().length > 0)
console.warn("workspace-badge:", this.text.trim());
}
}
}
// niri: one JSON event per line. Read again on any workspace change.
Process {
id: niriEvents
running: false
command: ["niri", "msg", "--json", "event-stream"]
onExited: niriRetry.start()
stdout: SplitParser {
onRead: data => {
if (data.startsWith("{\"Workspace"))
refreshTimer.restart();
}
}
}
// Start the niri event stream again if it stops, e.g. after niri restarts.
Timer {
id: niriRetry
interval: 2000
onTriggered: niriEvents.running = true
}
// Hyprland: read again on workspace and monitor events.
Connections {
target: root.kind === "hyprland" ? Hyprland : null
function onRawEvent(event: HyprlandEvent): void {
const name = event.name;
if (name.indexOf("workspace") >= 0 || name.startsWith("monitor") || name.startsWith("focusedmon"))
refreshTimer.restart();
}
}
}