Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/brightness.js

Raw
// brightness.js — pure brightness logic: levels, display rows, DDC commands and parsing, setup stages.
// NO I/O. Dual-mode: node `require` (tests) + QML import.

// --- clamp a level to 0..1, null/NaN-safe ---
function clampLevel(value) {
    var n = Number(value);
    if (!isFinite(n)) return 0;
    return n < 0 ? 0 : (n > 1 ? 1 : n);
}

// --- integer percent 0..100 for a level ---
function levelPercent(value) {
    return Math.round(clampLevel(value) * 100);
}

// --- compact/bar role color token by level band:
// dim (<=15%) -> ui.minor, bright (>=85%) -> warning, else ui.accent ---
function levelRole(value) {
    var v = clampLevel(value);
    if (v <= 0.15) return "ui.minor";
    if (v >= 0.85) return "warning";
    return "ui.accent";
}

function outputArray(outputs) {
    if (Array.isArray(outputs)) return outputs;
    var obj = outputs || {};
    return Object.keys(obj).map(function (name) {
        var row = obj[name] || {};
        var copy = {};
        Object.keys(row).forEach(function (key) { copy[key] = row[key]; });
        copy.name = copy.name || name;
        return copy;
    });
}

// A display reads by its model; the connector stays only when the model is
// unknown or repeats it, or to tell apart displays that share one model.
function displayName(output, outputs) {
    var name = String(output.name || "display");
    var model = String(output.model || "");
    if (model.length === 0 || model === "Unknown" || model.toLowerCase() === name.toLowerCase()) return name;
    var twins = (outputs || []).filter(function (other) { return String(other.model || "") === model; }).length;
    return twins > 1 ? name + " · " + model : model;
}

function displayRows(backlight, outputs, ddc) {
    var rows = [];
    var b = backlight || {};
    if (b.present) {
        rows.push({
            id: "backlight",
            name: "built-in",
            kind: "backlight",
            level: clampLevel(b.level),
            controllable: true,
            issue: diagnostic(b.error)
        });
    }

    var ddcMap = ddc || {};
    var outputList = outputArray(outputs);
    outputList.forEach(function (output) {
        var key = String(output.name || "");
        // Internal connectors use the backlight row, never DDC setup.
        if (key.length === 0 || /^(eDP|LVDS|DSI)-[0-9]+$/.test(key)) return;
        var state = ddcMap[key] || {};
        var ok = !!state.controllable;
        rows.push({
            id: "ddc:" + key,
            name: displayName(output, outputList),
            kind: "ddc",
            level: ok ? clampLevel(state.level) : null,
            controllable: ok,
            issue: state.error || (ok ? "" : "needs setup")
        });
    });
    return rows;
}

function globalState(rows) {
    var levels = (rows || []).filter(function (row) {
        return !!row.controllable;
    }).map(function (row) {
        return Math.round(clampLevel(row.level) * 100) / 100;
    });
    if (levels.length === 0) return { mode: "none", level: 0, levels: [] };

    var first = levels[0];
    var mixed = levels.some(function (level) { return level !== first; });
    if (!mixed) return { mode: "synced", level: first, levels: levels };

    var sum = levels.reduce(function (a, b) { return a + b; }, 0);
    return { mode: "mixed", level: Math.round(sum / levels.length * 100) / 100, levels: levels };
}

// Fixed scripts only: never interpolate connector names, diagnostics or user input.
function preflightCommand() {
    return timedCommand(5, ["/usr/bin/sh", "-c", [
        "if /usr/bin/pacman -Qq ddcutil >/dev/null 2>&1; then echo package=yes; else echo package=no; fi",
        "if test -d /sys/module/i2c_dev; then echo module=yes; else echo module=no; fi",
        "for d in /sys/class/drm/card*-*; do",
        "test -f \"$d/status\" || continue",
        "test \"$(/usr/bin/cat \"$d/status\")\" = connected || continue",
        "b=$(/usr/bin/readlink -f \"$d/ddc\"); b=${b##*/i2c-}",
        "case $b in ''|*[!0-9]*) continue;; esac",
        "n=${d##*/}; n=${n#card*-}; a=no",
        "case $n in eDP-*|LVDS-*|DSI-*) continue;; esac",
        "if test -r /dev/i2c-\"$b\" && test -w /dev/i2c-\"$b\"; then a=yes; fi",
        "printf 'connector=%s,%s,%s\\n' \"$n\" \"$b\" \"$a\"",
        "done"
    ].join("\n")]);
}

