Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/AmbientLight.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Io

// One-shot only. Helper restores temporary activation before publishing a sample.
Item {
    id: root

    component Settings: QtObject {
        property bool known: false
        property string channel: ""
        property int frequencyPercent: 0
        property int integrationTime: 0

        function clear() {
            known = false;
            channel = "";
            frequencyPercent = 0;
            integrationTime = 0;
        }

        function apply(value) {
            clear();
            if (value === null)
                return true;
            if (!value || ["red", "white", "blue", "green"].indexOf(value.channel) < 0 || [0, 2, 20, 100].indexOf(value.frequencyPercent) < 0 || !Number.isInteger(value.integrationTime) || value.integrationTime < 0 || value.integrationTime > 65535)
                return false;
            channel = value.channel;
            frequencyPercent = value.frequencyPercent;
            integrationTime = value.integrationTime;
            known = true;
            return true;
        }

        function stateObject() {
            return known ? {
                "channel": channel,
                "frequencyPercent": frequencyPercent,
                "integrationTime": integrationTime
            } : null;
        }
    }

    // Enumeration-only discovery never activates the sensor.
    property bool monitoring: false
    property bool found: false
    property string probeOutput: ""
    signal sampleFinished

    function refreshPresence() {
        if (busy || presenceProbe.running)
            return;
        probeOutput = "";
        presenceProbe.running = true;
    }

    function finishPresence(code) {
        let present = false;
        try {
            const result = JSON.parse(probeOutput);
            present = code === 0 && result.found === true && result.error === "";
        } catch (error) {}
        found = present;
    }

    property string status: "idle"
    readonly property bool busy: status === "reading"
    property real rawCount: -1
    property string readAt: ""
    property string errorCode: ""
    property string restorationStatus: "not-needed"
    property string operationError: ""
    property string restoreError: ""
    property string verificationError: ""
    property string cleanupError: ""
    property string helperOutput: ""
    readonly property Settings originalSettings: Settings {}
    readonly property Settings effectiveSettings: Settings {}
    readonly property Settings restoredSettings: Settings {}

    function stateJson() {
        return JSON.stringify({
            "status": status,
            "found": found,
            "busy": busy,
            "raw": status === "ready" ? rawCount : null,
            "unit": "counts",
            "channel": effectiveSettings.channel,
            "frequencyPercent": effectiveSettings.frequencyPercent,
            "integrationTime": effectiveSettings.integrationTime,
            "readAt": readAt,
            "error": errorCode,
            "original": originalSettings.stateObject(),
            "effective": effectiveSettings.stateObject(),
            "restored": restoredSettings.stateObject(),
            "restoration": restorationStatus,
            "operationError": operationError,
            "restoreError": restoreError,
            "verificationError": verificationError,
            "cleanupError": cleanupError,
            // A sample with failed restoration is diagnostic, never ready data.
            "measurement": rawCount < 0 ? null : {
                "raw": rawCount,
                "unit": "counts"
            }
        });
    }

    function requestRead() {
        if (busy)
            return;
        helperOutput = "";
        rawCount = -1;
        readAt = "";
        errorCode = "";
        restorationStatus = "pending";
        operationError = "";
        restoreError = "";
        verificationError = "";
        cleanupError = "";
        originalSettings.clear();
        effectiveSettings.clear();
        restoredSettings.clear();
        status = "reading";
        reader.running = true;
    }

    function finish(code) {
        if (!busy)
            return;
        let failure = code === 0 ? "invalid-response" : code === 124 || code === 137 ? "timeout" : code === 127 ? "helper-not-built" : "read-failed";
        restorationStatus = code === 127 ? "not-needed" : "unverified";
        let result;
        try {
            result = JSON.parse(helperOutput);
        } catch (error) {
            errorCode = failure;
            status = "unavailable";
            sampleFinished();
            return;
        }
        const knownErrors = ["", "invalid-arguments", "usb-context-failed", "no-device", "usb-open-failed", "configuration-read-failed", "unexpected-configuration", "interface-claim-failed", "sensor-state-read-failed", "sensor-state-invalid", "activation-scale-failed", "activation-integral-failed", "effective-read-failed", "effective-mismatch", "sensor-reading-failed", "interrupted", "work-timeout", "restore-scale-failed", "restore-integral-failed", "verification-read-failed", "verification-state-invalid", "verification-mismatch", "interface-release-failed", "usb-close-failed"];
        const valid = result && result.unit === "counts" && ["ready", "unavailable"].indexOf(result.status) >= 0 && ["verified", "mismatch", "unverified", "not-needed"].indexOf(result.restoration) >= 0 && [result.error, result.operationError, result.restoreError, result.verificationError, result.cleanupError].every(value => knownErrors.indexOf(value) >= 0) && originalSettings.apply(result.original) && effectiveSettings.apply(result.effective) && restoredSettings.apply(result.restored);
        const verified = originalSettings.known && restoredSettings.known && JSON.stringify(originalSettings.stateObject()) === JSON.stringify(restoredSettings.stateObject());
        const sampleValid = valid && Number.isInteger(result.raw) && result.raw >= 0 && result.raw <= 4294967295 && effectiveSettings.known && effectiveSettings.frequencyPercent > 0 && effectiveSettings.integrationTime > 0 && result.channel === effectiveSettings.channel && result.frequencyPercent === effectiveSettings.frequencyPercent && result.integrationTime === effectiveSettings.integrationTime;
        if (valid && (result.raw === null || sampleValid) && (result.restoration !== "verified" || verified)) {
            restorationStatus = result.restoration;
            operationError = result.operationError;
            restoreError = result.restoreError;
            verificationError = result.verificationError;
            cleanupError = result.cleanupError;
            if (sampleValid)
                rawCount = result.raw;
            if (code === 0 && result.status === "ready" && sampleValid && result.restoration === "verified" && !result.error && !operationError && !restoreError && !verificationError && !cleanupError) {
                readAt = new Date().toISOString();
                errorCode = "";
                status = "ready";
                sampleFinished();
                return;
            }
            if (code !== 0 && result.status === "unavailable" && result.error)
                failure = result.error;
        }
        errorCode = failure;
        status = "unavailable";
        sampleFinished();
    }

    Timer {
        interval: 5000
        repeat: true
        triggeredOnStart: true
        running: root.monitoring
        onTriggered: root.refreshPresence()
    }

    Process {
        id: presenceProbe

        command: ["/usr/bin/timeout", "--kill-after=1s", "3s", Quickshell.shellPath("ambient-light-native/read"), "--probe"]
        stdout: SplitParser {
            onRead: data => root.probeOutput = (root.probeOutput + data + "\n").slice(0, 256)
        }
        stderr: SplitParser {}
        onExited: (code, exitStatus) => root.finishPresence(exitStatus === 0 ? code : 128 + code)
        onRunningChanged: {
            if (!running)
                Qt.callLater(() => {
                    if (!presenceProbe.running && root.probeOutput.length === 0)
                        root.found = false;
                });
        }
    }

    Process {
        id: reader

        command: ["/usr/bin/timeout", "--kill-after=1s", "10s", Quickshell.shellPath("ambient-light-native/read")]
        stdout: SplitParser {
            onRead: data => root.helperOutput = (root.helperOutput + data + "\n").slice(0, 2048)
        }
        stderr: SplitParser {}
        onExited: (code, exitStatus) => root.finish(exitStatus === 0 ? code : 128 + code)
        onRunningChanged: {
            if (!running)
                Qt.callLater(() => {
                    if (root.busy && !reader.running)
                        root.finish(127);
                });
        }
    }
}