repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
quickshell/nuguland/Resources.qml
Rawimport QtQuick
import Quickshell.Io
Item {
id: root
property real cpuUsage: 0
property real previousIdle: 0
property real previousTotal: 0
readonly property int sampleIntervalMs: 2000
readonly property int historyWindowSeconds: 7200
readonly property int historySampleLimit: 3600
property var cpuHistory: [0.12, 0.24, 0.38, 0.72]
property var systemHistorySamples: []
property var networkHistorySamples: []
property real memoryUsage: 0
property real swapUsage: 0
property real memTotal: 0
property real memAvailable: 0
property real swapTotal: 0
property real swapFree: 0
property real networkRxRate: 0
property real networkTxRate: 0
property real diskReadRate: 0
property real diskWriteRate: 0
property real previousNetworkRx: 0
property real previousNetworkTx: 0
property real previousDiskRead: 0
property real previousDiskWrite: 0
property real previousRateTime: 0
property string tempLabel: "n/a"
property real cpuTemperatureC: 0
property var temperatureHistorySamples: []
readonly property int hotHoldSeconds: 10
readonly property int coolHoldSeconds: 10
readonly property real cpuTempSensorHighC: 87
property int firestormHotSeconds: 0
property int firestormCoolSeconds: 0
property real firestormTarget: 0
property var processes: []
property var lastBtmAction: ({
})
function clamp01(value) {
return Math.max(0, Math.min(1, Number(value)));
}
function signalFor(value) {
if (value >= 0.9)
return "error";
if (value >= 0.7)
return "warning";
return "normal";
}
function colorRoleFor(value) {
const signal = signalFor(value);
if (signal === "error")
return "error";
if (signal === "warning")
return "warning";
return "ui.accent";
}
function formatBytes(value) {
const bytes = Math.max(0, Number(value));
if (bytes >= 1.07374e+09)
return `${(bytes / 1073741824).toFixed(1)} GiB`;
if (bytes >= 1.04858e+06)
return `${(bytes / 1048576).toFixed(1)} MiB`;
if (bytes >= 1024)
return `${(bytes / 1024).toFixed(1)} KiB`;
return `${Math.round(bytes)} B`;
}
function formatRate(value) {
return `${formatBytes(value)}/s`;
}
function networkRxLevel() {
return clamp01(networkRxRate / 262144);
}
function networkTxLevel() {
return clamp01(networkTxRate / 262144);
}
function diskLevel() {
return clamp01((diskReadRate + diskWriteRate) / 8.38861e+06);
}
function temperatureLevel() {
return clamp01(cpuTemperatureC / Math.max(temperatureHighThresholdC(), 1));
}
function systemLoad() {
return Math.max(cpuUsage, memoryUsage, swapUsage);
}
function systemSignal(value) {
return signalFor(value);
}
function systemColorRole(value) {
return colorRoleFor(value);
}
function appendHistorySample(history, sample) {
const next = history.slice(Math.max(0, history.length - historySampleLimit + 1));
next.push(sample.map((value) => {
return clamp01(value);
}));
return next;
}
function appendNumericHistorySample(history, value) {
const next = history.slice(Math.max(0, history.length - historySampleLimit + 1));
const numeric = Number(value);
if (Number.isFinite(numeric) && numeric > 0)
next.push(numeric);
return next;
}
function percentile(values, ratio) {
const sorted = (values || []).filter((value) => {
return Number.isFinite(Number(value)) && Number(value) > 0;
}).map(Number).sort((a, b) => {
return a - b;
});
if (sorted.length === 0)
return 61;
const index = Math.max(0, Math.min(sorted.length - 1, Math.ceil((sorted.length - 1) * ratio)));
return sorted[index];
}
function temperatureHighThresholdC() {
return Math.max(72, Math.min(87, percentile(temperatureHistorySamples, 0.95) + 8));
}
function temperatureCoolThresholdC() {
return temperatureHighThresholdC() - 5;
}
function updateFirestormState() {
const temp = Number(cpuTemperatureC);
if (!Number.isFinite(temp) || temp <= 0)
return ;
const high = temperatureHighThresholdC();
const cool = temperatureCoolThresholdC();
if (temp >= high) {
firestormHotSeconds = Math.min(hotHoldSeconds, firestormHotSeconds + sampleIntervalMs / 1000);
firestormCoolSeconds = 0;
} else if (temp <= cool) {
firestormCoolSeconds = Math.min(coolHoldSeconds, firestormCoolSeconds + sampleIntervalMs / 1000);
firestormHotSeconds = 0;
}
if (firestormHotSeconds >= hotHoldSeconds)
firestormTarget = 1;
if (firestormCoolSeconds >= coolHoldSeconds)
firestormTarget = 0;
}
function systemHistorySample() {
return [cpuUsage, memoryUsage, swapUsage, diskLevel(), temperatureLevel()];
}
function networkHistorySample() {
return [networkRxLevel(), networkTxLevel(), 0, 0];
}
function refreshHistories() {
systemHistorySamples = appendHistorySample(systemHistorySamples, systemHistorySample());
networkHistorySamples = appendHistorySample(networkHistorySamples, networkHistorySample());
}
function shaderHistoryObject(samples) {
return {
"windowSeconds": historyWindowSeconds,
"sampleIntervalMs": sampleIntervalMs,
"sampleLimit": historySampleLimit,
"sampleCount": samples.length
};
}
function systemWidgetState() {
const load = systemLoad();
return JSON.stringify({
"kind": "system",
"title": "system",
"load": load,
"percent": Math.round(load * 100),
"signal": systemSignal(load),
"colorRole": systemColorRole(load),
"barLabel": "system",
"shader": {
"kind": "system-mini-graph",
"clipped": true,
"source": "shaders/system-mini-graph.frag.qsb",
"priorArt": "Shadertoy smoothstep and distance-to-segment line drawing primitives plus heat haze sine/noise thermal shimmer",
"values": [cpuUsage, memoryUsage, swapUsage, diskLevel()],
"history": shaderHistoryObject(systemHistorySamples),
"colors": ["ui.accent", "ui.focus", "warning", "ui.minor", "error"]
},
"cpu": {
"usage": cpuUsage,
"percent": Math.round(cpuUsage * 100)
},
"memory": {
"usage": memoryUsage,
"percent": Math.round(memoryUsage * 100),
"used": Math.max(0, memTotal - memAvailable),
"total": memTotal,
"label": `${formatBytes(Math.max(0, memTotal - memAvailable))} / ${formatBytes(memTotal)}`
},
"swap": {
"usage": swapUsage,
"percent": Math.round(swapUsage * 100),
"used": Math.max(0, swapTotal - swapFree),
"total": swapTotal,
"label": swapTotal > 0 ? `${formatBytes(Math.max(0, swapTotal - swapFree))} / ${formatBytes(swapTotal)}` : "off"
},
"network": {
"rxRate": networkRxRate,
"txRate": networkTxRate,
"label": `↓ ${formatRate(networkRxRate)} ↑ ${formatRate(networkTxRate)}`
},
"disk": {
"readRate": diskReadRate,
"writeRate": diskWriteRate,
"level": diskLevel(),
"label": `R ${formatRate(diskReadRate)} W ${formatRate(diskWriteRate)}`
},
"temperature": {
"label": tempLabel,
"celsius": cpuTemperatureC,
"level": temperatureLevel(),
"highThresholdC": temperatureHighThresholdC(),
"coolThresholdC": temperatureCoolThresholdC(),
"firestormTarget": firestormTarget
},
"processes": processes,
"btmAction": lastBtmAction
});
}
function resourceHeroCard(kind, value, samples) {
const name = String(kind || "system");
const clamped = clamp01(value);
const boundedSamples = (samples || []).map((sample) => {
return clamp01(sample);
}).slice(-24);
return JSON.stringify({
"kind": name,
"title": name === "system" ? "System" : name.toUpperCase(),
"value": clamped,
"percent": Math.round(clamped * 100),
"signal": signalFor(clamped),
"role": colorRoleFor(clamped),
"boundedHeroMeter": {
"value": clamped,
"min": 0,
"max": 1,
"shape": clamped >= 0.8 ? "burst" : (clamped >= 0.4 ? "sunny" : "plain"),
"role": colorRoleFor(clamped)
},
"sparkline": {
"fillOpacity": 0.22,
"sampleCount": boundedSamples.length,
"alignment": "right"
},
"sparklineSamples": boundedSamples,
"helperProcesses": [],
"widgetProcesses": "forbidden"
});
}
function refreshCpu() {
statFile.reload();
const line = statFile.text().split("\n")[0] || "";
const parts = line.trim().split(/\s+/).slice(1).map(Number);
if (parts.length < 4 || parts.some((n) => {
return !Number.isFinite(n);
}))
return ;
const idle = parts[3] + (parts[4] || 0);
const total = parts.reduce((sum, n) => {
return sum + n;
}, 0);
const totalDelta = total - previousTotal;
const idleDelta = idle - previousIdle;
previousTotal = total;
previousIdle = idle;
if (totalDelta > 0) {
cpuUsage = clamp01(1 - idleDelta / totalDelta);
const nextHistory = cpuHistory.slice(-23);
nextHistory.push(cpuUsage);
cpuHistory = nextHistory;
}
}
function refreshMemory() {
meminfoFile.reload();
const values = ({
});
const lines = meminfoFile.text().split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^([A-Za-z_()]+):\s+(\d+)/);
if (match)
values[match[1]] = Number(match[2]) * 1024;
}
memTotal = Number(values.MemTotal || 0);
memAvailable = Number(values.MemAvailable || values.MemFree || 0);
swapTotal = Number(values.SwapTotal || 0);
swapFree = Number(values.SwapFree || 0);
memoryUsage = memTotal > 0 ? clamp01((memTotal - memAvailable) / memTotal) : 0;
swapUsage = swapTotal > 0 ? clamp01((swapTotal - swapFree) / swapTotal) : 0;
}
function applyProcessSnapshot(text) {
const rows = [];
const lines = String(text || "").trim().split("\n");
for (let i = 0; i < lines.length; i++) {
const parts = lines[i].trim().split(/\s+/);
if (parts.length < 4)
continue;
rows.push({
"pid": Number(parts[0]),
"name": parts[1],
"cpu": Number(parts[2]) || 0,
"mem": Number(parts[3]) || 0
});
}
processes = rows;
}
function applyTemperature(text) {
tempLabel = String(text || "n/a").trim() || "n/a";
const match = tempLabel.match(/([0-9]+(?:\.[0-9]+)?)/);
cpuTemperatureC = match ? Number(match[1]) : 0;
temperatureHistorySamples = appendNumericHistorySample(temperatureHistorySamples, cpuTemperatureC);
updateFirestormState();
}
function firestormState() {
return JSON.stringify({
"temperatureC": cpuTemperatureC,
"label": tempLabel,
"historySamples": temperatureHistorySamples.length,
"historyP95C": percentile(temperatureHistorySamples, 0.95),
"highThresholdC": temperatureHighThresholdC(),
"coolThresholdC": temperatureCoolThresholdC(),
"hotHoldSeconds": hotHoldSeconds,
"coolHoldSeconds": coolHoldSeconds,
"hotSeconds": firestormHotSeconds,
"coolSeconds": firestormCoolSeconds,
"firestormTarget": firestormTarget,
"sensorFacts": {
"currentObservedC": 61,
"coretempHighC": cpuTempSensorHighC,
"coretempCritC": 105
}
});
}
function refreshDetails() {
if (!processScan.running)
processScan.exec(["sh", "-c", "ps -eo pid=,comm=,pcpu=,pmem= --sort=-pcpu | head -n 5"]);
if (!tempScan.running)
tempScan.exec(["sh", "-c", "for f in /sys/class/thermal/thermal_zone*/temp /sys/class/hwmon/hwmon*/temp*_input; do [ -r \"$f\" ] || continue; v=$(cat \"$f\"); case \"$v\" in ''|*[!0-9]*) continue;; esac; awk -v v=\"$v\" 'BEGIN{printf \"%.0f°C\\n\", v/1000}'; exit; done; printf 'n/a\\n'"]);
}
function launchBtm() {
lastBtmAction = {
"kind": "btm",
"terminal": "wezterm",
"argv": ["wezterm", "start", "--", "btm"]
};
btmLaunch.exec(["wezterm", "start", "--", "btm"]);
return JSON.stringify(lastBtmAction);
}
function refreshRates() {
netFile.reload();
diskFile.reload();
let rx = 0;
let tx = 0;
const netLines = netFile.text().split("\n");
for (let i = 0; i < netLines.length; i++) {
const line = netLines[i];
if (line.indexOf(":") < 0)
continue;
const pieces = line.split(":");
const name = pieces[0].trim();
if (name === "lo")
continue;
const fields = pieces[1].trim().split(/\s+/).map(Number);
if (fields.length >= 16) {
rx += fields[0];
tx += fields[8];
}
}
let readBytes = 0;
let writeBytes = 0;
const diskLines = diskFile.text().split("\n");
for (let j = 0; j < diskLines.length; j++) {
const fields = diskLines[j].trim().split(/\s+/);
if (fields.length < 10)
continue;
const name = fields[2] || "";
if (name.indexOf("loop") === 0 || name.indexOf("ram") === 0)
continue;
const readSectors = Number(fields[5]);
const writeSectors = Number(fields[9]);
if (Number.isFinite(readSectors))
readBytes += readSectors * 512;
if (Number.isFinite(writeSectors))
writeBytes += writeSectors * 512;
}
const now = Date.now();
const seconds = previousRateTime > 0 ? Math.max(0.2, (now - previousRateTime) / 1000) : 0;
if (seconds > 0) {
networkRxRate = Math.max(0, (rx - previousNetworkRx) / seconds);
networkTxRate = Math.max(0, (tx - previousNetworkTx) / seconds);
diskReadRate = Math.max(0, (readBytes - previousDiskRead) / seconds);
diskWriteRate = Math.max(0, (writeBytes - previousDiskWrite) / seconds);
}
previousNetworkRx = rx;
previousNetworkTx = tx;
previousDiskRead = readBytes;
previousDiskWrite = writeBytes;
previousRateTime = now;
}
function refreshSystem() {
refreshCpu();
refreshMemory();
refreshRates();
refreshHistories();
refreshDetails();
}
FileView {
id: statFile
path: "/proc/stat"
blockLoading: true
printErrors: false
}
FileView {
id: meminfoFile
path: "/proc/meminfo"
blockLoading: true
printErrors: false
}
FileView {
id: netFile
path: "/proc/net/dev"
blockLoading: true
printErrors: false
}
FileView {
id: diskFile
path: "/proc/diskstats"
blockLoading: true
printErrors: false
}
Process {
id: processScan
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: root.applyProcessSnapshot(this.text)
}
}
Process {
id: tempScan
running: false
stdout: StdioCollector {
waitForEnd: true
onStreamFinished: root.applyTemperature(this.text)
}
}
Process {
id: btmLaunch
running: false
}
Timer {
interval: 2000
repeat: true
running: true
triggeredOnStart: true
onTriggered: root.refreshSystem()
}
}