repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nuguland/Launcher.qml

Raw
import QtQuick
import Quickshell
import "launch.js" as Launch

Item {
    id: root

    property QtObject niriService
    property QtObject clipboardService
    property var launchRecords: []
    property var lastInteraction: ({
    })
    readonly property var actions: [{
        "id": "lock",
        "title": "Lock",
        "subtitle": "Lock this session",
        "route": "service"
    }, {
        "id": "overview",
        "title": "Overview",
        "subtitle": "Open niri overview",
        "route": "service"
    }, {
        "id": "screenshot",
        "title": "Screenshot",
        "subtitle": "Capture with native niri screenshot",
        "route": "service"
    }, {
        "id": "color",
        "title": "Pick color",
        "subtitle": "Use native niri color picker",
        "route": "service"
    }]
    // Apps come straight from Quickshell's native DesktopEntries singleton, which
    // already parses XDG desktop files, drops Hidden/NoDisplay, and dedupes by id.
    // The binding re-evaluates when the entry set changes. Mapping lives in launch.js.
    readonly property var apps: Launch.buildApps(DesktopEntries.applications ? DesktopEntries.applications.values : [])
    readonly property bool appScanDone: true
    readonly property string appScanError: ""

    // IPC serializer (launcherState). Telemetry essentials only — all narration
    // fields were removed with the launcher redesign.
    function stateJson() {
        return JSON.stringify({
            "launchRecords": launchRecords,
            "lastInteraction": lastInteraction,
            "appCount": apps.length,
            "appScanDone": appScanDone,
            "appScanError": appScanError
        });
    }

    // Telemetry-ONLY: records activations; does NOT feed scoring (ranking is a
    // pure function of query + static per-provider boost in launch.js).
    function rememberActivation(record, executed) {
        const entry = {
            "kind": "activate",
            "record": record,
            "executed": !!executed
        };
        const rows = launchRecords.slice(Math.max(0, launchRecords.length - 19));
        rows.push(record);
        launchRecords = rows;
        lastInteraction = entry;
        return stateJson();
    }

    function rowFromJson(rowJson) {
        if (typeof rowJson === "string") {
            try {
                return JSON.parse(rowJson);
            } catch (error) {
                return {
                    "id": "invalid",
                    "title": "Invalid launcher row",
                    "provider": "error",
                    "error": String(error)
                };
            }
        }
        return rowJson || ({
        });
    }

    function sliceForRow(row) {
        if (row.provider === "app")
            return row.terminal ? "work.slice" : "app-graphical.slice";

        return "session-graphical.slice";
    }

    function launchRecord(rowJson) {
        const row = rowFromJson(rowJson);
        const provider = String(row.provider || row.route || "item");
        const title = String(row.title || row.id || provider);
        const id = String(row.id || row.desktopId || title);
        const argv = provider === "calculator" ? ["wl-copy", String(row.value || row.title || "")] : (provider === "app" ? (row.execArgv || []) : (provider === "clipboard" ? ["wl-copy", String(row.body || row.title || "")] : (provider === "action" ? ["nuguland-action", id] : (provider === "window" ? ["niri", "msg", "action", "focus-window", "--id", String(row.windowId || row.id)] : []))));
        return JSON.stringify({
            "id": id,
            "label": title,
            "kind": provider === "app" ? "app" : provider,
            "provider": provider,
            "desktopId": row.desktopId || "",
            "desktopPath": row.desktopPath || "",
            "argv": argv,
            "workingDirectory": "",
            "environment": {
            },
            "slice": sliceForRow(row),
            "startupNotify": provider === "app",
            "windowMatching": {
                "desktopId": row.desktopId || "",
                "title": title,
                "appId": row.desktopId ? String(row.desktopId).replace(/\.desktop$/, "") : ""
            },
            "osdFeedback": `${provider}:${title}`,
            "route": row.route || provider,
            "terminal": !!row.terminal
        });
    }

    function runAction(id) {
        const name = String(id);
        if (name === "overview" && niriService)
            niriService.action(["toggle-overview"]);

        if (name === "screenshot" && niriService)
            niriService.screenshot(Quickshell.env("XDG_RUNTIME_DIR") + "/nuguland-launcher-screenshot.png");

        if (name === "color" && niriService)
            niriService.pickColor();

        return name === "overview" || name === "screenshot" || name === "color";
    }

    function activate(rowJson) {
        const row = rowFromJson(rowJson);
        const record = JSON.parse(launchRecord(row));
        if (record.kind === "calculator" || record.kind === "clipboard") {
            Quickshell.execDetached(record.argv);
            return rememberActivation(record, true);
        }
        if (record.kind === "action")
            return rememberActivation(record, runAction(record.id));

        if (record.kind === "window" && niriService) {
            niriService.action(["focus-window", "--id", String(row.windowId || row.id)]);
            return rememberActivation(record, true);
        }
        if (record.kind === "app" && record.argv.length > 0) {
            const selector = record.slice === "work.slice" ? "w" : "a";
            Quickshell.execDetached(["uwsm", "app", "-s", selector].concat(record.desktopPath ? [record.desktopPath] : record.argv));
            return rememberActivation(record, true);
        }
        return rememberActivation(record, false);
    }

    function activateFirst(query) {
        const result = JSON.parse(search(query));
        if (!result.results || result.results.length === 0) {
            lastInteraction = {
                "kind": "activate-empty",
                "query": String(query)
            };
            return stateJson();
        }
        return activate(JSON.stringify(result.results[0]));
    }

    function rowById(id) {
        const wanted = String(id);
        for (let i = 0; i < actions.length; i++) {
            if (actions[i].id === wanted)
                return Launch.shapeRow(actions[i], "action", 1500);

        }
        for (let i = 0; i < apps.length; i++) {
            if (apps[i].id === wanted || apps[i].desktopId === wanted)
                return Launch.shapeRow(Object.assign({
                "route": "desktop-entry"
            }, apps[i]), "app", 1500);

        }
        return null;
    }

    function activateId(id) {
        const row = rowById(id);
        if (!row) {
            lastInteraction = {
                "kind": "activate-missing-id",
                "id": String(id)
            };
            return stateJson();
        }
        return activate(JSON.stringify(row));
    }

    function hotkey(id) {
        const name = String(id);
        let record = {
            "id": name,
            "label": name,
            "kind": "hotkey",
            "provider": "hotkey",
            "argv": ["nuguctl", "hotkey", name],
            "slice": "session-graphical.slice",
            "osdFeedback": name
        };
        if (name === "open-launcher")
            record.argv = ["qs", "ipc", "-c", "nuguland", "call", "nuguland", "openLauncher"];

        lastInteraction = {
            "kind": "hotkey",
            "record": record
        };
        return JSON.stringify(lastInteraction);
    }

    // Clipboard rows come from the clipboard service as a JSON string; the service
    // does its own query filtering. Empty list on missing service / parse failure.
    function clipboardProviderRows(query) {
        if (!clipboardService)
            return [];

        try {
            return JSON.parse(clipboardService.launcherRows(query));
        } catch (error) {
            return [];
        }
    }

    // Thin wrapper over launch.rankResults: gather the live source bundles (apps,
    // actions, niri windows, clipboard rows) and delegate all parsing/scoring/sort
    // to the pure ranking core. Returns {query, providerIntent, selectedIndex, results}.
    function search(raw) {
        const intent = Launch.prefixIntent(raw);
        const windows = niriService ? (niriService.windows || []) : [];
        const clipRows = (intent.intent === "clipboard" || intent.intent === "all") ? clipboardProviderRows(intent.query) : [];
        const ranked = Launch.rankResults(raw, {
            "apps": apps,
            "actions": actions,
            "windows": windows,
            "clipRows": clipRows
        });
        return JSON.stringify({
            "query": raw,
            "providerIntent": ranked.providerIntent,
            "selectedIndex": ranked.selectedIndex,
            "results": ranked.results
        });
    }

    // Gate test: exercises the pure launch.js logic through QML so a stale qmlcache
    // or a broken import surfaces as failing cases. Mirrors Clipboard.qml selfTest.
    function selfTest() {
        const cases = [];
        function ok(name, cond) {
            cases.push({
                "name": name,
                "pass": !!cond
            });
        }
        try {
            ok("prefix-calculator", Launch.prefixIntent("=2+2").intent === "calculator");
            ok("prefix-action", Launch.prefixIntent("> over").intent === "action");
            ok("prefix-clipboard", Launch.prefixIntent("clip foo").intent === "clipboard" && Launch.prefixIntent("clip foo").query === "foo");
            ok("prefix-all", Launch.prefixIntent("firefox").intent === "all");
            const exact = Launch.fuzzyScore("firefox", "firefox", 0);
            const prefix = Launch.fuzzyScore("fire", "firefox", 0);
            const subseq = Launch.fuzzyScore("frfx", "firefox", 0);
            ok("fuzzy-order", exact > prefix && prefix > subseq && subseq >= 0);
            ok("fuzzy-miss", Launch.fuzzyScore("zzz", "firefox", 0) === -1);
            ok("calc-eval", Launch.calculatorValue("2+2") === "4");
            ok("calc-reject-call", Launch.calculatorValue("a()") === null);
            ok("calc-reject-assign", Launch.calculatorValue("x=1") === null);
            const rApp = Launch.rankResults("firefox", {
                "apps": [{
                    "title": "Files",
                    "id": "app:files"
                }, {
                    "title": "Firefox",
                    "id": "app:ff",
                    "icon": "firefox"
                }]
            });
            ok("rank-exact-first", rApp.selectedIndex === 0 && rApp.results[0].title === "Firefox");
            ok("rank-keeps-icon", rApp.results[0].icon === "firefox");
            const rAction = Launch.rankResults("> over", {
                "actions": [{
                    "title": "Overview",
                    "id": "overview"
                }],
                "apps": [{
                    "title": "Overx",
                    "id": "app:x"
                }]
            });
            ok("rank-action-intent", rAction.providerIntent === "action" && rAction.results[0].provider === "action");
            const rClip = Launch.rankResults("clip ", {
                "clipRows": [{
                    "title": "snippet",
                    "id": "clip-1"
                }]
            });
            ok("rank-clip-intent", rClip.providerIntent === "clipboard" && rClip.results[0].provider === "clipboard");
            const rCalc = Launch.rankResults("=2*21", {});
            ok("rank-calc-row", rCalc.calc !== null && rCalc.calc.value === "42" && rCalc.results[0].title === "42");
        } catch (error) {
            ok("threw:" + error, false);
        }
        const fail = cases.filter((c) => {
            return !c.pass;
        }).length;
        return JSON.stringify({
            "pass": cases.length - fail,
            "fail": fail,
            "cases": cases
        });
    }

}