repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
quickshell/nuguland/Niri.qml
Rawimport QtQuick
import Quickshell
import Quickshell.Io
Item {
id: root
readonly property bool available: String(Quickshell.env("NIRI_SOCKET") || "").length > 0
property bool ready: false
property string lastError: ""
property var workspaces: []
readonly property var visibleWorkspaces: displayWorkspaces(workspaces)
property var windows: []
property var outputs: []
property var focusedWindow: null
property string overviewState: "unknown"
property string lastPickedColor: ""
property var lastWindowAction: ({
})
readonly property var focusedWindowRecord: windowById(focusedWindow)
readonly property string focusedTitle: focusedWindowRecord ? (focusedWindowRecord.title || "") : ""
readonly property string focusedAppId: focusedWindowRecord ? (focusedWindowRecord.app_id || focusedWindowRecord.appId || "") : ""
function refresh() {
if (!available || query.running)
return ;
query.exec(["niri", "msg", "--json", "event-stream"]);
}
function loadSnapshot() {
if (!available || snapshot.running)
return ;
snapshot.exec(["sh", "-c", "printf '{\"windows\":'; niri msg --json windows; printf ',\"workspaces\":'; niri msg --json workspaces; printf ',\"outputs\":'; niri msg --json outputs; printf ',\"focused\":'; niri msg --json focused-window || printf 'null'; printf ',\"overview\":'; niri msg --json overview-state || printf '{\"is_open\":false}'; printf '}\\n'"]);
}
function applySnapshot(text) {
let data;
try {
data = JSON.parse(String(text || "{}"));
} catch (error) {
lastError = String(error);
return ;
}
windows = data.windows || [];
workspaces = data.workspaces || [];
outputs = data.outputs || [];
focusedWindow = data.focused && data.focused.id !== undefined ? data.focused.id : null;
overviewState = data.overview && data.overview.is_open ? "open" : "closed";
ready = true;
}
function action(args) {
const list = Array.isArray(args) ? args : [String(args)];
actionProc.exec(["niri", "msg", "action"].concat(list.map(String)));
}
function screenshot(path) {
action(["screenshot", "--path", path]);
}
function screenshotScreen(path) {
action(["screenshot-screen", "--path", path, "--write-to-disk", "true"]);
}
function screenshotWindow(path) {
action(["screenshot-window", "--path", path, "--write-to-disk", "true"]);
}
function pickColor() {
lastPickedColor = "";
colorProc.exec(["niri", "msg", "pick-color"]);
}
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;
});
}
// 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(vis[i]);
}
return order.map((name) => {
return {
"output": name,
"workspaces": byOutput[name].slice().sort((a, b) => Number(a.idx || 0) - Number(b.idx || 0))
};
});
}
// outputs may arrive as a name-keyed object (niri snapshot) or an array
// (event stream); normalize to an array of records that each carry `name`.
function outputList() {
if (Array.isArray(outputs))
return outputs;
const obj = outputs || ({
});
return Object.keys(obj).map((key) => {
return Object.assign({
"name": key
}, obj[key]);
});
}
// 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));
}
// Local gate for the grouping logic (untestable on a single monitor): feed
// a synthetic two-output array and assert grouping, per-tray idx sort, and
// empty-trailing-workspace filtering. Drive via the niriSelfTest IPC.
function selfTest() {
const failures = [];
const sample = [{
"idx": 4,
"output": "DP-2",
"name": "browser"
}, {
"idx": 5,
"output": "DP-2",
"name": "vault"
}, {
"idx": 3,
"output": "DP-1",
"name": "games"
}, {
"idx": 6,
"output": "DP-1",
"name": null
}, {
"idx": 2,
"output": "DP-1",
"name": "media"
}, {
"idx": 1,
"output": "DP-1",
"name": "code",
"is_focused": true
}];
const groups = groupWorkspaces(sample);
if (groups.length !== 2)
failures.push(`expected 2 groups, got ${groups.length}`);
const dp1 = groups.filter((g) => g.output === "DP-1")[0] || null;
const dp2 = groups.filter((g) => g.output === "DP-2")[0] || null;
if (!dp1)
failures.push("missing DP-1 group");
if (!dp2)
failures.push("missing DP-2 group");
if (dp1) {
const idxs = JSON.stringify(dp1.workspaces.map((w) => w.idx));
if (idxs !== "[1,2,3]")
failures.push(`DP-1 idx order ${idxs} != [1,2,3]`);
}
if (dp2) {
const idxs = JSON.stringify(dp2.workspaces.map((w) => w.idx));
if (idxs !== "[4,5]")
failures.push(`DP-2 idx order ${idxs} != [4,5]`);
}
const total = groups.reduce((sum, g) => sum + g.workspaces.length, 0);
if (total !== 5)
failures.push(`expected 5 pills after empty filter, got ${total}`);
return {
"pass": failures.length === 0,
"failures": failures
};
}
function parsePickedColor(text) {
const value = String(text || "");
const match = value.match(/#[0-9a-fA-F]{6}/);
lastPickedColor = match ? match[0].toLowerCase() : "";
lastError = value.trim();
}
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 windowActions(id) {
return [{
"id": "focus",
"label": "focus",
"route": "Niri.qml",
"niriAction": "focus-window",
"destructive": false,
"keyboard": "Enter"
}, {
"id": "toggle-fullscreen",
"label": "fullscreen",
"route": "Niri.qml",
"niriAction": "toggle-fullscreen",
"destructive": false,
"keyboard": "F"
}, {
"id": "move-workspace",
"label": "move workspace",
"route": "Niri.qml",
"niriAction": "move-window-to-workspace",
"destructive": false,
"keyboard": "M"
}, {
"id": "close-window",
"label": "close",
"route": "Niri.qml",
"niriAction": "close-window",
"destructive": true,
"keyboard": "Delete"
}].map((action) => {
return Object.assign({
}, action, {
"windowId": id
});
});
}
function windowPanelContract() {
return {
"source": "Nuguland WindowInfo.qml Details.qml Buttons.qml plus Nuguland TaskViewContent.qml",
"ownedBy": "PopoutHost.qml inline WindowPanel",
"niriWindowCardPanel": true,
"previewSlotCard": true,
"detailsRows": true,
"ruleHintRows": true,
"windowActionRail": true,
"workspaceMoveAffordance": true,
"serviceActionsOnly": true,
"route": "Niri.qml",
"realNiriWindowState": true,
"cardParts": ["preview-slot", "details", "rule-hints", "actions", "workspace-move"],
"noCompositorOverviewClone": true
};
}
function windowCardObject() {
const win = focusedWindowRecord || ({
});
const appId = win.app_id || win.appId || "";
const title = win.title || "";
const workspace = win.workspace_id || win.workspaceId || null;
const id = win.id || focusedWindow || null;
const hints = [];
if (appId.length > 0)
hints.push(`match app-id=${JSON.stringify(appId)}`);
if (title.length > 0)
hints.push(`match title=${JSON.stringify(title)}`);
if (workspace !== null)
hints.push(`workspace id ${workspace}`);
const actions = windowActions(id);
return {
"id": id,
"appId": appId,
"title": title,
"workspace": workspace,
"focused": focusedWindowRecord !== null,
"ruleHints": hints,
"previewSlot": {
"source": "niri-toplevel",
"available": focusedWindowRecord !== null,
"live": focusedWindowRecord !== null,
"title": title,
"appId": appId,
"role": "content.normal"
},
"actionRow": {
"route": "Niri.qml",
"keyboardFirst": true,
"pointerParity": true,
"actions": actions
},
"windowPanelContract": windowPanelContract(),
"detailsRows": [{
"id": "app-id",
"label": "app-id",
"value": appId,
"role": "content.normal"
}, {
"id": "title",
"label": "title",
"value": title,
"role": "content.normal"
}, {
"id": "workspace",
"label": "workspace",
"value": workspace === null ? "unknown" : String(workspace),
"role": "ui.accent"
}, {
"id": "focused",
"label": "focused",
"value": focusedWindowRecord !== null ? "yes" : "no",
"role": focusedWindowRecord !== null ? "ui.accent" : "ui.minor"
}],
"actions": actions,
"lastWindowAction": lastWindowAction
};
}
function windowRuleMetadata() {
return JSON.stringify(windowCardObject());
}
function windowCardAction(kind) {
const name = String(kind);
const card = windowCardObject();
const actionRows = card.actions || [];
let selected = null;
for (let i = 0; i < actionRows.length; i++) if (actionRows[i].id === name) {
selected = actionRows[i];
}
lastWindowAction = {
"kind": name,
"route": "Niri.qml",
"accepted": selected !== null,
"niriAction": selected ? selected.niriAction : "",
"windowId": card.id,
"executed": false
};
return JSON.stringify(windowCardObject());
}
function stateJson() {
return JSON.stringify({
"available": available,
"ready": ready,
"workspaceCount": workspaces.length,
"windowCount": windows.length,
"windows": windows,
"outputCount": Array.isArray(outputs) ? outputs.length : Object.keys(outputs || {
}).length,
"outputs": outputs,
"workspaces": workspaces,
"overviewState": overviewState,
"focusedWindow": focusedWindow,
"focusedAppId": focusedAppId,
"focusedTitle": focusedTitle,
"lastError": lastError
});
}
function applyEvent(line) {
let event;
try {
event = JSON.parse(line);
} catch (e) {
return ;
}
ready = true;
if (event.WorkspacesChanged)
workspaces = event.WorkspacesChanged.workspaces || [];
if (event.WorkspaceActivated) {
const activatedId = event.WorkspaceActivated.id;
const focused = !!event.WorkspaceActivated.focused;
let activatedOutput = null;
for (let i = 0; i < workspaces.length; i++) if (workspaces[i].id === activatedId)
activatedOutput = workspaces[i].output;
workspaces = workspaces.map((ws) => {
const next = Object.assign({
}, ws);
if (ws.output === activatedOutput)
next.is_active = ws.id === activatedId;
if (focused)
next.is_focused = ws.id === activatedId;
return next;
});
}
if (event.WindowsChanged)
windows = event.WindowsChanged.windows || [];
if (event.OutputsChanged)
outputs = event.OutputsChanged.outputs || [];
if (event.WindowFocusChanged)
focusedWindow = event.WindowFocusChanged.id || null;
if (event.OverviewOpenedOrClosed)
overviewState = event.OverviewOpenedOrClosed.is_open ? "open" : "closed";
}
Component.onCompleted: {
loadSnapshot();
refresh();
}
Process {
id: snapshot
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: root.applySnapshot(this.text)
}
stderr: StdioCollector {
waitForEnd: true
onStreamFinished: {
if (this.text.trim().length > 0)
root.lastError = this.text.trim();
}
}
}
Process {
id: query
running: false
onExited: (code, status) => {
if (code !== 0 && root.available)
root.lastError = `event stream exited ${code}`;
}
stdout: SplitParser {
onRead: (data) => {
return root.applyEvent(data);
}
}
stderr: StdioCollector {
onStreamFinished: root.lastError = this.text
}
}
Process {
id: actionProc
stderr: StdioCollector {
onStreamFinished: root.lastError = this.text
}
}
Process {
id: colorProc
stdout: StdioCollector {
onStreamFinished: root.parsePickedColor(this.text)
}
stderr: StdioCollector {
onStreamFinished: root.lastError = this.text
}
}
}