import QtQuick import Quickshell import Quickshell.Io import "niri.js" as NiriState Item { id: root readonly property bool available: String(Quickshell.env("NIRI_SOCKET") || "").length > 0 // Output poll cadence; isolated fixtures shorten it, production keeps 5 s. property int outputPollMs: 5000 property bool ready: false property bool windowsInitialized: false property bool workspacesInitialized: false property bool streamFailed: false property int retryDelay: 250 property string lastError: "" property string outputError: "" property bool outputsPending: false property bool outputsFinished: false property var workspaces: [] readonly property var visibleWorkspaces: displayWorkspaces(workspaces) property var windows: [] property var outputs: ({}) property var focusedWindow: null property string overviewState: "unknown" property var actionQueue: [] readonly property var focusedWindowRecord: windowById(focusedWindow) readonly property string focusedTitle: focusedWindowRecord ? (focusedWindowRecord.title || "") : "" readonly property string focusedAppId: focusedWindowRecord ? (focusedWindowRecord.app_id || focusedWindowRecord.appId || "") : "" readonly property string focusedOutputName: focusedOutputNameFromWorkspaces(workspaces) readonly property string keybindConfigPath: { const xdg = String(Quickshell.env("XDG_CONFIG_HOME") || ""); const home = String(Quickshell.env("HOME") || ""); return (xdg.length > 0 ? xdg : home + "/.config") + "/niri/cfg/keybinds.kdl"; } property var workspaceShortcuts: ({}) function refresh() { if (!available || query.running) return; reconnect.stop(); resetStream(); streamFailed = false; lastError = ""; query.exec(["niri", "msg", "--json", "event-stream"]); } function resetStream() { ready = false; windowsInitialized = false; workspacesInitialized = false; windows = []; workspaces = []; focusedWindow = null; overviewState = "unknown"; } function streamDisconnected() { resetStream(); if (lastError.length === 0) lastError = "event stream disconnected"; if (!available || reconnect.running) return; reconnect.interval = retryDelay; retryDelay = Math.min(retryDelay * 2, 8000); reconnect.start(); } function failStream(message) { lastError = message; ready = false; streamFailed = true; query.signal(9); } function refreshOutputs() { if (!available) return; if (outputQuery.running) { outputsPending = true; return; } outputsPending = false; outputsFinished = false; outputQuery.exec(["niri", "msg", "--json", "outputs"]); } function applyOutputs(text, code, status) { try { const inventory = NiriState.parseOutputs(text, code, status); if (JSON.stringify(outputs) !== JSON.stringify(inventory)) outputs = inventory; outputError = ""; } catch (error) { outputError = String(error); } } function action(args) { const list = Array.isArray(args) ? args : [String(args)]; actionQueue = actionQueue.concat([["niri", "msg", "action"].concat(list.map(String))]); dispatchNextAction(); } function dispatchNextAction() { if (actionProc.running || actionQueue.length === 0) return; const command = actionQueue[0]; actionQueue = actionQueue.slice(1); // Process.exec terminates an already-running command; preserve rapid requests. actionProc.exec(command); } function focusWorkspace(ref) { action(["focus-workspace", String(ref)]); } function displayWorkspaces(items) { return (items || []).filter(workspace => { return workspace.name || workspace.is_focused || workspace.is_active || workspace.is_urgent || workspace.active_window_id !== null && workspace.active_window_id !== undefined; }); } function focusedOutputNameFromWorkspaces(items) { const list = items || []; for (let i = 0; i < list.length; i++) if (list[i].is_focused) return String(list[i].output || ""); return ""; } function shortcutKey(sequence) { const parts = String(sequence || "").split("+"); return parts.length > 0 ? parts[parts.length - 1] : ""; } function parseWorkspaceShortcuts(text) { const map = ({}); const re = /(?:^|\n)\s*([^\s{]+)[^{]*\{([^{}]*)\}/g; let match; while ((match = re.exec(String(text || ""))) !== null) { const focus = /\bfocus-workspace\s+(?:"([^"]+)"|([^\s}]+))/.exec(match[2]); if (!focus) continue; const name = String(focus[1] || focus[2] || ""); if (name.length > 0 && !map[name]) map[name] = shortcutKey(match[1]); } return map; } function reloadWorkspaceShortcuts() { workspaceShortcuts = parseWorkspaceShortcuts(keybindFile.text()); } function workspaceShortcut(name) { return workspaceShortcuts[String(name || "")] || ""; } // Group visible workspaces by output, each output's list idx-sorted, so the // single primary bar renders every monitor's workspaces in its own tray. // Pure: pass `items` for testing; defaults to the live workspace array. function groupWorkspaces(items) { const vis = displayWorkspaces(items === undefined ? workspaces : items); const byOutput = ({}); const order = []; for (let i = 0; i < vis.length; i++) { const name = String(vis[i].output || ""); if (!byOutput[name]) { byOutput[name] = []; order.push(name); } byOutput[name].push(Object.assign({}, vis[i], { "shortcut": workspaceShortcut(vis[i].name) })); } return order.map(name => { return { "output": name, "workspaces": byOutput[name].slice().sort((a, b) => Number(a.idx || 0) - Number(b.idx || 0)) }; }); } // Installed niri's outputs request returns a name-keyed object. function outputList() { return Object.keys(outputs).map(name => outputs[name]); } // physical left-to-right order key for an output, from niri's logical x; // large fallback so unknown outputs sort last (stable, not hash order). function outputX(name) { const list = outputList(); const want = String(name || ""); for (let i = 0; i < list.length; i++) { if (String(list[i].name || "") === want) { const logical = list[i].logical || ({}); return typeof logical.x === "number" ? logical.x : 1000000; } } return 1000000; } // live grouping for the bar, groups ordered by physical output position. function workspaceGroups() { return groupWorkspaces(workspaces).slice().sort((a, b) => outputX(a.output) - outputX(b.output)); } function windowById(id) { if (id === null || id === undefined) return null; for (let i = 0; i < windows.length; i++) { if (windows[i].id === id) return windows[i]; } return null; } function stateJson() { return JSON.stringify({ "available": available, "ready": ready, "workspaceCount": workspaces.length, "windowCount": windows.length, "windows": windows, "outputCount": Object.keys(outputs).length, "outputError": outputError, "outputs": outputs, "workspaces": workspaces, "workspaceShortcuts": workspaceShortcuts, "overviewState": overviewState, "focusedWindow": focusedWindow, "focusedOutputName": focusedOutputName, "focusedAppId": focusedAppId, "focusedTitle": focusedTitle, "lastError": lastError }); } function applyEvent(line) { if (streamFailed || String(line).trim().length === 0) return; try { const patch = NiriState.reduce(root, JSON.parse(line)); if (patch === null) return; for (const key of Object.keys(patch)) root[key] = patch[key]; ready = windowsInitialized && workspacesInitialized && overviewState !== "unknown"; if (ready) retryDelay = 250; } catch (error) { failStream(String(error)); } } onReadyChanged: if (ready) refreshOutputs() Component.onCompleted: { refreshOutputs(); refresh(); } Connections { target: Quickshell function onScreensChanged() { Qt.callLater(root.refreshOutputs); } } // Niri has no OutputsChanged event. Qt screen notifications cover hotplug; // polling also catches compositor-only geometry changes. One query at a time. Timer { interval: root.outputPollMs running: root.available repeat: true onTriggered: root.refreshOutputs() } Timer { id: reconnect onTriggered: root.refresh() } Timer { interval: 5000 running: query.running && !root.ready && !root.streamFailed onTriggered: root.failStream("event stream initialization timed out") } Timer { interval: 3000 running: outputQuery.running onTriggered: outputQuery.signal(9) } FileView { id: keybindFile path: root.keybindConfigPath preload: true printErrors: false onLoaded: root.reloadWorkspaceShortcuts() onLoadFailed: root.workspaceShortcuts = ({}) } Process { id: outputQuery onRunningChanged: { if (!running) { if (!root.outputsFinished) root.outputError = "outputs query failed to start"; if (root.outputsPending) Qt.callLater(root.refreshOutputs); } } stdout: StdioCollector { id: outputStdout waitForEnd: true } } Process { id: query running: false onRunningChanged: if (!running) root.streamDisconnected() stdout: SplitParser { onRead: data => { return root.applyEvent(data); } } stderr: StdioCollector { onStreamFinished: { if (this.text.trim().length > 0 && !root.streamFailed) root.lastError = this.text.trim(); } } } Connections { target: outputQuery function onExited(code, status) { root.outputsFinished = true; root.applyOutputs(outputStdout.text, code, status); } } Connections { target: query function onExited(code) { if (!root.streamFailed) root.lastError = `event stream exited ${code}`; } } Process { id: actionProc onRunningChanged: if (!running) root.dispatchNextAction() stderr: StdioCollector { onStreamFinished: root.lastError = this.text } } }