Files
2026-10-16 14:28:25 -04:00

108 lines
3.2 KiB
QML

import QtQuick
import Quickshell
import Quickshell.Io
// Workspace colors and badge opacity, saved to a JSON file so they last
// across restarts.
// Workspaces with a name are stored by name. Ones without are stored by id,
// which niri does not keep across restarts.
Item {
id: root
// Color and opacity of a workspace that has none saved.
required property color fallback
required property real fallbackOpacity
readonly property string stateDir: {
const dir = Quickshell.env("XDG_STATE_HOME");
return (dir ? dir : Quickshell.env("HOME") + "/.local/state") + "/skygqts";
}
// Key -> { color: "#rrggbb", opacity: 0.8 }. Older files hold just the
// color string. Read from JSON, so this stays an untyped object.
property var colors: ({})
function keyFor(id: int, name: string): string {
return name.length > 0 ? "name:" + name : "id:" + id;
}
// The saved entry for a key, as an object. A JSON value, so untyped.
function entry(key: string): var {
const value = root.colors[key];
if (typeof value === "string")
return {
color: value
};
if (value && typeof value === "object")
return value;
return {};
}
function colorFor(key: string): color {
const value = root.entry(key).color;
return typeof value === "string" && value.length > 0 ? value : root.fallback;
}
function opacityFor(key: string): real {
const value = root.entry(key).opacity;
return typeof value === "number" && value >= 0 && value <= 1 ? value : root.fallbackOpacity;
}
// Change part of an entry and keep the rest.
function update(key: string, change): void {
const next = Object.assign({}, root.colors);
next[key] = Object.assign({}, root.entry(key), change);
root.colors = next;
root.save();
}
function setColor(key: string, value: color): void {
root.update(key, {
color: value.toString()
});
}
function setOpacity(key: string, value: real): void {
root.update(key, {
opacity: value
});
}
// Carry the color and opacity over when a workspace is renamed.
function move(from: string, to: string): void {
if (from === to || !(from in root.colors))
return;
const next = Object.assign({}, root.colors);
next[to] = next[from];
delete next[from];
root.colors = next;
root.save();
}
function save(): void {
file.setText(JSON.stringify(root.colors, null, 2) + "\n");
}
// Make sure the folder exists before the first save.
Process {
running: true
command: ["mkdir", "-p", root.stateDir]
}
FileView {
id: file
path: root.stateDir + "/workspace-colors.json"
// A missing file just means no colors yet.
printErrors: false
onLoaded: {
try {
const parsed = JSON.parse(file.text());
root.colors = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
} catch (e) {
console.warn("workspace-badge: could not read saved colors:", e);
}
}
}
}