Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/fixtures/services/Brightness.qml

Raw
import QtQuick

Item {
    // Inputs the registry forwards to the production service.
    property var osdService: null
    property var niriService: null
    property var privilegeService: null
    property var ambientLightService: null
    property real level: 0.5
    property int writes: 0
    property bool available: true
    property var snapshotOverride: null
    property int setups: 0
    property int cancellations: 0
    property int retries: 0
    property string lastDisplay: ""
    // The registry sets this while the popup is open; it gates sensor discovery.
    property bool panelOpen: false
    readonly property bool setupExpanded: !!(snapshotOverride && snapshotOverride.setup && snapshotOverride.setup.expanded)
    readonly property bool sensorWanted: panelOpen || !!(snapshotOverride && snapshotOverride.adaptive && snapshotOverride.adaptive.enabled && snapshotOverride.setup && snapshotOverride.setup.ready)
    // The production service's panel properties, read from the suite's state
    // (or the base display), so the panel binds identically to both.
    readonly property var current: stateObject()
    readonly property var displays: current.displays || []
    readonly property string globalMode: current.global ? String(current.global.mode) : "none"
    readonly property real globalLevel: current.global ? Number(current.global.level || 0) : 0
    readonly property var globalLevels: current.global ? current.global.levels || [] : []
    readonly property bool setupNeeded: !!(current.setup && current.setup.needed)
    readonly property bool setupAvailable: !!(current.setup && current.setup.available)
    readonly property bool setupRunning: !!(current.setup && current.setup.running)
    readonly property bool setupReady: !!(current.setup && current.setup.ready)
    readonly property var setupStages: current.setup && current.setup.stages || []
    readonly property string setupError: String(current.setup && current.setup.error || "")
    readonly property bool cancelRequested: !!(current.setup && current.setup.cancelRequested)
    // A state without adaptive has no light sensor route.
    readonly property bool adaptiveRoute: !!current.adaptive
    readonly property bool adaptiveEnabled: !!(current.adaptive && current.adaptive.enabled)
    readonly property bool adaptiveAvailable: !!(current.adaptive && current.adaptive.available)
    readonly property bool adaptiveActive: !!(current.adaptive && current.adaptive.active)
    readonly property int currentBucket: current.adaptive && typeof current.adaptive.currentBucket === "number" ? current.adaptive.currentBucket : -1
    readonly property var adaptiveRaw: current.adaptive && typeof current.adaptive.raw === "number" ? current.adaptive.raw : null
    readonly property var adaptiveThresholds: current.adaptive && current.adaptive.thresholds || []
    readonly property string adaptiveError: String(current.adaptive && current.adaptive.error || "")
    readonly property string persistenceError: String(current.adaptive && current.adaptive.persistenceError || "")

    function copyState() {
        return snapshotOverride ? JSON.parse(JSON.stringify(snapshotOverride)) : null;
    }

    function updateGlobal(state) {
        const levels = state.displays.filter(row => row.controllable).map(row => row.level);
        state.global = {
            mode: levels.length === 0 ? "none" : levels.every(value => value === levels[0]) ? "synced" : "mixed",
            level: levels.length ? levels.reduce((sum, value) => sum + value, 0) / levels.length : 0,
            levels: levels
        };
    }

    function learnAdaptive(state, row) {
        const adaptive = state.adaptive;
        if (!adaptive || !adaptive.enabled || !adaptive.available || !adaptive.active || adaptive.currentBucket < 0 || adaptive.currentBucket > 3)
            return;
        const buckets = adaptive.buckets || [];
        if (!buckets[adaptive.currentBucket])
            return;
        const targets = Object.assign({}, buckets[adaptive.currentBucket].targets || {});
        targets[row.id] = row.level;
        buckets[adaptive.currentBucket] = Object.assign({}, buckets[adaptive.currentBucket], {
            targets: targets
        });
        adaptive.buckets = buckets;
    }

    function applyAdaptiveTargets(state, bucket) {
        const targets = ((state.adaptive.buckets || [])[bucket] || {}).targets || {};
        state.displays = state.displays.map(row => row.controllable && typeof targets[row.id] === "number" ? Object.assign({}, row, {
                level: targets[row.id]
            }) : row);
        updateGlobal(state);
    }

    // Suite surface: synthetic boundary changes, never native setup or hardware access.
    // A full state replaces the base display; null restores it.
    function setState(state) {
        snapshotOverride = state;
    }

    // An external writer changes the base display's level.
    function externalUpdate() {
        level = 0.25;
    }

    function setAvailable(value) {
        available = !!value;
    }

    // Setup reaches `stage` with its predecessors done; "ready" completes it.
    function advanceSetup(stage) {
        fixtureEvent(String(stage));
    }

    // The ambient sensor reports `bucket` (0 dark … 3 sunlight).
    function setAmbient(bucket) {
        fixtureEvent("ambient:" + bucket);
    }

    function setSensorAvailable(value) {
        fixtureEvent(value ? "sensor-available" : "sensor-unavailable");
    }

    function setDdcReady(value) {
        fixtureEvent(value ? "ddc-ready" : "ddc-not-ready");
    }

    // `features.brightness.service`: the state the panel reads plus intent counters.
    function fixtureState() {
        return Object.assign({}, stateObject(), {
            "level": level,
            "writes": writes,
            "setups": setups,
            "cancellations": cancellations,
            "retries": retries,
            "lastDisplay": lastDisplay,
            "sensorMonitoring": !!ambientLightService && ambientLightService.monitoring
        });
    }

    function fixtureEvent(event) {
        const state = copyState();
        if (!state)
            return;
        const setup = state.setup || {};
        if (event === "ready") {
            setup.stages = (setup.stages || []).map(stage => ({
                        id: stage.id,
                        status: "done",
                        error: ""
                    }));
            setup.ready = true;
            setup.needed = false;
            setup.expanded = false;
            setup.running = false;
            setup.error = "";
            state.setup = setup;
            state.displays = state.displays.map(row => Object.assign({}, row, {
                    controllable: true,
                    level: 0.5,
                    issue: ""
                }));
            updateGlobal(state);
        } else if (event.startsWith("ambient:")) {
            const bucket = Number(event.slice("ambient:".length));
            if (state.adaptive && Number.isInteger(bucket) && bucket >= 0 && bucket < 4) {
                state.adaptive.currentBucket = bucket;
                state.adaptive.raw = [10, 50, 200, 500][bucket];
                state.adaptive.active = !!state.adaptive.enabled && !!state.adaptive.available;
                state.adaptive.error = "";
                if (state.adaptive.active)
                    applyAdaptiveTargets(state, bucket);
            }
        } else if (event === "sensor-unavailable" || event === "ddc-not-ready") {
            if (state.adaptive) {
                state.adaptive.available = false;
                state.adaptive.active = false;
            }
            if (event === "ddc-not-ready") {
                state.setup = Object.assign({}, setup, {
                    ready: false,
                    needed: true
                });
                state.displays = state.displays.map(row => Object.assign({}, row, {
                        controllable: false,
                        issue: "needs setup"
                    }));
                updateGlobal(state);
            }
        } else if (event === "sensor-available" || event === "ddc-ready") {
            if (state.adaptive) {
                state.adaptive.available = true;
                state.adaptive.active = !!state.adaptive.enabled && state.adaptive.currentBucket >= 0;
            }
            if (event === "ddc-ready")
                state.setup = Object.assign({}, setup, {
                    ready: true,
                    needed: false
                });
        } else {
            const index = (setup.stages || []).findIndex(stage => stage.id === event);
            setup.stages = (setup.stages || []).map((stage, i) => ({
                        id: stage.id,
                        status: i < index ? "done" : i === index ? "running" : "waiting",
                        error: ""
                    }));
            state.setup = setup;
        }
        snapshotOverride = state;
    }

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

    // The typed properties read this; callers never mutate it.
    function stateObject() {
        if (snapshotOverride)
            return snapshotOverride;
        return {
            global: {
                mode: available ? "synced" : "none",
                level: available ? level : 0,
                levels: available ? [level] : []
            },
            setup: {
                needed: false,
                available: false
            },
            displays: [
                {
                    id: "fixture-display",
                    name: "fixture display",
                    level: level,
                    controllable: available,
                    issue: available ? "" : "unavailable"
                }
            ]
        };
    }

    function setAll(value) {
        if (snapshotOverride) {
            const state = copyState();
            state.displays = state.displays.map(row => {
                const next = row.controllable ? Object.assign({}, row, {
                    level: value
                }) : row;
                if (next !== row)
                    learnAdaptive(state, next);
                return next;
            });
            updateGlobal(state);
            snapshotOverride = state;
            writes++;
            return stateJson();
        }
        if (available) {
            level = value;
            writes++;
        }
        return stateJson();
    }

    function setDisplay(id, value) {
        lastDisplay = id;
        if (!snapshotOverride)
            return setAll(value);
        const state = copyState();
        state.displays = state.displays.map(row => {
            const next = row.id === id && row.controllable ? Object.assign({}, row, {
                level: value
            }) : row;
            if (next !== row)
                learnAdaptive(state, next);
            return next;
        });
        updateGlobal(state);
        snapshotOverride = state;
        writes++;
        return stateJson();
    }

    function toggleAdaptive() {
        const state = copyState();
        if (!state || !state.adaptive || !state.adaptive.available)
            return stateJson();
        state.adaptive.enabled = !state.adaptive.enabled;
        state.adaptive.active = state.adaptive.enabled && state.adaptive.currentBucket >= 0;
        snapshotOverride = state;
        return stateJson();
    }

    function setAdaptiveThreshold(index, value) {
        const state = copyState();
        const adaptive = state && state.adaptive;
        if (!adaptive || !Number.isInteger(index) || index < 0 || index > 2 || !Number.isSafeInteger(value) || value <= 0)
            return adaptiveThresholds[index] === value;
        const thresholds = (adaptive.thresholds || []).slice();
        if (thresholds.length !== 3)
            return adaptiveThresholds[index] === value;
        const minimum = index === 0 ? 1 : thresholds[index - 1] + 1;
        const maximum = index === 2 ? Number.MAX_SAFE_INTEGER : thresholds[index + 1] - 1;
        thresholds[index] = Math.max(minimum, Math.min(maximum, value));
        adaptive.thresholds = thresholds;
        snapshotOverride = state;
        return thresholds[index] === value;
    }

    function setupDdc() {
        if (!snapshotOverride || snapshotOverride.setup.running)
            return stateJson();
        setups++;
        const state = copyState();
        state.setup.expanded = true;
        state.setup.running = true;
        state.setup.error = "";
        state.setup.cancelRequested = false;
        state.setup.privilegedEntered = false;
        snapshotOverride = state;
        fixtureEvent("preflight");
        return stateJson();
    }

    function cancelSetup() {
        if (!setupRunning || cancelRequested)
            return stateJson();
        cancellations++;
        const state = copyState();
        if (state.setup.privilegedEntered) {
            state.setup.cancelRequested = true;
            state.setup.error = "cancel requested; waiting for package setup";
            snapshotOverride = state;
            return stateJson();
        }
        return finishCancellation();
    }

    function finishCancellation() {
        const state = copyState();
        state.setup.running = false;
        state.setup.error = "cancelled";
        state.setup.stages = state.setup.stages.map(stage => stage.status === "running" ? {
                id: stage.id,
                status: "failed",
                error: "cancelled"
            } : stage);
        snapshotOverride = state;
        return stateJson();
    }

    function retrySetup() {
        retries++;
        return setupDdc();
    }

    function toggleSetup() {
        const state = copyState();
        state.setup.expanded = !state.setup.expanded;
        snapshotOverride = state;
        return stateJson();
    }
}