function parsePreflight(text) {
    var result = { installed: false, module: false, connectors: {} };
    String(text).split(/\r?\n/).forEach(function (line) {
        if (line === "package=yes") result.installed = true;
        if (line === "module=yes") result.module = true;
        var m = /^connector=([A-Za-z0-9-]+),(\d+),(yes|no)$/.exec(line);
        if (m) result.connectors[m[1]] = { bus: Number(m[2]), accessible: m[3] === "yes" };
    });
    result.needsPrivilege = !result.installed || !result.module || Object.keys(result.connectors).some(function (name) {
        return !result.connectors[name].accessible;
    });
    return result;
}

function privilegedCommand(install) {
    // Arch ddcutil owns modules-load.d/ddcutil.conf + 60-ddcutil-i2c.rules.
    // Activate those package-owned rules for this session; never duplicate them.
    // Cancellation during a package transaction is deferred until this tracked
    // process exits. Pacman receives INT at its deadline to clean up normally;
    // never SIGKILL a package transaction or remove its lock.
    // Two-phase authorization: root payload cannot mutate until the service
    // acknowledges the marker. A cancelled/expired request can never install.
    var script = "set -e\nprintf 'nugu:authorized\\n'\n/usr/bin/timeout --kill-after=2s 5s /usr/bin/sh -c 'read -r consent; test \"$consent\" = continue'\n";
    if (install) script += "/usr/bin/timeout --signal=INT 300s /usr/bin/pacman -S --needed --noconfirm ddcutil\n";
    script += "printf 'nugu:package-done\\n'\n";
    script += "/usr/bin/timeout --kill-after=2s 15s /usr/bin/udevadm control --reload\n";
    script += "/usr/bin/timeout --kill-after=2s 15s /usr/bin/modprobe i2c-dev\n";
    script += "/usr/bin/timeout --kill-after=2s 15s /usr/bin/udevadm trigger --action=change --subsystem-match=i2c-dev\n";
    script += "/usr/bin/udevadm settle --timeout=15\n";
    return ["/usr/bin/pkexec", "--disable-internal-agent", "/usr/bin/sh", "-c", script];
}

function timedCommand(seconds, args) {
    return ["/usr/bin/timeout", "--kill-after=2s", String(seconds) + "s"].concat(args);
}

function ddcCommand(kind, bus, level, maximum) {
    var args = ["/usr/bin/ddcutil", "--noconfig"];
    if (kind === "detect") return timedCommand(20, args.concat(["detect", "--verbose"]));
    if (!Number.isInteger(Number(bus)) || Number(bus) < 0 || Number(bus) > 65535) return [];
    args = args.concat(["--bus", String(Number(bus))]);
    if (kind === "read") return timedCommand(8, args.concat(["getvcp", "10", "--terse"]));
    if (kind === "write" && Number(maximum) > 0)
        return timedCommand(8, args.concat(["setvcp", "10", String(Math.round(clampLevel(level) * Number(maximum))), "--verify"]));
    return [];
}

function parseDetection(text, connectors) {
    var displays = [];
    var current = {};
    String(text).split(/\r?\n/).forEach(function (line) {
        if (/^\s*(?:Invalid display|Display\s+\d+)/.test(line)) {
            displays.push(current);
            current = {};
        }
        var bus = /I2C bus:\s*\/dev\/i2c-(\d+)/.exec(line);
        if (bus) current.bus = Number(bus[1]);
        var connector = /^\s*DRM[_ ]connector:\s*(?:\/[^\s]*\/)?card\d+-([A-Za-z0-9-]+)/.exec(line);
        if (connector) current.connector = connector[1];
    });
    displays.push(current);

    var connected = connectors || {};
    var result = {};
    displays.forEach(function (display) {
        if (!Number.isInteger(display.bus) || display.bus < 0 || display.bus > 65535) return;
        // ddcutil resolves DisplayPort AUX buses that can differ from sysfs ddc
        // links. Connector identity, not monitor model or detection order, wins.
        if (display.connector && Object.prototype.hasOwnProperty.call(connected, display.connector))
            result[display.connector] = { bus: display.bus, controllable: false, error: "" };
    });
    Object.keys(connected).forEach(function (name) {
        if (result[name]) return;
        var bus = connected[name].bus;
        if (!Number.isInteger(bus) || bus < 0 || bus > 65535) return;
        // Older output without connector identity can still use an exact sysfs
        // bus match. Never override an explicit different connector identity.
        if (displays.some(function (display) { return !display.connector && display.bus === bus; }))
            result[name] = { bus: bus, controllable: false, error: "" };
    });
    return result;
}

