Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/brightness-panel.test.mjs

Raw
import assert from "node:assert/strict";
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { assertOffscreenPass, runOffscreen } from "../../test-fixtures/offscreen.mjs";

// Real production panel/control objects run offscreen. The copied typed fixture
// records rejected intents without any native brightness, authorization, or I/O.
const directory = mkdtempSync(join(tmpdir(), "nuguland-brightness-panel-"));
try {
    // Shared controls at the shell root, the panel and its double in the feature directory.
    for (const file of [
        "PopupSlider.qml", "PopupButton.qml", "PopupCard.qml",
        "PopupToolTip.qml", "PopupTextField.qml", "NuguText.qml", "StableListModel.qml", "Theme.qml", "nugu.json", "Util.js"
    ])
        copyFileSync(new URL("../../" + file, import.meta.url), join(directory, file));
    const feature = join(directory, "features", "brightness");
    mkdirSync(feature, { recursive: true });
    for (const file of ["BrightnessPanel.qml", "brightness.js"])
        copyFileSync(new URL(file, import.meta.url), join(feature, file));

    let brightnessFixture = readFileSync(new URL("fixtures/services/Brightness.qml", import.meta.url), "utf8");
    for (const [from, to] of [
        ["    property string lastDisplay: \"\"", "    property string lastDisplay: \"\"\n    property real lastAll: -1\n    property real lastDisplayValue: -1\n    property bool failWrites: false"],
        ["    function setAll(value) {\n        if (snapshotOverride) {", "    function setAll(value) {\n        lastAll = value;\n        if (failWrites)\n            return stateJson();\n        if (snapshotOverride) {"],
        ["    function setDisplay(id, value) {\n        lastDisplay = id;", "    function setDisplay(id, value) {\n        lastDisplay = id;\n        lastDisplayValue = value;\n        if (failWrites)\n            return stateJson();"]
    ]) {
        assert.equal(brightnessFixture.split(from).length, 2, "missing or ambiguous fixture substitution: " + from);
        brightnessFixture = brightnessFixture.replace(from, to);
    }
    writeFileSync(join(feature, "Brightness.qml"), brightnessFixture);
    writeFileSync(join(directory, "shell.qml"), `import QtQuick
import QtQuick.Window
import Quickshell
import "features/brightness"

ShellRoot {
    id: test

    property int phase: 0

    function fail(message) {
        console.error("ERROR brightness panel phase " + phase + ": " + message);
        Qt.quit();
    }

    function check(condition, message) {
        if (!condition)
            fail(message);
        return condition;
    }

    function tree(item) {
        let result = [item];
        for (const child of item.children || [])
            result = result.concat(tree(child));
        return result;
    }

    function effectivelyVisible(item) {
        for (let current = item; current; current = current.parent) {
            if (current.visible === false)
                return false;
        }
        return true;
    }

    function panelSliders() {
        return tree(panel).filter(child => child.levels !== undefined
            && child.displayedValue !== undefined && child.boundedValue !== undefined);
    }

    function slider(name) {
        return panelSliders().find(child => child.Accessible.name === name) || null;
    }

    function visibleText(item) {
        return tree(item).filter(child => effectivelyVisible(child) && child.font !== undefined
            && child.text !== undefined).map(child => String(child.text));
    }

    function accentFillCount(item) {
        return tree(item).filter(child => effectivelyVisible(child) && child.color !== undefined
            && String(child.color).toLowerCase() === String(theme.ui.accent).toLowerCase()).length;
    }

    function snapshot(displays, global) {
        return {
            global: global,
            setup: { needed: false, available: false, running: false, expanded: false, ready: false },
            displays: displays
        };
    }

    Theme { id: theme }
    Brightness {
        id: brightness
        snapshotOverride: ({
            global: { mode: "none", level: 0, levels: [] },
            setup: { needed: false, available: false, running: false, expanded: false, ready: false },
            displays: []
        })
    }

    Window {
        visible: true
        width: 480
        height: 360
        color: "transparent"

        BrightnessPanel {
            id: panel
            anchors.fill: parent
            theme: theme
            brightnessService: brightness
        }

        PopupSlider {
            id: ordinarySlider
            objectName: "ordinary-slider"
            x: 20
            y: 320
            width: 180
            theme: theme
            accessibleName: "ordinary brightness"
            value: 0.6
        }
    }

    Timer {
        interval: 15
        running: true
        repeat: true
        onTriggered: {
            if (test.phase === 0) {
                brightness.snapshotOverride = test.snapshot([
                    { id: "DP-1", name: "unresolved one", level: 0, controllable: false, issue: "unavailable" },
                    { id: "DP-2", name: "unresolved two", level: 0, controllable: false, issue: "unavailable" }
                ], { mode: "none", level: 0, levels: [] });
                test.phase = 1;
            } else if (test.phase === 1) {
                const sliders = test.panelSliders();
                test.check(test.slider("all displays brightness") !== null, "global slider missing");
                test.check(sliders.every(item => !test.effectivelyVisible(item)), "uncontrollable rows expose a visible slider");
                const unresolved = sliders.filter(item => item.Accessible.name !== "all displays brightness");
                test.check(unresolved.length === 2 && unresolved.every(item => !item.enabled), "uncontrollable display sliders enabled");
                test.check(test.visibleText(panel).every(value => !/\\d+%/.test(value)), "uncontrollable rows invented percentages");
                panel.setAllAt(1);
                test.check(brightness.lastAll === -1, "global intent sent without a global control");
                brightness.snapshotOverride = test.snapshot([
                    { id: "DP-1", name: "first display", level: 0.25, controllable: true, issue: "" },
                    { id: "DP-2", name: "second display", level: 0.75, controllable: true, issue: "" }
                ], { mode: "mixed", level: 0.5, levels: [0.25, 0.75] });
                test.phase = 2;
            } else if (test.phase === 2) {
                const globalSlider = test.slider("all displays brightness");
                test.check(test.effectivelyVisible(globalSlider), "mixed global slider hidden");
                test.check(globalSlider.levels.length === 2 && globalSlider.levels[0] === 0.25 && globalSlider.levels[1] === 0.75, "mixed levels not forwarded");
                test.check(test.accentFillCount(globalSlider) === 2, "mixed slider did not render confirmed level fills");
                const presets = [
                    ["25%", "󰃝"], ["50%", "󰃞"], ["75%", "󰃟"], ["100%", "󰃠"]
                ];
                for (const [percent, icon] of presets) {
                    const preset = test.tree(panel).find(child => child.text === percent && child.levelIcon === icon) || null;
                    test.check(preset !== null, "missing " + percent + " icon preset");
                    test.check(preset.accessibleName === "all displays brightness " + percent, "wrong preset accessible name " + percent);
                    // Manual presets carry the same icon-over-label look as the adaptive buckets.
                    test.check(test.visibleText(preset).includes(percent) && test.visibleText(preset).includes(icon), "preset lacks its icon and label " + percent);
                }
                brightness.snapshotOverride = test.snapshot([
                    { id: "DP-1", name: "first display", level: 0.5, controllable: true, issue: "" },
                    { id: "DP-2", name: "second display", level: 0.5, controllable: true, issue: "" }
                ], { mode: "synced", level: 0.5, levels: [0.5, 0.5] });
                test.phase = 3;
            } else if (test.phase === 3) {
                const globalSlider = test.slider("all displays brightness");
                test.check(globalSlider.levels.length === 0 && test.accentFillCount(globalSlider) === 1, "synced global slider lacks one normal fill");
                test.check(ordinarySlider.levels.length === 0 && test.accentFillCount(ordinarySlider) === 1 && ordinarySlider.displayedValue === 0.6, "ordinary slider behavior changed");
                brightness.snapshotOverride = test.snapshot([
                    { id: "DP-1", name: "first display", level: 0.25, controllable: true, issue: "" },
                    { id: "DP-2", name: "second display", level: 0.75, controllable: true, issue: "" }
                ], { mode: "mixed", level: 0.5, levels: [0.25, 0.75] });
                brightness.failWrites = true;
                test.phase = 4;
            } else if (test.phase === 4) {
                const globalSlider = test.slider("all displays brightness");
                const displaySlider = test.slider("first display brightness");
                const before = JSON.stringify(brightness.snapshotOverride);
                globalSlider.moved(0.8);
                test.check(brightness.lastAll === 0.8, "global moved did not send absolute intent");
                test.check(JSON.stringify(brightness.snapshotOverride) === before, "failed global write changed confirmed levels");
                displaySlider.moved(0.9);
                test.check(brightness.lastDisplay === "DP-1" && brightness.lastDisplayValue === 0.9, "display moved did not send absolute intent");
                test.check(JSON.stringify(brightness.snapshotOverride) === before, "failed display write changed confirmed levels");
                panel.setAllAt(2);
                panel.setDisplayAt("DP-2", -1);
                test.check(brightness.lastAll === 1 && brightness.lastDisplay === "DP-2" && brightness.lastDisplayValue === 0, "intents not bounded to 0..1");
                test.check(panel.initialFocus === globalSlider, "two controllable displays do not focus the all-displays slider");
                brightness.failWrites = false;
                brightness.snapshotOverride = test.snapshot([
                    { id: "DP-1", name: "only display", level: 0.5, controllable: true, issue: "" },
                    { id: "DP-2", name: "unresolved display", level: 0, controllable: false, issue: "needs setup" }
                ], { mode: "synced", level: 0.5, levels: [0.5] });
                test.phase = 5;
            } else if (test.phase === 5) {
                // One controllable display: its own slider and the presets, no all-displays slider.
                const only = test.slider("only display brightness");
                test.check(!test.effectivelyVisible(test.slider("all displays brightness")), "one controllable display shows an all-displays slider");
                test.check(test.effectivelyVisible(only) && panel.initialFocus === only, "one controllable display does not focus its own slider");
                const preset = test.tree(panel).find(child => child.text === "50%" && child.levelIcon !== undefined) || null;
                test.check(preset !== null && test.effectivelyVisible(preset) && preset.accessibleName === "brightness 50%", "one display preset missing or named for all displays");
                console.log("brightness panel qml: PASS");
                Qt.quit();
            }
        }
    }

    Timer {
        interval: 4000
        running: true
        onTriggered: {
            console.error("ERROR brightness panel deadline phase " + test.phase);
            Qt.quit();
        }
    }
}
`);

    const run = runOffscreen(join(directory, "shell.qml"), { directory, cwd: directory, timeout: 8000 });
    assertOffscreenPass(run, /brightness panel qml: PASS/);
    console.log(run.output.trim());
    console.log("brightness-panel.test.mjs: PASS (offscreen load/properties/programmatic signals; not pointer, keyboard, or pixel proof)");
} finally {
    rmSync(directory, { recursive: true, force: true });
}