repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nugu/CpuWidget.qml

Raw
import QtQuick
import Quickshell.Io
import "."

StatusItem {
    id: root

    required property QtObject commands

    property int lastIdle: 0
    property int lastTotal: 0
    property int percent: 0

    text: `${percent}%`
    minWidth: 54

    // `/proc/stat` avoids spawning a full monitor until clicked and is cheap at a
    // 2s cadence, matching the current bar's small status role.
    onLeftClicked: commands.openSystemMonitor()
    onMiddleClicked: commands.openSystemMonitor()

    Timer {
        running: true
        repeat: true
        interval: 2000
        triggeredOnStart: true
        onTriggered: poll.exec(["sh", "-c", "awk '/^cpu /{print}' /proc/stat"])
    }

    Process {
        id: poll
        stdout: StdioCollector {
            onStreamFinished: {
                const parts = this.text.trim().split(/\s+/).slice(1).map(x => parseInt(x, 10))
                if (parts.length < 5) return
                const idle = parts[3] + parts[4]
                const total = parts.reduce((a, b) => a + b, 0)
                const deltaIdle = idle - root.lastIdle
                const deltaTotal = total - root.lastTotal
                if (root.lastTotal > 0 && deltaTotal > 0) {
                    root.percent = Math.max(0, Math.min(100, Math.round((1 - deltaIdle / deltaTotal) * 100)))
                }
                root.lastIdle = idle
                root.lastTotal = total
            }
        }
    }
}