Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/system/SystemPanel.qml

Raw
pragma ComponentBehavior: Bound
import QtQuick
import "../.."
import "../../Util.js" as Util
import "sysinfo.js" as Sys

Item {
    id: root

    required property Theme theme
    readonly property Flickable scrollView: contentScroll
    required property Resources resourceService
    implicitHeight: contentColumn.implicitHeight
    height: parent ? parent.height : implicitHeight
    // The card fits the content; the entry height caps it (FeatureEntry.qml).
    readonly property real naturalHeight: implicitHeight

    readonly property Resources rs: resourceService
    // Retained by the host across close, switch and reload (the entry's retainedState).
    property bool machineExpanded: false
    // The incident whose technical details are shown, also retained.
    property string expandedIncident: ""
    // Opening focuses the first control in reading order: the first current
    // problem's action, else the history retry or first incident action, else the
    // machine disclosure (FeatureEntry.qml).
    property Item attentionAction: null
    property Item historyAction: null
    readonly property bool historyUnreadable: rs.incidentStatus !== "ready" && rs.incidentStatus !== "not checked"
    readonly property Item initialFocus: root.conditions.length > 0 && attentionAction ? attentionAction : root.historyUnreadable ? retryButton : root.incidents.length > 0 && historyAction ? historyAction : machineToggle
    // One label and one value column for every metric row: the longest label, both rates.
    readonly property real metricLabelWidth: Math.ceil(longestMetricLabel.advanceWidth) + theme.spaceSm
    readonly property int metricValueWidth: 210
    TextMetrics {
        id: longestMetricLabel

        font.family: root.theme.fontSans
        font.pixelSize: root.theme.textMeta
        text: "temperature"
    }
    readonly property var identity: rs.identity
    // Repeaters keep their rows (and focus) while a new array has equal content;
    // active thermal, memory-pressure and load issues carry live measurements,
    // so every metric tick rebuilds the rows while one is shown.
    readonly property var conditions: rs.conditions
    readonly property var incidents: rs.incidentGroups

    // Relative incident times refresh with every issue update and at least every 30 s.
    onConditionsChanged: now = Date.now()
    onIncidentsChanged: now = Date.now()
    property real now: Date.now()
    Timer {
        interval: 30000
        running: true
        repeat: true
        onTriggered: root.now = Date.now()
    }

    // Intent to the host: close this popup once an agent request is dispatched.
    signal closeRequested(string reason)

    Connections {
        target: root.resourceService
        function onAgentDispatched(): void {
            root.closeRequested("agent-dispatched");
        }
    }

    // Net and disk have no natural ceiling: scale the combined rate against its recent peak.
    function peakFraction(up: var, down: var, current: real): real {
        let peak = 0;
        for (let i = 0; i < up.length; i++)
            peak = Math.max(peak, up[i] + down[i]);
        return peak > 0 ? Math.min(1, current / peak) : 0;
    }

    Flickable {
        id: contentScroll

        anchors.fill: parent
        contentHeight: contentColumn.implicitHeight
        clip: true
        boundsBehavior: Flickable.StopAtBounds

        Column {
            id: contentColumn

            width: contentScroll.width
            spacing: root.theme.spaceMd

            // Expanded details open below the fold: once laid out, bring them into view.
            property bool revealMachine: false
            onPositioningComplete: if (revealMachine) {
                revealMachine = false;
                Util.revealIn(machineCard, contentScroll);
            }

            // ---- leads: current problems by severity, or one all ok line ----
            NuguText {
                objectName: "allOk"
                visible: root.conditions.length === 0
                theme: root.theme
                width: parent.width
                variant: "title"
                text: "all ok"
            }

            Column {
                objectName: "currentIssues"
                visible: root.conditions.length > 0
                width: parent.width
                spacing: 8

                Row {
                    width: parent.width
                    spacing: 12
                    NuguText {
                        theme: root.theme
                        variant: "title"
                        text: "needs attention"
                    }
                    NuguText {
                        theme: root.theme
                        variant: "meta"
                        color: root.theme.ui.minor
                        text: root.conditions.length + (root.conditions.length === 1 ? " problem" : " problems")
                    }
                }
                Repeater {
                    model: root.conditions
                    delegate: SystemIssueRow {
                        id: issueRow
                        required property var modelData
                        required property int index
                        objectName: "issue " + modelData.id
                        theme: root.theme
                        width: contentColumn.width
                        issue: modelData
                        now: root.now
                        pending: root.rs.agentPending && root.rs.agentIssueId === modelData.id
                        launchBusy: root.rs.agentPending
                        launchError: root.rs.agentIssueId === modelData.id ? root.rs.agentError : ""
                        onFocusEntered: Qt.callLater(Util.revealIn, issueRow, contentScroll)
                        onOpenRequested: root.rs.runIssueAction(modelData.id)
                        onAgentRequested: root.rs.runIssueAgent(modelData.id)
                        expanded: root.expandedIncident === modelData.id
                        onDetailsToggled: root.expandedIncident = expanded ? "" : modelData.id

                        Binding {
                            when: issueRow.index === 0
                            target: root
                            property: "attentionAction"
                            value: issueRow.firstAction
                            restoreMode: Binding.RestoreNone
                        }
                    }
                }
            }

            // ===== LIVE STATS: one row per metric, then the top processes =====
            PopupCard {
                objectName: "liveMetrics"
                theme: root.theme
                width: parent.width

                Column {
                    width: parent.width
                    spacing: root.theme.spaceSm

                    NuguText {
                        theme: root.theme
                        variant: "title"
                        text: "live"
                    }

                    MetricRow {
                        theme: root.theme
                        label: "cpu"
                        labelWidth: root.metricLabelWidth
                        valueWidth: root.metricValueWidth
                        value: `${Math.round(root.rs.cpuUsage * 100)}%`
                        fraction: root.rs.cpuUsage
                        ring: root.rs.cpuRing
                        sparkScaleMax: 1
                    }

                    MetricRow {
                        theme: root.theme
                        label: "memory"
                        labelWidth: root.metricLabelWidth
                        valueWidth: root.metricValueWidth
                        value: `${Math.round(root.rs.memoryUsage * 100)}% · ${Sys.formatBytes(Math.max(0, root.rs.memTotal - root.rs.memAvailable))}`
                        fraction: root.rs.memoryUsage
                        // Memory pressure starts at 90% (sysinfo.js detectIssues).
                        barColor: root.rs.memoryUsage >= 0.9 ? root.theme.warning : root.theme.ui.minor
                        ring: root.rs.memRing
                        sparkScaleMax: 1
                    }

                    MetricRow {
                        theme: root.theme
                        label: "swap"
                        labelWidth: root.metricLabelWidth
                        valueWidth: root.metricValueWidth
                        value: root.rs.swapTotal > 0 ? `${Math.round(root.rs.swapUsage * 100)}% · ${Sys.formatBytes(Math.max(0, root.rs.swapTotal - root.rs.swapFree))}` : "off"
                        fraction: root.rs.swapUsage
                        showSpark: false
                    }

                    // Omitted without a temperature sensor or fan reading.
                    MetricRow {
                        readonly property bool hasTemp: root.rs.cpuTemperatureC !== null && root.rs.cpuTemperatureC !== undefined
                        readonly property bool hasFan: root.rs.fanRpm !== null && root.rs.fanRpm !== undefined

                        visible: hasTemp || hasFan
                        theme: root.theme
                        label: "temperature"
                        labelWidth: root.metricLabelWidth
                        valueWidth: root.metricValueWidth
                        value: [hasTemp ? `${Math.round(Number(root.rs.cpuTemperatureC))}°C` : "", hasFan ? `${Math.round(Number(root.rs.fanRpm))} rpm` : ""].filter(Boolean).join(" · ")
                        fraction: {
                            const t = root.rs.cpuTemperatureC;
                            if (t === null || t === undefined)
                                return 0;

                            return Math.max(0, Math.min(1, Number(t) / Math.max(1, root.rs.tempHighC)));
                        }
                        // The sensor's high threshold is where the thermal issue starts.
                        barColor: fraction >= 1 ? root.theme.warning : root.theme.ui.minor
                        showSpark: hasTemp
                        ring: root.rs.tempRing
                        sparkScaleMax: Math.max(1, root.rs.tempHighC)
                    }

                    // net and disk: the fill bar shows the combined rate; the split spark
                    // shows its directions, the first above the line, the second below.
                    MetricRow {
                        theme: root.theme
                        label: "network"
                        labelWidth: root.metricLabelWidth
                        valueWidth: root.metricValueWidth
                        value: `↓ ${Sys.formatRate(root.rs.networkRxRate)}  ↑ ${Sys.formatRate(root.rs.networkTxRate)}`
                        fraction: root.peakFraction(root.rs.netTxRing, root.rs.netRxRing, root.rs.networkRxRate + root.rs.networkTxRate)
                        splitSpark: true
                        ring: root.rs.netTxRing
                        ringDown: root.rs.netRxRing
                    }

                    MetricRow {
                        theme: root.theme
                        label: "disk"
                        labelWidth: root.metricLabelWidth
                        valueWidth: root.metricValueWidth
                        value: `read ${Sys.formatRate(root.rs.diskReadRate)}  write ${Sys.formatRate(root.rs.diskWriteRate)}`
                        fraction: root.peakFraction(root.rs.diskReadRing, root.rs.diskWriteRing, root.rs.diskReadRate + root.rs.diskWriteRate)
                        splitSpark: true
                        ring: root.rs.diskReadRing
                        ringDown: root.rs.diskWriteRing
                    }

                    // One figure: the last minute's load per core; the averages wait in the hint.
                    Row {
                        NuguText {
                            theme: root.theme
                            variant: "meta"
                            width: root.metricLabelWidth + root.theme.spaceXs
                            text: "load"
                        }

                        NuguText {
                            theme: root.theme
                            variant: "meta"
                            text: `${Math.round(root.rs.loadOne / Math.max(1, root.rs.cores) * 100)}% busy`
                        }

                        HoverHandler {
                            id: loadHover
                        }

                        PopupToolTip {
                            theme: root.theme
                            text: `averages over 1, 5 and 15 min: ${root.rs.loadOne.toFixed(2)} · ${root.rs.loadFive.toFixed(2)} · ${root.rs.loadFifteen.toFixed(2)} on ${root.rs.cores} cores`
                            wanted: loadHover.hovered
                        }
                    }

                    // ---- top CPU consumers (chips) ----
                    Flow {
                        visible: root.rs.processes.length > 0
                        width: parent.width
                        spacing: root.theme.spaceSm

                        Repeater {
                            model: root.rs.processes

                            delegate: PopupBadge {
                                required property var modelData

                                theme: root.theme
                                text: `${String(modelData.name || "?")} · ${Number(modelData.cpu || 0).toFixed(0)}%`
                                role: "normal"
                            }
                        }
                    }
                }
            }

            // ---- recorded crashes and oom stops: history, never a current failure ----
            Column {
                objectName: "incidentHistory"
                width: parent.width
                spacing: 8

                Row {
                    width: parent.width
                    spacing: 12
                    NuguText {
                        theme: root.theme
                        variant: "title"
                        text: "incident history"
                    }
                    // No count beside unreadable, empty history: zero would claim a check that failed.
                    NuguText {
                        visible: root.incidents.length > 0 || root.rs.incidentStatus === "ready"
                        theme: root.theme
                        variant: "meta"
                        color: root.theme.ui.minor
                        text: root.incidents.reduce((count, issue) => count + (issue.events ? issue.events.length : 1), 0) + " recorded"
                    }
                }
                // What history can cover, always in sight.
                NuguText {
                    theme: root.theme
                    width: parent.width
                    wrapMode: Text.Wrap
                    variant: "meta"
                    color: root.theme.ui.minor
                    text: "current boot · last 24 hours · latest 100"
                }
                NuguText {
                    visible: root.incidents.length === 0 && root.rs.incidentStatus === "ready" || root.rs.incidentStatus === "not checked"
                    theme: root.theme
                    width: parent.width
                    wrapMode: Text.Wrap
                    variant: "meta"
                    text: root.rs.incidentStatus === "ready" ? "no crashes or out-of-memory stops recorded" : "reading crash history"
                }
                // Unreadable history names the problem, the fix and a retry.
                Item {
                    visible: root.historyUnreadable
                    width: parent.width
                    height: visible ? Math.max(unreadableText.implicitHeight, retryButton.height) : 0

                    Column {
                        id: unreadableText

                        anchors.left: parent.left
                        anchors.right: retryButton.left
                        anchors.rightMargin: root.theme.spaceMd
                        anchors.verticalCenter: parent.verticalCenter
                        spacing: root.theme.spaceXs

                        NuguText {
                            theme: root.theme
                            width: parent.width
                            wrapMode: Text.Wrap
                            variant: "meta"
                            text: root.incidents.length > 0 ? "showing last readable history · journal unreadable" : "crash history unavailable · journal unreadable"
                        }
                        NuguText {
                            theme: root.theme
                            width: parent.width
                            wrapMode: Text.Wrap
                            variant: "meta"
                            color: root.theme.ui.minor
                            text: "join the systemd-journal group and sign in again, then retry"
                        }
                    }
                    PopupButton {
                        id: retryButton

                        anchors.right: parent.right
                        anchors.verticalCenter: parent.verticalCenter
                        theme: root.theme
                        icon: "\uF01E"
                        text: "retry"
                        accessibleName: "retry crash history"
                        tooltip: "read the journal again"
                        onActiveFocusChanged: if (activeFocus)
                            Qt.callLater(Util.revealIn, retryButton, contentScroll)
                        onClicked: root.rs.retryIncidents()
                    }
                }
                Repeater {
                    model: root.incidents
                    delegate: SystemIssueRow {
                        id: incidentRow
                        required property var modelData
                        required property int index
                        objectName: "issue " + modelData.id
                        theme: root.theme
                        width: contentColumn.width
                        issue: modelData
                        now: root.now
                        pending: root.rs.agentPending && root.rs.agentIssueId === modelData.id
                        launchBusy: root.rs.agentPending
                        launchError: root.rs.agentIssueId === modelData.id ? root.rs.agentError : ""
                        onFocusEntered: Qt.callLater(Util.revealIn, incidentRow, contentScroll)
                        onOpenRequested: root.rs.runIssueAction(modelData.id)
                        onAgentRequested: root.rs.runIssueAgent(modelData.id)
                        expanded: root.expandedIncident === modelData.id
                        onDetailsToggled: root.expandedIncident = expanded ? "" : modelData.id

                        Binding {
                            when: incidentRow.index === 0
                            target: root
                            property: "historyAction"
                            value: incidentRow.firstAction
                            restoreMode: Binding.RestoreNone
                        }
                    }
                }
            }

            // ---- machine identity: secondary detail last, behind a disclosure
            // kept as the user left it across close, switch and reopen ----
            PopupButton {
                id: machineToggle

                objectName: "machineToggle"
                theme: root.theme
                width: parent.width
                height: 34
                text: "machine"
                icon: root.machineExpanded ? "\uF106" : "\uF107"
                accessibleName: (root.machineExpanded ? "collapse " : "expand ") + text
                tooltip: accessibleName
                disclosure: true
                // Focus here, by Tab or on an all-clear opening, scrolls it into view.
                onControlFocusedChanged: if (controlFocused)
                    Qt.callLater(Util.revealIn, machineToggle, contentScroll)
                onClicked: {
                    root.machineExpanded = !root.machineExpanded;
                    contentColumn.revealMachine = root.machineExpanded;
                }
            }

            PopupCard {
                id: machineCard

                objectName: "machineDetails"
                visible: root.machineExpanded
                theme: root.theme
                width: parent.width
                height: visible ? implicitHeight : 0

                Grid {
                    id: identityGrid

                    readonly property real cellWidth: (width - columnSpacing) / 2

                    width: parent.width
                    columns: 2
                    columnSpacing: root.theme.spaceLg
                    rowSpacing: root.theme.spaceSm

                    // Unknown facts are omitted, never shown as a placeholder.
                    Repeater {
                        model: [["", root.identity.host], ["", root.identity.model], ["", root.identity.distro], ["", root.identity.kernel], ["", root.identity.wm], ["", root.identity.packages ? `${root.identity.packages} packages` : ""], ["", root.identity.shell], ["", root.identity.uptime]].filter(row => !!row[1])

                        delegate: IdentityRow {
                            required property var modelData

                            theme: root.theme
                            width: identityGrid.cellWidth
                            glyph: modelData[0]
                            value: String(modelData[1])
                        }
                    }

                    IdentityRow {
                        theme: root.theme
                        width: identityGrid.cellWidth
                        glyph: "\uF240"
                        // battery row hidden entirely when there is no laptop battery
                        visible: root.rs.isLaptopBattery
                        value: {
                            const p = root.rs.batteryPercent;
                            const st = root.rs.batteryStatus;
                            const h = root.rs.healthPercentage;
                            let s = (p === null || p === undefined) ? "battery" : `battery ${p}%`;
                            if (st)
                                s += ` · ${st}`;
                            if (h !== null && h !== undefined)
                                s += ` · health ${Math.round(Number(h))}%`;
                            return s;
                        }
                    }
                }
            }
        }
    }
}