repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nuguland/Power.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Services.UPower

Item {
    id: root

    property QtObject lockService
    property QtObject niriService
    property string selectedProfile: "balanced"
    property string pendingConfirmation: ""
    property var powerHistorySamples: []
    property var lastAction: ({
    })
    readonly property bool nativeActionRoute: true
    readonly property bool usesUPower: true
    readonly property bool powerProfilesAvailable: false
    readonly property var boundedActions: ["lock", "logout", "suspend", "reboot", "poweroff", "monitor-off", "monitor-on", "set-profile", "confirm", "cancel"]
    readonly property var destructiveActions: ["logout", "reboot", "poweroff"]

    function normalizeProfile(value) {
        const text = String(value).toLowerCase();
        if (text.indexOf("performance") >= 0)
            return "performance";

        if (text.indexOf("saver") >= 0)
            return "power-saver";

        return "balanced";
    }

    function currentProfile() {
        return selectedProfile;
    }

    function normalizePercent(value) {
        const n = Number(value || 0);
        if (n > 0 && n <= 1)
            return Math.round(n * 100);

        return Math.round(n);
    }

    function deviceState(device) {
        return String(UPowerDeviceState.toString(device.state || UPowerDeviceState.Unknown)).toLowerCase().replace(/\s+/g, "").replace("fullycharged", "full");
    }

    function minutesToLabel(seconds) {
        const value = Math.max(0, Math.round(Number(seconds || 0) / 60));
        if (value <= 0)
            return "unknown";

        const hours = Math.floor(value / 60);
        const minutes = value % 60;
        if (hours <= 0)
            return `${minutes}m`;

        if (minutes <= 0)
            return `${hours}h`;

        return `${hours}h ${minutes}m`;
    }

    function nativeBatteryObject() {
        const device = UPower.displayDevice;
        if (!device || !device.ready)
            return {
            "id": "display",
            "percent": 0,
            "state": "unknown",
            "timeEstimate": "unknown",
            "health": -1,
            "profile": currentProfile()
        };

        const state = deviceState(device);
        const timeEstimate = state === "charging" ? minutesToLabel(device.timeToFull) : minutesToLabel(device.timeToEmpty);
        return {
            "id": String(device.nativePath || "display"),
            "percent": normalizePercent(device.percentage),
            "state": state,
            "timeEstimate": timeEstimate,
            "health": device.healthSupported ? Math.round(Number(device.healthPercentage || 0)) : -1,
            "profile": currentProfile()
        };
    }

    function displayBattery() {
        return nativeBatteryObject();
    }

    function nativeExternalDevices() {
        const rows = [];
        const devices = UPower.devices.values || [];
        for (let i = 0; i < devices.length; i++) {
            const device = devices[i];
            if (!device || device.isLaptopBattery || !device.isPresent)
                continue;

            rows.push({
                "id": String(device.nativePath || device.model || `device-${i}`),
                "name": String(device.model || UPowerDeviceType.toString(device.type)),
                "type": String(UPowerDeviceType.toString(device.type)).toLowerCase(),
                "percent": normalizePercent(device.percentage),
                "state": deviceState(device)
            });
        }
        return rows;
    }

    function externalDevices() {
        return nativeExternalDevices();
    }

    function externalDevicesById() {
        const indexed = {
        };
        const devices = externalDevices();
        for (let i = 0; i < devices.length; i++) {
            const device = devices[i];
            indexed[device.id] = {
                "id": device.id,
                "name": device.name,
                "type": device.type,
                "percent": device.percent,
                "state": device.state
            };
        }
        return indexed;
    }

    function batteryRole(battery) {
        if (battery.percent <= 10)
            return "error";

        if (battery.percent <= 25)
            return "warning";

        return "ui.accent";
    }

    function batteryFraction() {
        return Math.max(0, Math.min(1, Number(displayBattery().percent || 0) / 100));
    }

    function appendPowerHistorySample() {
        const next = powerHistorySamples.slice(Math.max(0, powerHistorySamples.length - 3599));
        next.push([batteryFraction(), chargingValue(), profileValue(), healthFraction(), 0]);
        powerHistorySamples = next;
    }

    function chargingValue() {
        return displayBattery().state === "charging" ? 1 : 0;
    }

    function profileValue() {
        const profile = currentProfile();
        if (profile === "performance")
            return 1;

        if (profile === "power-saver")
            return 0;

        return 0.5;
    }

    function healthFraction() {
        const health = Number(displayBattery().health || 0);
        return health > 0 ? Math.max(0, Math.min(1, health / 100)) : 1;
    }

    function lowPowerMode() {
        const state = String(displayBattery().state || "").toLowerCase();
        return state.indexOf("discharging") >= 0 || state.indexOf("pendingdischarge") >= 0;
    }

    function batteryObject() {
        const battery = displayBattery();
        return {
            "id": battery.id,
            "percent": battery.percent,
            "state": battery.state,
            "timeEstimate": battery.timeEstimate,
            "health": battery.health,
            "profile": battery.profile,
            "role": batteryRole(battery)
        };
    }

    function powerPanelContract() {
        return {
            "source": "Nuguland session Content.qml plus Nuguland SessionScreen.qml plus Nuguland Power.qml",
            "ownedBy": "PopoutHost.qml inline PowerPanel",
            "upowerSessionPanel": true,
            "batteryHero": true,
            "externalDeviceBatteryRows": true,
            "powerProfileSelector": true,
            "keyboardActionGrid": true,
            "confirmationStrip": true,
            "destructiveTwoStep": true,
            "serviceActionsOnly": true,
            "safeDefault": "lock",
            "actions": ["lock", "suspend", "monitor-off", "monitor-on", "logout", "reboot", "poweroff"],
            "profileRows": ["power-saver", "balanced", "performance"]
        };
    }

    function stateObject() {
        const battery = batteryObject();
        const devices = externalDevices();
        return {
            "backend": "Power.qml",
            "usesUPower": usesUPower,
            "nativeActionRoute": nativeActionRoute,
            "helperProcesses": [],
            "serviceOwnedActions": true,
            "boundedActions": boundedActions,
            "powerPanelContract": powerPanelContract(),
            "profile": currentProfile(),
            "powerProfilesAvailable": powerProfilesAvailable,
            "lowPowerMode": lowPowerMode(),
            "lowPowerPolicy": {
                "trigger": "battery-discharge",
                "shaders": false,
                "animations": false
            },
            "battery": battery,
            "externalDevices": devices.map((device) => {
                return ({
                    "id": device.id,
                    "name": device.name,
                    "type": device.type,
                    "percent": device.percent,
                    "state": device.state
                });
            }),
            "externalDevicesById": externalDevicesById(),
            "session": {
                "safeDefault": "lock",
                "requiresConfirmation": destructiveActions,
                "keyboardFocus": true,
                "escapeCancels": true,
                "routes": {
                    "lock": "Lock.qml",
                    "monitor": "Niri.qml"
                }
            },
            "compact": {
                "label": "Power",
                "role": battery.role,
                "charging": battery.state === "charging"
            },
            "shader": {
                "kind": "power-gradient",
                "clipped": true,
                "source": "shaders/power-gradient.frag.qsb",
                "priorArt": "Made by Evan fwidth/smoothstep antialiased line ideas adapted to a foreground-only battery history sparkline",
                "values": [batteryFraction(), chargingValue(), profileValue(), healthFraction()],
                "colors": ["ui.accent", "ui.focus", "ui.minor", "ui.backdrop", "warning", "error"]
            },
            "pendingConfirmation": pendingConfirmation,
            "lastAction": lastAction
        };
    }

    function stateJson() {
        return JSON.stringify(stateObject());
    }

    function setProfile(name) {
        const selected = normalizeProfile(name);
        selectedProfile = selected;
        pendingConfirmation = "";
        lastAction = {
            "kind": "set-profile",
            "profile": selected,
            "nativeActionRoute": nativeActionRoute
        };
        return stateJson();
    }

    function requiresConfirmation(kind) {
        return destructiveActions.indexOf(kind) >= 0;
    }

    function executeSessionAction(actionName) {
        if (actionName === "lock" && lockService)
            lockService.request();
        else if (actionName === "monitor-off" && niriService)
            niriService.action(["power-off-monitors"]);
        else if (actionName === "monitor-on" && niriService)
            niriService.action(["power-on-monitors"]);
    }

    function sessionAction(kind) {
        const actionName = String(kind);
        if (requiresConfirmation(actionName)) {
            pendingConfirmation = actionName;
            lastAction = {
                "kind": actionName,
                "nativeActionRoute": nativeActionRoute,
                "confirmed": false
            };
        } else {
            pendingConfirmation = "";
            executeSessionAction(actionName);
            lastAction = {
                "kind": actionName,
                "nativeActionRoute": nativeActionRoute,
                "confirmed": true
            };
        }
        return stateJson();
    }

    function confirmAction(kind) {
        const actionName = String(kind);
        const confirmed = pendingConfirmation === actionName && requiresConfirmation(actionName);
        pendingConfirmation = "";
        if (confirmed)
            executeSessionAction(actionName);

        lastAction = {
            "kind": actionName,
            "nativeActionRoute": nativeActionRoute,
            "confirmed": confirmed
        };
        return stateJson();
    }

    function cancelAction() {
        pendingConfirmation = "";
        lastAction = {
            "kind": "cancel"
        };
        return stateJson();
    }

    Component.onCompleted: appendPowerHistorySample()

    Timer {
        interval: 2000
        repeat: true
        running: true
        onTriggered: root.appendPowerHistorySample()
    }

}