Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/Brightness.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Io
import "../.."
import "../osd"
import "brightness.js" as Brightness
import "adaptive-brightness.js" as Adaptive

Item {
    id: root

    property Osd osdService
    property Niri niriService
    property Privilege privilegeService
    property AmbientLight ambientLightService: null
    property var adaptiveConfig: Adaptive.normalizeConfig(null)
    property bool persistenceReady: false
    property string persistenceError: ""
    property int currentBucket: -1
    property var adaptiveRaw: null
    property var adaptiveSmoothed: null
    property real adaptiveReadAt: 0
    property string adaptiveSignature: ""
    property string adaptiveError: ""
    property bool adaptiveUnsafe: false
    property int adaptiveGeneration: 0
    property var adaptiveTransitions: ({})
    property int adaptiveTransitionStep: 0
    property bool adaptiveReapplyNeeded: false
    readonly property bool adaptiveTransitioning: Object.keys(adaptiveTransitions).length > 0
    property int adaptiveSampleEpoch: 0
    property int adaptiveRequestedEpoch: -1
    property bool adaptiveReadPending: false
    // A sample older than this stops adaptation; motion eases over this many ticks.
    readonly property int adaptiveSampleLifetime: 10000
    readonly property int adaptiveSteps: 20
    readonly property bool adaptiveEnabled: adaptiveConfig.enabled
    readonly property var adaptiveThresholds: adaptiveConfig.thresholds
    readonly property var adaptiveBuckets: Adaptive.buckets(adaptiveConfig)
    readonly property var adaptiveRows: Brightness.displayRows({
        "present": backlightPresent(),
        "level": levelFraction()
    }, outputRows(), ddcDisplays)
    // Adaptive could run as soon as a sensor appears.
    readonly property bool adaptiveEligible: setupReady && !setupRunning && adaptiveRows.some(row => row.kind === "ddc" && row.controllable)
    readonly property bool adaptiveAvailable: !!ambientLightService && ambientLightService.found && adaptiveEligible
    // Set by the registry while the popup is open.
    property bool panelOpen: false
    // Sensor discovery only while someone sees its state or adaptive mode needs it.
    readonly property bool sensorWanted: panelOpen || (adaptiveEnabled && adaptiveEligible)
    readonly property bool adaptiveSampling: persistenceReady && adaptiveEnabled && adaptiveAvailable && !adaptiveUnsafe
    readonly property bool adaptiveActive: adaptiveSampling && currentBucket >= 0

    onAdaptiveSamplingChanged: {
        resetAdaptive();
    }
    onAmbientLightServiceChanged: resetAdaptive()
    // Connector removal must invalidate queued work even when another DDC row remains.
    readonly property string adaptiveTopology: adaptiveRows.filter(row => row.controllable).map(row => row.id).sort().join("|")
    onAdaptiveTopologyChanged: resetAdaptive()

    function resetAdaptive() {
        adaptiveSampleEpoch++;
        adaptiveGeneration++;
        adaptiveTransitions = ({});
        adaptiveTransitionStep = 0;
        adaptiveReapplyNeeded = false;
        writeQueue = writeQueue.filter(write => write.source !== "adaptive");
        currentBucket = -1;
        adaptiveRaw = null;
        adaptiveSmoothed = null;
        adaptiveReadAt = 0;
        adaptiveSignature = "";
    }

    function saveAdaptive() {
        if (persistenceReady)
            adaptiveFile.setText(JSON.stringify(adaptiveConfig));
    }

    function loadAdaptive(text) {
        try {
            adaptiveConfig = Adaptive.normalizeConfig(JSON.parse(text));
        } catch (error) {
            persistenceError = "invalid adaptive settings";
        }
        persistenceReady = true;
    }

    function setAdaptiveEnabled(enabled) {
        if (typeof enabled !== "boolean")
            return stateJson();
        resetAdaptive();
        adaptiveUnsafe = false;
        adaptiveError = "";
        adaptiveConfig = Object.assign({}, adaptiveConfig, {
            "enabled": enabled
        });
        saveAdaptive();
        // Explicit retry also works when already enabled.
        Qt.callLater(sampleAdaptive);
        return stateJson();
    }

    function toggleAdaptive() {
        return setAdaptiveEnabled(!adaptiveEnabled);
    }

    // True when the confirmed threshold now equals `value`; edits clamp between neighbours.
    function setAdaptiveThreshold(index, value) {
        const thresholds = Adaptive.editThreshold(adaptiveThresholds, index, value);
        if (!thresholds)
            return adaptiveThresholds[index] === value;
        adaptiveConfig = Object.assign({}, adaptiveConfig, {
            "thresholds": thresholds
        });
        saveAdaptive();
        // Never change intent-time learning scope while editing an inactive bucket.
        // Reclassify on the next terminal sample, not against old measurements.
        adaptiveGeneration++;
        adaptiveTransitions = ({});
        adaptiveReapplyNeeded = true;
        writeQueue = writeQueue.filter(write => write.source !== "adaptive");
        return thresholds[index] === value;
    }

    function sampleAdaptive() {
        if (adaptiveSampling && ambientLightService && !ambientLightService.busy) {
            adaptiveRequestedEpoch = adaptiveSampleEpoch;
            adaptiveReadPending = true;
            ambientLightService.requestRead();
        }
    }

    function acceptAdaptiveSample() {
        const sensor = ambientLightService;
        if (!sensor)
            return;
        if (sensor.restoreError || sensor.verificationError || sensor.cleanupError || sensor.restorationStatus === "unverified" || sensor.restorationStatus === "mismatch") {
            adaptiveUnsafe = true;
            adaptiveError = "sensor cleanup failed; toggle to retry";
            resetAdaptive();
            return;
        }
        const obsolete = adaptiveReadPending && adaptiveRequestedEpoch !== adaptiveSampleEpoch;
        adaptiveReadPending = false;
        if (!adaptiveSampling || obsolete)
            return;
        const timestamp = Date.parse(sensor.readAt);
        if (sensor.status !== "ready" || sensor.errorCode || !isFinite(sensor.rawCount) || sensor.rawCount < 0 || !isFinite(timestamp) || Date.now() - timestamp >= adaptiveSampleLifetime || timestamp > Date.now()) {
            adaptiveError = "sensor read failed";
            resetAdaptive();
            return;
        }
        const settings = sensor.effectiveSettings;
        const signature = JSON.stringify([settings.channel, settings.frequencyPercent, settings.integrationTime]);
        if (signature !== adaptiveSignature) {
            resetAdaptive();
            adaptiveSignature = signature;
        }
        adaptiveError = "";
        adaptiveRaw = sensor.rawCount;
        adaptiveReadAt = timestamp;
        adaptiveSmoothed = Adaptive.smooth(adaptiveSmoothed, adaptiveRaw);
        const next = Adaptive.bucket(adaptiveSmoothed, adaptiveThresholds, currentBucket);
        if (next !== currentBucket || adaptiveReapplyNeeded) {
            adaptiveReapplyNeeded = false;
            currentBucket = next;
            adaptiveGeneration++;
            writeQueue = writeQueue.filter(write => write.source !== "adaptive");
            applyAdaptive();
        }
    }

    function applyAdaptive() {
        if (!adaptiveActive)
            return;
        const transitions = {};
        for (const row of adaptiveRows) {
            if (!row.controllable)
                continue;
            // Do not fight a drag or a pending manual intent, even across buckets.
            if ((writePending && activeWrite.id === row.id && activeWrite.source === "manual") || writeQueue.some(write => write.id === row.id && write.source === "manual"))
                continue;
            const actual = deviceLevel(row, Adaptive.target(adaptiveConfig, row.id, currentBucket));
            if (Math.abs(row.level - actual) < 0.000001 && !(writePending && activeWrite.id === row.id && activeWrite.source === "adaptive"))
                continue;
            transitions[row.id] = {
                "from": row.level,
                "target": actual,
                "bucket": currentBucket,
                "generation": adaptiveGeneration
            };
        }
        adaptiveTransitions = transitions;
        adaptiveTransitionStep = 0;
    }

    // The nearest level the device can show; a backlight never turns fully off.
    function deviceLevel(row, level) {
        const maximum = row.kind === "ddc" ? ddcDisplays[row.id.slice(4)].maximum : nativeMax();
        return Math.max(row.kind === "ddc" ? 0 : 1, Math.round(level * maximum)) / maximum;
    }

    function cancelAdaptiveDisplay(id) {
        const transitions = Object.assign({}, adaptiveTransitions);
        delete transitions[id];
        adaptiveTransitions = transitions;
        writeQueue = writeQueue.filter(write => write.id !== id || write.source !== "adaptive");
    }

    function advanceAdaptive() {
        if (!adaptiveActive || writePending || writeQueue.length)
            return;
        if (Date.now() - adaptiveReadAt >= adaptiveSampleLifetime) {
            adaptiveError = "sensor sample stale";
            resetAdaptive();
            return;
        }
        adaptiveTransitionStep = Math.min(adaptiveSteps, adaptiveTransitionStep + 1);
        for (const id of Object.keys(adaptiveTransitions)) {
            const transition = adaptiveTransitions[id];
            const row = adaptiveRows.find(display => display.id === id && display.controllable);
            if (!row) {
                cancelAdaptiveDisplay(id);
                continue;
            }
            const level = deviceLevel(row, Adaptive.easedLevel(transition.from, transition.target, adaptiveTransitionStep / adaptiveSteps));
            if (Math.abs(row.level - level) >= 0.000001)
                enqueueWrite(id, level, "adaptive", transition.bucket, transition.generation);
            else if (adaptiveTransitionStep === adaptiveSteps)
                cancelAdaptiveDisplay(id);
        }
    }
    property var setupStages: Brightness.initialStages()
    property bool setupRunning: false
    property bool setupExpanded: false
    property bool setupReady: false
    property bool cancelRequested: false
    property string stopReason: ""
    property int setupEpoch: 0
    property string setupStage: ""
    property string setupError: ""
    property var preflight: ({})
    property string retryStage: ""
    property var readQueue: []
    property string readingName: ""
    property string operation: ""
    property bool operationPending: false
    property string operationOutput: ""
    property bool privilegedEntered: false
    property var writeQueue: []
    property var activeWrite: ({})
    property bool writePending: false
    property string writeOutput: ""
    property string devicePath: "/sys/class/backlight/intel_backlight"
    property var ddcDisplays: ({})
    property var lastAction: ({})
    property var lastOsd: ({})
    // Last confirmed native write; failures never replace the previous level.
    property real liveLevel: -1
    property string nativeError: ""
    // Panel state; stateObject() reuses it for IPC.
    readonly property var displays: Brightness.displayRows({
        "present": backlightPresent(),
        "level": Math.round(levelFraction() * 100) / 100,
        "error": nativeError
    }, outputRows(), ddcDisplays)
    readonly property var globalState: Brightness.globalState(displays)
    readonly property string globalMode: globalState.mode
    readonly property real globalLevel: globalState.level
    readonly property var globalLevels: globalState.levels
    // Internal panels use backlight; only external displays need DDC setup.
    readonly property bool setupNeeded: displays.some(row => row.kind === "ddc" && !row.controllable)
    readonly property bool setupAvailable: !setupRunning && !writePending && writeQueue.length === 0
    // Adaptive's heading row needs a light sensor route.
    readonly property bool adaptiveRoute: ambientLightService !== null

    function intText(text, fallback) {
        const n = parseInt(String(text || "").trim(), 10);
        return isFinite(n) ? n : fallback;
    }

    function backlightPresent() {
        const maximum = String(maxFile.text() || "").trim();
        const current = String(brightnessFile.text() || "").trim();
        return /^\d+$/.test(maximum) && /^\d+$/.test(current) && Number(maximum) > 0 && Number(current) <= Number(maximum);
    }

    function nativeMax() {
        return Math.max(1, intText(maxFile.text(), 1));
    }

    function nativeBrightness() {
        return Math.max(1, intText(brightnessFile.text(), nativeMax()));
    }

    function levelFraction() {
        if (!backlightPresent())
            return 0;

        if (liveLevel >= 0)
            return Brightness.clampLevel(liveLevel);

        return Brightness.clampLevel(nativeBrightness() / nativeMax());
    }

    function outputRows() {
        return niriService ? niriService.outputList() : [];
    }

    // Without an OSD service, or on an unreadable reply, report the requested event.
    function triggerOsd(value) {
        const text = String(Brightness.levelPercent(value));
        const requested = {
            "event": "brightness",
            "value": text
        };
        if (!osdService)
            return requested;
        try {
            return osdService.trigger("brightness", text);
        } catch (error) {
            return requested;
        }
    }

    function stateObject() {
        return {
            "level": globalLevel,
            "adaptive": {
                "enabled": adaptiveEnabled,
                "available": adaptiveAvailable,
                "active": adaptiveActive,
                "transitioning": adaptiveTransitioning,
                "currentBucket": currentBucket,
                "raw": adaptiveRaw,
                "smoothed": adaptiveSmoothed,
                "thresholds": adaptiveThresholds,
                "buckets": adaptiveBuckets,
                "error": adaptiveError,
                "persistenceError": persistenceError
            },
            "displays": displays,
            "global": {
                "mode": globalMode,
                "level": globalLevel,
                "levels": globalLevels
            },
            "setup": {
                "needed": setupNeeded,
                "available": setupAvailable,
                "running": setupRunning,
                "expanded": setupExpanded,
                "ready": setupReady,
                "stage": setupStage,
                "stages": setupStages,
                "error": setupError,
                "cancelRequested": cancelRequested
            },
            "compact": {
                "label": "brightness",
                "role": Brightness.levelRole(globalLevel)
            },
            "pendingWrites": (writePending ? [activeWrite.id] : []).concat(writeQueue.map(write => write.id)),
            "lastAction": lastAction,
            "lastOsd": lastOsd
        };
    }

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

    function stage(id, status, error) {
        setupStage = id;
        setupStages = Brightness.stageState(setupStages, id, status, error || "");
    }

    function failSetup(message) {
        setupError = Brightness.diagnostic(message);
        const current = setupStages.find(item => item.id === setupStage);
        // Cancellation between stages must not erase completed work.
        if (!current || current.status !== "done")
            stage(setupStage, "failed", setupError);
        setupRunning = false;
    }

    function runOperation(kind, command) {
        operation = kind;
        operationOutput = "";
        operationPending = true;
        setupProcess.command = command;
        setupProcess.running = true;
    }

    function deferSetup(next) {
        const epoch = setupEpoch;
        Qt.callLater(() => {
            if (setupRunning && !cancelRequested && epoch === setupEpoch)
                next();
        });
    }

    function beginAuthorization() {
        if (!setupRunning || cancelRequested)
            return;
        stage("authorization", "running");
        if (!privilegeService || !privilegeService.polkitAgent || !privilegeService.polkitAgent.isRegistered) {
            failSetup("authorization unavailable");
            return;
        }
        if (privilegeService.polkitAgent.isActive) {
            failSetup("authorization busy");
            return;
        }
        // pkexec delegates to this registered native PolkitAgent automatically.
        // No secret handoff, second agent, global authorized flag or detached job.
        privilegedEntered = false;
        runOperation("privileged", Brightness.privilegedCommand(!preflight.installed));
        authorizationDeadline.restart();
    }

    function beginDetection() {
        stage("detection", "running");
        runOperation("detect", Brightness.ddcCommand("detect"));
    }

    function beginReads() {
        stage("reading", "running");
        readQueue = Object.keys(ddcDisplays).filter(name => !ddcDisplays[name].controllable);
        readNext();
    }

    function readNext() {
        if (cancelRequested) {
            failSetup(stopReason || "cancelled");
            return;
        }
        if (readQueue.length === 0) {
            const failedRead = Object.keys(ddcDisplays).some(name => !ddcDisplays[name].controllable && !!ddcDisplays[name].error);
            if (failedRead) {
                failSetup("read failed");
                return;
            }
            stage("reading", "done");
            stage("verification", "running");
            const rows = displays.filter(row => row.kind === "ddc");
            if (!rows.length || !rows.some(row => row.controllable)) {
                failSetup("read failed");
            } else if (rows.some(row => !row.controllable)) {
                failSetup("some displays unavailable");
            } else {
                stage("verification", "done");
                stage("ready", "done");
                setupReady = true;
                setupRunning = false;
                setupExpanded = false;
            }
            return;
        }
        readingName = readQueue[0];
        readQueue = readQueue.slice(1);
        runOperation("read", Brightness.ddcCommand("read", ddcDisplays[readingName].bus));
    }

    function consumeOutput(data) {
        operationOutput = (operationOutput + data + "\n").slice(0, 65536);
        if (operation === "privileged" && data === "nugu:authorized") {
            authorizationDeadline.stop();
            if (cancelRequested) {
                setupProcess.write("cancel\n");
                return;
            }
            privilegedEntered = true;
            stage("authorization", "done");
            stage("installation", "running");
            installationDeadline.restart();
            setupProcess.write("continue\n");
        }
    }

    function authorizationExpired() {
        if (operationPending && operation === "privileged" && !privilegedEntered) {
            cancelRequested = true;
            stopReason = "timeout";
            setupError = stopReason;
            setupProcess.write("cancel\n");
            setupProcess.running = false;
        }
    }

    function installationExpired() {
        if (operationPending && operation === "privileged" && privilegedEntered) {
            cancelRequested = true;
            stopReason = "timeout";
            setupError = stopReason;
            stage("installation", "failed", stopReason);
            // Keep ownership until the package process actually exits. Its INT
            // deadline permits pacman cleanup; never SIGKILL a package transaction.
        }
    }

    function finishOperation(code) {
        if (!operationPending)
            return;
        operationPending = false;
        authorizationDeadline.stop();
        installationDeadline.stop();
        const kind = operation;
        if (cancelRequested) {
            failSetup(stopReason || "cancelled");
            return;
        }
        if (kind === "preflight" || kind === "refresh" || kind === "retry-preflight") {
            if (code !== 0) {
                failSetup(Brightness.processError(code, "preflight failed"));
                return;
            }
            preflight = Brightness.parsePreflight(operationOutput);
            if (kind === "preflight" || kind === "retry-preflight") {
                stage("preflight", "done");
                if (preflight.needsPrivilege) {
                    deferSetup(beginAuthorization);
                    return;
                }
                stage("authorization", "done");
                stage("installation", "done");
                if (kind === "retry-preflight" && retryStage === "reading") {
                    deferSetup(beginReads);
                    return;
                }
            }
            deferSetup(beginDetection);
        } else if (kind === "privileged") {
            if (code !== 0) {
                failSetup(Brightness.processError(code, privilegedEntered ? "installation failed" : "authorization denied"));
                return;
            }
            stage("installation", "done");
            // New device nodes/ACLs and DRM links may have appeared.
            deferSetup(() => runOperation("refresh", Brightness.preflightCommand()));
        } else if (kind === "detect") {
            // ddcutil may return nonzero for one invalid display. Keep successful buses.
            const found = Brightness.parseDetection(operationOutput, preflight.connectors);
            for (const name of Object.keys(found)) {
                const previous = ddcDisplays[name];
                if (previous && previous.bus === found[name].bus && previous.controllable)
                    found[name] = previous;
            }
            ddcDisplays = found;
            if (!Object.keys(found).length) {
                failSetup(Brightness.processError(code, code === 0 ? "no mapped displays" : "detection failed"));
                return;
            }
            stage("detection", "done");
            deferSetup(beginReads);
        } else if (kind === "read") {
            const reading = code === 0 ? Brightness.parseBrightness(operationOutput) : null;
            const copy = Object.assign({}, ddcDisplays);
            copy[readingName] = Object.assign({}, copy[readingName], reading || {}, {
                "controllable": !!reading,
                "error": reading ? "" : Brightness.processError(code, "read failed")
            });
            ddcDisplays = copy;
            deferSetup(readNext);
        }
    }

    function setupDdc() {
        if (setupRunning || writePending || writeQueue.length)
            return stateJson();
        setupEpoch++;
        setupExpanded = true;
        setupRunning = true;
        setupReady = false;
        cancelRequested = false;
        stopReason = "";
        setupError = "";
        setupStages = Brightness.initialStages();
        stage("preflight", "running");
        lastAction = {
            "kind": "setup-ddc"
        };
        runOperation("preflight", Brightness.preflightCommand());
        return stateJson();
    }

    function retrySetup() {
        if (setupRunning || writePending || writeQueue.length)
            return stateJson();
        const failed = setupStage;
        setupEpoch++;
        setupRunning = true;
        cancelRequested = false;
        stopReason = "";
        setupError = "";
        retryStage = failed;
        // Retained package/session changes are facts to re-read, not assumptions
        // from the original attempt. Never authorize from a stale preflight.
        stage("preflight", "running");
        runOperation("retry-preflight", Brightness.preflightCommand());
        return stateJson();
    }

    function cancelSetup() {
        if (!setupRunning)
            return stateJson();
        setupEpoch++;
        cancelRequested = true;
        stopReason = "cancelled";
        if (operationPending && operation === "privileged" && !privilegedEntered) {
            setupProcess.write("cancel\n");
            setupProcess.running = false;
        } else if (operationPending && operation === "privileged") {
            // A root transaction cannot safely be killed by this unprivileged owner.
            // Keep tracking until exit; never claim rollback or release the busy guard.
            setupError = "cancel requested; waiting for package setup";
        } else if (!operationPending) {
            failSetup(stopReason || "cancelled");
        }
        // Unprivileged commands already have short process-group deadlines.
        return stateJson();
    }

    function toggleSetup() {
        setupExpanded = !setupExpanded;
        return stateJson();
    }

    function setDisplay(id, level) {
        const row = displays.find(display => display.id === String(id));
        if (setupRunning || !row || !row.controllable)
            return stateJson();
        cancelAdaptiveDisplay(String(id));
        enqueueWrite(String(id), Brightness.clampLevel(level), "manual", adaptiveActive ? currentBucket : -1);
        return stateJson();
    }

    function enqueueWrite(id, level, source, bucket, generation) {
        const request = {
            "id": id,
            "level": level,
            "source": source,
            "bucket": bucket,
            "generation": generation === undefined ? adaptiveGeneration : generation
        };
        // Coalesce slider motion per display; manual always replaces queued auto.
        writeQueue = writeQueue.filter(write => write.id !== request.id).concat([request]);
        startWrite();
    }

    function startWrite() {
        if (writePending || !writeQueue.length)
            return;
        activeWrite = writeQueue[0];
        writeQueue = writeQueue.slice(1);
        const row = adaptiveRows.find(display => display.id === activeWrite.id);
        if (setupRunning || !row || !row.controllable || (activeWrite.source === "adaptive" && (!adaptiveActive || activeWrite.generation !== adaptiveGeneration || Date.now() - adaptiveReadAt >= adaptiveSampleLifetime))) {
            Qt.callLater(startWrite);
            return;
        }
        let command;
        if (activeWrite.id === "backlight") {
            // Paths/values are positional arguments, never interpolated shell source.
            const native = Math.max(1, Math.round(activeWrite.level * nativeMax()));
            command = Brightness.timedCommand(5, ["/usr/bin/sh", "-c", "printf '%s\\n' \"$2\" > \"$1/brightness\" && /usr/bin/cat \"$1/brightness\"", "nugu-backlight", devicePath, String(native)]);
        } else {
            const state = ddcDisplays[activeWrite.id.slice(4)];
            command = state && state.controllable ? Brightness.ddcCommand("write", state.bus, activeWrite.level, state.maximum) : [];
        }
        if (!command.length) {
            finishWrite(1);
            return;
        }
        writeOutput = "";
        writePending = true;
        writeProcess.command = command;
        writeProcess.running = true;
    }

    function finishWrite(code) {
        writePending = false;
        const readback = String(writeOutput).trim();
        const native = /^\d+$/.test(readback) ? Number(readback) : -1;
        const success = code === 0 && (activeWrite.id !== "backlight" || (native >= 0 && native <= nativeMax()));
        const error = success ? "" : Brightness.processError(code, "write failed");
        if (activeWrite.id === "backlight") {
            if (success)
                liveLevel = native / nativeMax();
            nativeError = error;
        } else {
            const name = String(activeWrite.id).slice(4);
            const copy = Object.assign({}, ddcDisplays);
            if (copy[name]) {
                copy[name] = Object.assign({}, copy[name], {
                    "error": error
                });
                if (success)
                    copy[name].level = Math.round(activeWrite.level * copy[name].maximum) / copy[name].maximum;
            }
            ddcDisplays = copy;
        }
        lastAction = {
            "kind": "set-display",
            "id": activeWrite.id,
            "source": activeWrite.source,
            "level": activeWrite.level,
            "success": success,
            "error": error
        };
        const confirmed = activeWrite.id === "backlight" ? liveLevel : (ddcDisplays[activeWrite.id.slice(4)] || {}).level;
        if (activeWrite.source === "adaptive") {
            const transition = adaptiveTransitions[activeWrite.id];
            if (!success || (transition && activeWrite.generation === transition.generation && adaptiveTransitionStep === adaptiveSteps)) {
                if (success && Math.abs(confirmed - transition.target) >= 0.000001) {
                    adaptiveError = "adaptive target not confirmed";
                    if (activeWrite.id === "backlight")
                        nativeError = adaptiveError;
                }
                cancelAdaptiveDisplay(activeWrite.id);
            } else if (transition && activeWrite.generation !== transition.generation) {
                // Retargeting cannot undo an in-flight command. Rebase only after its ACK.
                const transitions = Object.assign({}, adaptiveTransitions);
                transitions[activeWrite.id] = Object.assign({}, transition, {
                    "from": confirmed
                });
                adaptiveTransitions = transitions;
            }
        }
        if (success && activeWrite.source === "manual" && activeWrite.bucket >= 0 && typeof confirmed === "number") {
            adaptiveConfig = Adaptive.learn(adaptiveConfig, activeWrite.id, activeWrite.bucket, confirmed);
            saveAdaptive();
        }
        if (success && activeWrite.source !== "adaptive")
            lastOsd = triggerOsd(confirmed);
        Qt.callLater(startWrite);
    }

    function setAll(level) {
        const value = Brightness.clampLevel(level);
        const rows = displays;
        for (let i = 0; i < rows.length; i++) {
            if (rows[i].controllable)
                setDisplay(rows[i].id, value);
        }
        lastAction = {
            "kind": "set-all",
            "level": Math.round(value * 100) / 100
        };
        return stateJson();
    }

    function increase() {
        return setAll(globalLevel + 0.05);
    }

    function decrease() {
        return setAll(globalLevel - 0.05);
    }

    Process {
        id: setupProcess

        stdinEnabled: true
        stdout: SplitParser {
            onRead: data => root.consumeOutput(data)
        }
        stderr: SplitParser {}
        onExited: (exitCode, exitStatus) => root.finishOperation(exitStatus === 0 ? exitCode : 128 + exitCode)
        onRunningChanged: {
            if (!running)
                Qt.callLater(() => {
                    // QProcess FailedToStart does not emit exited.
                    if (root.operationPending && !setupProcess.running)
                        root.finishOperation(127);
                });
        }
    }

    Timer {
        id: authorizationDeadline

        interval: 120000
        onTriggered: root.authorizationExpired()
    }

    Timer {
        id: installationDeadline

        interval: 370000
        onTriggered: root.installationExpired()
    }

    Process {
        id: writeProcess

        // Only backlight's strict numeric readback is consumed; never exposed raw.
        stdout: SplitParser {
            onRead: data => root.writeOutput = (root.writeOutput + data + "\n").slice(0, 128)
        }
        stderr: SplitParser {}
        onExited: (exitCode, exitStatus) => root.finishWrite(exitStatus === 0 ? exitCode : 128 + exitCode)
        onRunningChanged: {
            if (!running)
                Qt.callLater(() => {
                    if (root.writePending && !writeProcess.running)
                        root.finishWrite(127);
                });
        }
    }

    Connections {
        target: root.ambientLightService
        function onSampleFinished() {
            root.acceptAdaptiveSample();
        }
    }

    Timer {
        id: adaptiveTransitionTimer
        interval: 100
        repeat: true
        running: root.adaptiveActive && root.adaptiveTransitioning
        onTriggered: root.advanceAdaptive()
    }

    Timer {
        interval: 2000
        repeat: true
        triggeredOnStart: true
        running: root.adaptiveSampling
        onTriggered: root.sampleAdaptive()
    }

    Timer {
        interval: 500
        repeat: true
        running: root.adaptiveSampling
        onTriggered: {
            if (root.adaptiveReadAt > 0 && Date.now() - root.adaptiveReadAt >= root.adaptiveSampleLifetime) {
                root.resetAdaptive();
                root.adaptiveError = "sensor sample stale";
            }
        }
    }

    FileView {
        id: adaptiveFile
        path: Quickshell.statePath("adaptive-brightness.json")
        atomicWrites: true
        blockWrites: true
        printErrors: false
        onLoaded: root.loadAdaptive(adaptiveFile.text())
        onLoadFailed: error => {
            if (error !== FileViewError.FileNotFound)
                root.persistenceError = "adaptive settings could not be read";
            root.persistenceReady = true;
        }
        onSaveFailed: root.persistenceError = "adaptive settings could not be saved"
    }

    FileView {
        id: brightnessFile

        path: `${root.devicePath}/brightness`
        blockLoading: true
        blockAllReads: true
        printErrors: false
    }

    FileView {
        id: maxFile

        path: `${root.devicePath}/max_brightness`
        blockLoading: true
        blockAllReads: true
        printErrors: false
    }
}