Files
skygqts/window-carousel/Compositor.qml
T
2026-09-23 11:56:03 -04:00

301 lines
10 KiB
QML

import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Hyprland
import Quickshell.Wayland
// Lists the windows on the focused workspace and focuses one of them.
// Everything goes through the command line tools, so niri and Hyprland
// behave the same way.
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 "";
}
// Take niri screenshots for previews. Each one also replaces the
// clipboard, and niri has no way to turn that off.
required property bool niriScreenshots
// Id of the focused workspace, -1 when unknown.
property int workspaceId: -1
// Windows on the focused workspace, left to right. Each entry is
// { key, title, app, focused, preview }. Built from parsed JSON, so this
// stays an untyped array. key is the niri window id or the Hyprland
// address. preview is a screenshot file on niri, "" otherwise.
property var windows: []
// Bumped after each niri screenshot so preview images load again.
property int previewVersion: 0
// niri window ids still waiting for a screenshot.
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
signal refreshed
function refresh(): void {
if (root.kind === "")
return;
if (root.queryStage !== "") {
root.refreshQueued = true;
return;
}
root.startStage("workspace");
}
function startStage(stage: string): void {
root.acceptStream = false;
query.running = false;
root.queryStage = stage;
if (stage === "workspace") {
if (root.kind === "niri")
query.command = ["niri", "msg", "--json", "workspaces"];
else
query.command = ["hyprctl", "-j", "activeworkspace"];
} else {
if (root.kind === "niri")
query.command = ["niri", "msg", "--json", "windows"];
else
query.command = ["hyprctl", "-j", "clients"];
}
root.acceptStream = true;
query.running = true;
}
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")
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;
}
// Screenshot the listed niri windows one at a time.
function takeScreenshots(): void {
if (root.kind !== "niri" || !root.niriScreenshots)
return;
root.shotQueue = root.windows.map(w => w.key);
if (!shotProc.running)
root.nextScreenshot();
}
function nextScreenshot(): void {
if (root.shotQueue.length === 0) {
// niri may still be writing the last file, so look again shortly.
shotSettle.restart();
return;
}
const key = root.shotQueue[0];
root.shotQueue = root.shotQueue.slice(1);
shotProc.command = ["niri", "msg", "action", "screenshot-window", "--id", key, "--write-to-disk", "true", "--path", root.previewPath(key)];
shotProc.running = true;
}
function finishQuery(): void {
root.queryStage = "";
root.refreshed();
if (!root.refreshQueued)
return;
root.refreshQueued = false;
root.refresh();
}
// Some niri versions wrap replies in {"Ok": {"Variant": value}}.
// This returns the bare value either way, or null on an error reply.
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("window-carousel: compositor IPC error:", parsed.Err);
return null;
}
}
return parsed;
}
function asString(value): string {
if (value === null || value === undefined)
return "";
return String(value);
}
function asNumber(value, fallback: real): real {
const number = Number(value);
return Number.isFinite(number) ? number : fallback;
}
function parseWorkspace(parsed): void {
if (root.kind === "niri") {
const list = Array.isArray(parsed) ? parsed : [];
const focused = list.find(ws => ws.is_focused === true);
root.workspaceId = focused ? root.asNumber(focused.id, -1) : -1;
} else {
root.workspaceId = root.asNumber(parsed?.id, -1);
}
}
function parseWindows(parsed): void {
const list = Array.isArray(parsed) ? parsed : [];
const found = [];
for (let i = 0; i < list.length; i++) {
const w = list[i];
if (root.kind === "niri") {
if (root.asNumber(w.workspace_id, -1) !== root.workspaceId)
continue;
// 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;
found.push({
key: root.asString(w.id),
title: root.asString(w.title),
app: root.asString(w.app_id),
focused: w.is_focused === true,
sortA: tiled ? root.asNumber(pos[0], 0) : Number.MAX_SAFE_INTEGER,
sortB: tiled ? root.asNumber(pos[1], 0) : i
});
} else {
if (w.mapped === false || w.hidden === true)
continue;
if (root.asNumber(w.workspace?.id, -1) !== root.workspaceId)
continue;
const at = Array.isArray(w.at) ? w.at : [0, 0];
found.push({
key: root.asString(w.address),
title: root.asString(w.title),
app: root.asString(w["class"]),
focused: root.asNumber(w.focusHistoryID, -1) === 0,
sortA: root.asNumber(at[0], 0),
sortB: root.asNumber(at[1], 0)
});
}
}
found.sort((a, b) => a.sortA !== b.sortA ? a.sortA - b.sortA : a.sortB - b.sortB);
root.windows = found.map(w => ({
key: w.key,
title: w.title,
app: w.app,
focused: w.focused,
preview: root.kind === "niri" && root.niriScreenshots ? root.previewPath(w.key) : ""
}));
root.takeScreenshots();
}
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;
}
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("window-carousel: could not read compositor data:", e);
}
if (root.queryStage === "workspace") {
root.parseWorkspace(parsed);
if (root.workspaceId < 0) {
console.warn("window-carousel: no focused workspace reported");
root.windows = [];
root.finishQuery();
return;
}
root.startStage("windows");
return;
}
root.parseWindows(parsed);
root.finishQuery();
}
}
}
Process {
id: shotProc
running: false
onExited: {
root.previewVersion += 1;
root.nextScreenshot();
}
stderr: StdioCollector {
onStreamFinished: {
if (this.text.trim().length > 0)
console.warn("window-carousel:", this.text.trim());
}
}
}
Timer {
id: shotSettle
interval: 300
onTriggered: root.previewVersion += 1
}
Process {
id: action
running: false
stderr: StdioCollector {
onStreamFinished: {
if (this.text.trim().length > 0)
console.warn("window-carousel:", this.text.trim());
}
}
}
}