function parseBrightness(text) {
    var m = /^VCP\s+10\s+C\s+(\d+)\s+(\d+)\s*$/im.exec(String(text));
    if (!m || Number(m[2]) <= 0 || Number(m[1]) > Number(m[2])) return null;
    return { level: Number(m[1]) / Number(m[2]), maximum: Number(m[2]) };
}

function initialStages() {
    return ["preflight", "authorization", "installation", "detection", "reading", "verification", "ready"].map(function (id) {
        return { id: id, status: "waiting", error: "" };
    });
}

// Setup stages in the words of what each does.
var stageLabels = {
    preflight: "check system",
    authorization: "allow access",
    installation: "install ddcutil",
    detection: "find monitors",
    reading: "read brightness",
    verification: "confirm control",
    ready: "monitor control"
};

function stageLabel(id) {
    return stageLabels[id] || String(id);
}

// A stage the user stopped is cancelled, never failed.
function stageStatus(stage) {
    return stage.status === "failed" && stage.error === "cancelled" ? "cancelled" : String(stage.status);
}

// One expanded stage: "find monitors · failed · timeout", "find monitors · cancelled".
function stageLine(stage) {
    var status = stageStatus(stage);
    return stageLabel(stage.id) + " · " + status + (status === "failed" && stage.error ? " · " + stage.error : "");
}

// Collapsed setup in one line: the running step and its place, else the stage
// that stopped setup with its details. `detail` is the diagnostic it already says.
function setupSummary(stages, running, error) {
    var list = stages || [];
    var index = function (status) {
        for (var i = 0; i < list.length; i++)
            if (list[i].status === status) return i;
        return -1;
    };
    var step = function (i) {
        return { status: list[i].status, text: "step " + (i + 1) + " of " + list.length + " · " + stageLabel(list[i].id), detail: "" };
    };
    if (running && index("running") >= 0) return step(index("running"));
    var failed = index("failed");
    if (failed >= 0) {
        var stage = list[failed];
        var status = stageStatus(stage);
        var detail = status === "failed" ? String(stage.error || "") : "cancelled";
        return { status: status, text: stageLabel(stage.id) + " " + status + (status === "failed" && detail ? " · " + detail : ""), detail: detail };
    }
    if (!running && error) {
        var cancelled = error === "cancelled";
        return { status: cancelled ? "cancelled" : "failed", text: cancelled ? "setup cancelled" : "setup failed · " + error, detail: String(error) };
    }
    if (index("waiting") >= 0) return step(index("waiting"));
    return { status: "done", text: "monitor control ready", detail: "" };
}

function stageState(stages, id, status, error) {
    return stages.map(function (stage) {
        return stage.id === id ? { id: id, status: status, error: diagnostic(error) } : stage;
    });
}

// No raw subprocess text crosses the service boundary. Only known diagnostic codes.
function diagnostic(value) {
    var allowed = ["cancelled", "cancel requested; waiting for package setup", "timeout", "start failed", "authorization unavailable", "authorization busy", "authorization denied", "installation failed", "preflight failed", "detection failed", "no mapped displays", "read failed", "some displays unavailable", "write failed", "display unavailable"];
    return allowed.indexOf(String(value)) >= 0 ? String(value) : "";
}

function processError(code, fallback) {
    return Number(code) === 124 || Number(code) === 137 ? "timeout" : diagnostic(fallback);
}

if (typeof module !== 'undefined' && module.exports) {
    module.exports = { clampLevel: clampLevel, levelPercent: levelPercent,
        levelRole: levelRole, displayRows: displayRows, globalState: globalState,
        preflightCommand: preflightCommand, parsePreflight: parsePreflight,
        privilegedCommand: privilegedCommand, timedCommand: timedCommand,
        ddcCommand: ddcCommand, parseDetection: parseDetection, parseBrightness: parseBrightness,
        initialStages: initialStages, stageState: stageState, stageLabel: stageLabel, stageStatus: stageStatus,
        stageLine: stageLine, setupSummary: setupSummary, diagnostic: diagnostic, processError: processError };
}