Files
skygqts/workspace-manager/Compositor.qml
T
2026-10-16 15:18:18 -04:00

607 lines
21 KiB
QML

import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Hyprland
import Quickshell.Wayland
// Talks to whichever compositor is running. Everything goes through the
// command line tools so this file works the same on niri and Hyprland.
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 "";
}
readonly property string logoSource: {
if (root.kind === "niri")
return Qt.resolvedUrl("assets/niri.png");
if (root.kind === "hyprland")
return Qt.resolvedUrl("assets/hyprland.png");
return "";
}
// Monitors left to right, each with its workspaces in order.
// A nested list of parsed JSON, so this stays an untyped array.
property var monitors: []
// Output name -> { x, y, known, activeId, monitorFocused }.
// Held between the two query steps. Same reason as monitors.
property var outputLayout: ({})
// Raw workspace JSON saved between the workspaces and windows query stages.
property var workspaceData: []
// Normalized windows, left to right, with { title, app, id, key, focused,
// captureId, preview }. id is the workspace id. key is the niri window id
// or the Hyprland address. captureId is what the snapshot tool needs: the
// niri window id, or the Hyprland stableId. preview is the snapshot file,
// "" when snapshots are off.
property var windowList: []
// Live Hyprland previews.
required property bool livePreviews
// Still snapshots for previews, per compositor. See Theme.qml.
required property bool snapshotPreviewsHyprland
required property bool snapshotPreviewsNiri
readonly property bool snapshotPreviews: {
if (root.kind === "niri")
return root.snapshotPreviewsNiri;
if (root.kind === "hyprland")
return root.snapshotPreviewsHyprland;
return false;
}
// Bumped after each snapshot so preview images load again.
property int previewVersion: 0
// Window keys still waiting for a snapshot.
property list<string> shotQueue: []
readonly property string previewDir: {
const dir = Quickshell.env("XDG_RUNTIME_DIR");
return dir ? dir : "/tmp";
}
// "" while idle, otherwise the query step currently running.
property string queryStage: ""
property bool refreshQueued: false
// False while a query is being restarted, so a leftover finish is ignored.
property bool acceptStream: false
// Niri IPC responses come wrapped in {"Ok": {"Variant": value}}.
// This helper unwraps them so the rest of the code sees bare arrays/objects.
function unwrapJson(text: string): var {
const parsed = JSON.parse(text);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
if ("Ok" in 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;
}
if ("Err" in parsed) {
console.warn("workspace-manager: compositor IPC error:", parsed.Err);
return null;
}
}
return parsed;
}
// Argv arrays waiting to run. A list of lists, so this stays untyped.
property var focusQueue: []
property var focusPending: []
property bool focusRestart: false
signal refreshed
function refresh(): void {
if (root.kind === "")
return;
if (root.queryStage !== "") {
root.refreshQueued = true;
return;
}
root.startStage(root.kind === "niri" ? "outputs" : "monitors");
}
function startStage(stage: string): void {
root.acceptStream = false;
query.running = false;
root.queryStage = stage;
if (stage === "outputs")
query.command = ["niri", "msg", "--json", "outputs"];
else if (stage === "monitors")
query.command = ["hyprctl", "-j", "monitors"];
else if (stage === "workspaces") {
if (root.kind === "niri")
query.command = ["niri", "msg", "--json", "workspaces"];
else
query.command = ["hyprctl", "-j", "workspaces"];
} else if (stage === "windows") {
if (root.kind === "niri")
query.command = ["niri", "msg", "--json", "windows"];
else
query.command = ["hyprctl", "-j", "clients"];
}
root.acceptStream = true;
query.running = true;
}
function finishQuery(): void {
root.queryStage = "";
if (!root.refreshQueued)
return;
root.refreshQueued = false;
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;
}
// Some Hyprland releases report a numeric "id", newer ones only a
// string "address" (numeric for ordinary workspaces). Accept either.
function hyprWorkspaceId(ws): int {
if (!ws)
return -1;
return root.asNumber(ws.id ?? ws.address, -1);
}
function parseOutputs(parsed): void {
const layout = {};
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
// niri format: HashMap<String, Output>
const names = Object.keys(parsed);
for (let i = 0; i < names.length; i++) {
const out = parsed[names[i]];
const name = root.asString(out.name);
if (name.length === 0)
continue;
const logical = out.logical ?? {};
const x = root.asNumber(logical.x, 0);
const y = root.asNumber(logical.y, 0);
const known = Number.isFinite(Number(logical.x)) && Number.isFinite(Number(logical.y));
layout[name] = {
x: x,
y: y,
known: known,
activeId: -1,
monitorFocused: false
};
}
} else {
// Hyprland format: Array (unused, Hyprland uses parseMonitors)
const list = Array.isArray(parsed) ? parsed : [];
for (let i = 0; i < list.length; i++) {
const out = list[i];
const name = root.asString(out.name);
if (name.length === 0)
continue;
const logical = out.logical ?? {};
const x = root.asNumber(logical.x, 0);
const y = root.asNumber(logical.y, 0);
const known = Number.isFinite(Number(logical.x)) && Number.isFinite(Number(logical.y));
layout[name] = {
x: x,
y: y,
known: known,
activeId: -1,
monitorFocused: false
};
}
}
root.outputLayout = layout;
}
function parseMonitors(parsed): void {
const layout = {};
const list = Array.isArray(parsed) ? parsed : [];
for (let i = 0; i < list.length; i++) {
const mon = list[i];
const name = root.asString(mon.name);
if (name.length === 0)
continue;
const known = Number.isFinite(Number(mon.x)) && Number.isFinite(Number(mon.y));
const active = mon.activeWorkspace ?? {};
layout[name] = {
x: root.asNumber(mon.x, 0),
y: root.asNumber(mon.y, 0),
known: known,
activeId: root.hyprWorkspaceId(active),
monitorFocused: mon.focused === true
};
}
root.outputLayout = layout;
}
// Hyprland reports the numeric id as the name when the workspace has none.
function workspaceName(rawName, id: int): string {
const name = root.asString(rawName);
if (root.kind === "hyprland" && name === String(id))
return "";
return name;
}
function parseWindows(parsed): void {
const list = Array.isArray(parsed) ? parsed : [];
const windows = [];
for (let i = 0; i < list.length; i++) {
const w = list[i];
let title, app, id, key, captureId, focused, sortA, sortB;
if (root.kind === "niri") {
title = root.asString(w.title);
app = root.asString(w.app_id);
id = root.asNumber(w.workspace_id, -1);
key = root.asString(w.id);
captureId = key;
focused = w.is_focused === true;
// Tiled windows sort by column then row. Floating ones have
// no position and go last.
const pos = w.layout?.pos_in_scrolling_layout;
const tiled = Array.isArray(pos) && pos.length >= 2;
sortA = tiled ? root.asNumber(pos[0], 0) : Number.MAX_SAFE_INTEGER;
sortB = tiled ? root.asNumber(pos[1], 0) : i;
} else {
if (w.mapped === false)
continue;
title = root.asString(w.title);
app = root.asString(w.class);
id = root.hyprWorkspaceId(w.workspace);
key = root.asString(w.address);
captureId = root.asString(w.stableId);
focused = root.asNumber(w.focusHistoryID, -1) === 0;
const at = Array.isArray(w.at) ? w.at : [0, 0];
sortA = root.asNumber(at[0], 0);
sortB = root.asNumber(at[1], 0);
}
if (id < 0)
continue;
windows.push({
title: title,
app: app,
id: id,
key: key,
captureId: captureId,
focused: focused,
sortA: sortA,
sortB: sortB
});
}
windows.sort((a, b) => a.sortA !== b.sortA ? a.sortA - b.sortA : a.sortB - b.sortB);
root.windowList = windows.map(w => ({
title: w.title,
app: w.app,
id: w.id,
key: w.key,
captureId: w.captureId,
focused: w.focused,
preview: root.snapshotPreviews && w.captureId.length > 0 ? root.previewPath(w.key) : ""
}));
}
// Both niri and Hyprland match windows by workspace id.
function matchWindow(w, output: string, idx: int, id: int): bool {
return w.id === id;
}
function buildMonitors(parsed): void {
const list = Array.isArray(parsed) ? parsed : [];
const groups = {};
let anyFocused = false;
for (let i = 0; i < list.length; i++) {
const ws = list[i];
const id = root.kind === "hyprland" ? root.hyprWorkspaceId(ws) : root.asNumber(ws.id, -1);
if (root.kind === "hyprland" && id < 0)
continue;
const output = root.asString(root.kind === "niri" ? ws.output : ws.monitor);
const idx = root.kind === "niri" ? root.asNumber(ws.idx, 0) : id;
const name = root.workspaceName(ws.name, id);
const meta = root.outputLayout[output] ?? {};
const active = root.kind === "niri" ? ws.is_active === true : id === meta.activeId;
const focused = root.kind === "niri" ? ws.is_focused === true : active && meta.monitorFocused === true;
if (!groups[output])
groups[output] = [];
groups[output].push({
id: id,
idx: idx,
name: name,
active: active,
focused: focused
});
if (focused)
anyFocused = true;
}
const names = Object.keys(groups);
names.sort((a, b) => root.compareOutputs(a, b));
const built = [];
for (let i = 0; i < names.length; i++) {
const name = names[i];
const workspaces = groups[name];
workspaces.sort((a, b) => a.idx - b.idx);
for (let j = 0; j < workspaces.length; j++) {
const ws = workspaces[j];
ws.windows = root.windowList.filter(w => root.matchWindow(w, name, ws.idx, ws.id));
}
// Hide empty workspaces unless they are the active one on this monitor.
const visible = workspaces.filter(ws => ws.active || ws.windows.length > 0);
const pos = root.outputLayout[name] ?? {};
built.push({
name: name,
x: root.asNumber(pos.x, 0),
y: root.asNumber(pos.y, 0),
workspaces: visible
});
}
if (!anyFocused)
console.warn("workspace-manager: no focused workspace reported");
root.monitors = built;
root.refreshed();
}
// The workspace with this id from monitors, or null.
function workspaceById(id: int): var {
const mons = root.monitors;
for (let i = 0; i < mons.length; i++) {
const found = (mons[i].workspaces ?? []).find(ws => ws.id === id);
if (found)
return found;
}
return null;
}
function previewPath(key: string): string {
return root.previewDir + "/skygqts-window-carousel-" + key + ".png";
}
// Live capture handle for a Hyprland window, null when there is none.
function toplevelFor(key: string): Toplevel {
if (root.kind !== "hyprland" || !root.livePreviews)
return null;
const wanted = key.toLowerCase().replace(/^0x/, "");
const list = Hyprland.toplevels.values;
for (let i = 0; i < list.length; i++) {
if (list[i].address.toLowerCase().replace(/^0x/, "") === wanted)
return list[i].wayland;
}
return null;
}
// Snapshot these windows one at a time.
function takeScreenshots(keys: list<string>): void {
if (!root.snapshotPreviews)
return;
root.shotQueue = keys;
if (!shotProc.running)
root.nextScreenshot();
}
function nextScreenshot(): void {
if (root.shotQueue.length === 0) {
// The last file may still be settling, so look again shortly.
shotSettle.restart();
return;
}
const key = root.shotQueue[0];
root.shotQueue = root.shotQueue.slice(1);
const w = root.windowList.find(item => item.key === key);
if (!w || w.captureId.length === 0) {
root.nextScreenshot();
return;
}
const path = root.previewPath(key);
if (root.kind === "niri") {
shotProc.command = ["niri", "msg", "action", "screenshot-window", "--id", w.captureId, "--write-to-disk", "true", "--path", path];
} else {
shotProc.command = ["grim", "-T", w.captureId, path];
}
shotProc.running = true;
}
function focusWindow(key: string): void {
if (key.length === 0)
return;
if (root.kind === "niri")
action.command = ["niri", "msg", "action", "focus-window", "--id", key];
else if (root.kind === "hyprland")
action.command = ["hyprctl", "dispatch", "focuswindow", "address:" + key];
else
return;
action.running = false;
action.running = true;
}
function compareOutputs(a: string, b: string): int {
const left = root.outputLayout[a] ?? {};
const right = root.outputLayout[b] ?? {};
const leftKnown = left.known === true;
const rightKnown = right.known === true;
if (leftKnown !== rightKnown)
return leftKnown ? -1 : 1;
const xDelta = root.asNumber(left.x, 0) - root.asNumber(right.x, 0);
if (xDelta !== 0)
return xDelta;
const yDelta = root.asNumber(left.y, 0) - root.asNumber(right.y, 0);
if (yDelta !== 0)
return yDelta;
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
// Niri indexes count on the focused monitor only, so focus that monitor
// first, then the index. Hyprland switches by workspace id in one command.
function focusWorkspace(output: string, idx: int, id: int): void {
if (root.kind === "niri") {
const commands = [];
if (output.length > 0)
commands.push(["niri", "msg", "action", "focus-monitor", output]);
commands.push(["niri", "msg", "action", "focus-workspace", String(idx)]);
root.focusQueue = commands;
} else if (root.kind === "hyprland") {
if (id < 0)
return;
root.focusQueue = [["hyprctl", "dispatch", "workspace", String(id)]];
} else {
return;
}
root.pumpFocus();
}
function pumpFocus(): void {
if (root.focusQueue.length === 0)
return;
const next = root.focusQueue[0];
root.focusQueue = root.focusQueue.slice(1);
if (focusProc.running) {
root.focusPending = next;
root.focusRestart = true;
focusProc.running = false;
return;
}
focusProc.command = next;
focusProc.running = true;
}
function afterFocusExit(): void {
if (root.focusRestart) {
root.focusRestart = false;
focusProc.command = root.focusPending;
focusProc.running = true;
return;
}
root.pumpFocus();
}
Process {
id: query
running: false
stdout: StdioCollector {
onStreamFinished: {
if (!root.acceptStream)
return;
root.acceptStream = false;
let parsed = null;
try {
parsed = root.unwrapJson(this.text);
} catch (e) {
console.warn("workspace-manager: could not read workspace data:", e);
if (root.queryStage === "outputs" || root.queryStage === "monitors") {
root.outputLayout = ({ });
root.startStage("workspaces");
return;
}
if (root.queryStage === "windows") {
console.warn("workspace-manager: could not read window data, continuing without windows");
root.windowList = [];
root.buildMonitors(root.workspaceData);
root.finishQuery();
return;
}
root.finishQuery();
return;
}
if (!parsed) {
// unwrapJson returned null (niri IPC error)
root.finishQuery();
return;
}
if (root.queryStage === "outputs") {
root.parseOutputs(parsed);
root.startStage("workspaces");
return;
}
if (root.queryStage === "monitors") {
root.parseMonitors(parsed);
root.startStage("workspaces");
return;
}
if (root.queryStage === "workspaces") {
root.workspaceData = parsed;
root.startStage("windows");
return;
}
root.parseWindows(parsed);
root.buildMonitors(root.workspaceData);
root.finishQuery();
}
}
}
Process {
id: action
running: false
stderr: StdioCollector {
onStreamFinished: {
if (this.text.trim().length > 0)
console.warn("workspace-manager:", this.text.trim());
}
}
}
Process {
id: shotProc
running: false
onExited: {
root.previewVersion += 1;
root.nextScreenshot();
}
stderr: StdioCollector {
onStreamFinished: {
if (this.text.trim().length > 0)
console.warn("workspace-manager:", this.text.trim());
}
}
}
Timer {
id: shotSettle
interval: 300
onTriggered: root.previewVersion += 1
}
Process {
id: focusProc
running: false
onExited: root.afterFocusExit()
stderr: StdioCollector {
onStreamFinished: {
if (this.text.trim().length > 0)
console.warn("workspace-manager:", this.text.trim());
}
}
}
}