repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

quickshell/nuguland/Launcher.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Io

Item {
    id: root

    property QtObject niriService
    property QtObject clipboardService
    property var wheelTrace: []
    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"
    }]
    property var apps: []
    property bool appScanDone: false
    property string appScanError: ""

    function normalize(text) {
        return String(text || "").trim().toLowerCase();
    }

    function prefixIntent(raw) {
        const text = String(raw || "").trim();
        if (text.startsWith("="))
            return {
            "provider": "calculator",
            "query": text.slice(1).trim()
        };

        if (text.startsWith(">"))
            return {
            "provider": "action",
            "query": text.slice(1).trim()
        };

        if (text.toLowerCase().startsWith("clip "))
            return {
            "provider": "clipboard",
            "query": text.slice(5).trim()
        };

        return {
            "provider": "all",
            "query": text
        };
    }

    function fuzzyScore(query, title, providerBoost) {
        const q = normalize(query);
        const t = normalize(title);
        if (q.length === 0)
            return providerBoost;

        if (t === q)
            return providerBoost + 1000;

        if (t.startsWith(q))
            return providerBoost + 800 - t.length;

        if (t.indexOf(q) >= 0)
            return providerBoost + 500 - t.indexOf(q);

        return -1;
    }

    function calculatorValue(expression) {
        const expr = String(expression || "").replace(/\s+/g, "");
        if (!/^[0-9.+\-*/()%]+$/.test(expr) || expr.length === 0)
            return "";

        try {
            const value = Function(`"use strict"; return (${expr})`)();
            if (typeof value !== "number" || !Number.isFinite(value))
                return "";

            return Number.isInteger(value) ? String(value) : String(Math.round(value * 10000) / 10000);
        } catch (error) {
            return "";
        }
    }

    function rowVerb(provider, row) {
        if (row.verb)
            return String(row.verb);

        if (provider === "calculator")
            return "copy-result";

        if (provider === "action")
            return "run-action";

        if (provider === "app")
            return "launch-app";

        if (provider === "clipboard")
            return "copy-clipboard";

        if (provider === "window")
            return "focus-window";

        return "activate";
    }

    function rowIconRole(provider, row) {
        if (row.iconRole)
            return String(row.iconRole);

        if (provider === "calculator")
            return "calculator";

        if (provider === "action")
            return "shell-action";

        if (provider === "app")
            return "desktop-entry";

        if (provider === "clipboard")
            return "clipboard";

        if (provider === "window")
            return "niri-window";

        return "item";
    }

    function previewActionRows(row) {
        const provider = String(row.provider || "item");
        const primaryLabel = provider === "calculator" ? "Copy result" : (provider === "app" ? "Launch" : (provider === "window" ? "Focus" : "Run"));
        return [{
            "id": "primary",
            "label": primaryLabel,
            "iconRole": row.iconRole || provider,
            "verb": row.verb || "activate",
            "primaryAction": true,
            "keyboardReturnActivates": true
        }, {
            "id": "copy-title",
            "label": "Copy title",
            "iconRole": "clipboard",
            "verb": "copy-title",
            "primaryAction": false,
            "keyboardReturnActivates": false
        }, {
            "id": "copy-subtitle",
            "label": "Copy detail",
            "iconRole": "clipboard",
            "verb": "copy-subtitle",
            "primaryAction": false,
            "keyboardReturnActivates": false
        }];
    }

    function recordWheelSelection(before, after, deltaY) {
        const entry = {
            "kind": "wheel-select",
            "before": before,
            "after": after,
            "deltaY": deltaY
        };
        const rows = wheelTrace.slice(Math.max(0, wheelTrace.length - 15));
        rows.push(entry);
        wheelTrace = rows;
        lastInteraction = entry;
        return stateJson();
    }

    function providerCounts() {
        return {
            "app": apps.length,
            "action": actions.length,
            "clipboard": clipboardProviderRows("").length,
            "window": niriService ? (niriService.windows || []).length : 0,
            "calculator": 1
        };
    }

    function stateJson() {
        return JSON.stringify({
            "backend": "Launcher.qml",
            "wheelTrace": wheelTrace,
            "launchRecords": launchRecords,
            "lastInteraction": lastInteraction,
            "realWheelSelection": lastInteraction.kind === "wheel-select" && lastInteraction.before !== lastInteraction.after,
            "launcherPanelContract": launcherPanelContract(),
            "appCount": apps.length,
            "appScanDone": appScanDone,
            "appScanError": appScanError,
            "desktopEntrySource": "xdg-data-dirs",
            "fakeApps": false,
            "providerCounts": providerCounts()
        });
    }

    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 shapeRow(actions[i], "action", 1500);

        }
        for (let i = 0; i < apps.length; i++) {
            if (apps[i].id === wanted || apps[i].desktopId === wanted)
                return 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);
    }

    function launcherPanelContract() {
        return {
            "source": "Nuguland launcher Content.qml AppList.qml ActionItem.qml plus Nuguland SearchResults.qml ResultPreview plus Nuguland LaunchContent.qml",
            "ownedBy": "PopoutHost.qml inline LauncherPanel",
            "fullLauncherSurface": true,
            "searchFieldDockedBottom": true,
            "singleResultList": true,
            "sidePreviewPanel": true,
            "keyboardNavigation": true,
            "providerChips": true,
            "serviceFedOnly": true,
            "noSettingsCenter": true,
            "resultParts": ["iconRole", "title", "subtitle", "verb", "tags"],
            "previewActions": ["primary", "copy-title", "copy-subtitle"]
        };
    }

    function launcherPreviewPanel(row) {
        if (!row)
            return {
            "source": "Nuguland SearchResults.qml ResultPreview plus Nuguland launcher Content.qml",
            "emptyState": true,
            "sidePanelWidth": 386,
            "actionRows": [],
            "keyboardReturnActivates": "primaryAction"
        };

        return {
            "source": "Nuguland SearchResults.qml ResultPreview plus Nuguland launcher Content.qml",
            "emptyState": false,
            "provider": row.provider,
            "title": row.title || row.id || row.provider,
            "subtitle": row.subtitle || row.provider,
            "iconRole": row.iconRole,
            "verb": row.verb,
            "preview": row.preview,
            "sidePanelWidth": 386,
            "selectedResultDrivesPreview": true,
            "primaryAction": row.verb,
            "keyboardReturnActivates": "primaryAction",
            "settingsBacked": false,
            "actionRows": previewActionRows(row)
        };
    }

    function shapeRow(row, provider, score) {
        const next = Object.assign({
        }, row);
        const route = next.route || provider;
        next.provider = provider;
        next.iconRole = rowIconRole(provider, next);
        next.verb = rowVerb(provider, next);
        next.subtitle = next.subtitle || provider;
        next.tags = next.tags || [provider, route, next.verb];
        next.preview = next.preview || {
            "provider": provider,
            "title": next.title || next.id || provider,
            "subtitle": next.subtitle,
            "route": route
        };
        next.score = score;
        next.keyboard = true;
        return next;
    }

    function pushResult(results, row, provider, score) {
        if (score < 0)
            return ;

        results.push(shapeRow(row, provider, score));
    }

    function scrollableListChrome(rowCount, selectedIndex) {
        const count = Math.max(0, Number(rowCount));
        const selected = Math.max(0, Number(selectedIndex));
        const scrollable = count > 4;
        return {
            "source": "Nuguland ScrollEdgeFade.qml plus Nuguland FlickMonitor.qml",
            "scrollEdgeFade": true,
            "topEdgeFade": scrollable && selected > 0,
            "bottomEdgeFade": scrollable && selected < count - 1,
            "fadeSize": 32,
            "scrollHint": {
                "visible": scrollable,
                "icon": "keyboard_arrow_up_down",
                "side": "right",
                "tooltip": "scroll results"
            },
            "flickMonitor": {
                "enabled": true,
                "velocitySamples": 6,
                "events": ["pressed", "positionChanged", "released"]
            }
        };
    }

    function clipboardProviderRows(query) {
        if (!clipboardService)
            return [];

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

    function windowRows(query, boost, results) {
        const windows = niriService ? (niriService.windows || []) : [];
        for (let i = 0; i < windows.length; i++) {
            const win = windows[i];
            const title = win.title || win.app_id || win.appId || `window ${win.id}`;
            const score = fuzzyScore(query, title, boost);
            pushResult(results, {
                "id": String(win.id),
                "title": title,
                "subtitle": win.app_id || win.appId || "window",
                "route": "niri-window",
                "windowId": win.id
            }, "window", score);
        }
    }

    function desktopScanCode() {
        return `import json, os, re, shlex\n\ndef truth(value):\n    return str(value or '').strip().lower() == 'true'\n\ndef clean_exec(value):\n    return re.sub(r' ?%[fFuUdDnNickvm]', '', value or '').strip()\n\ndef parse_desktop(path):\n    data = {}\n    section = ''\n    try:\n        text = open(path, 'r', encoding='utf-8', errors='replace').read().splitlines()\n    except OSError:\n        return None\n    for line in text:\n        line = line.strip()\n        if not line or line.startswith(('#', ';')):\n            continue\n        if line.startswith('[') and line.endswith(']'):\n            section = line[1:-1]\n            continue\n        if section != 'Desktop Entry' or '=' not in line:\n            continue\n        key, value = line.split('=', 1)\n        if '[' not in key and key not in data:\n            data[key] = value\n    if data.get('Type', 'Application') != 'Application':\n        return None\n    if truth(data.get('NoDisplay')) or truth(data.get('Hidden')):\n        return None\n    name = data.get('Name') or data.get('GenericName')\n    if not name:\n        return None\n    base = os.path.basename(path)\n    command = clean_exec(data.get('Exec', ''))\n    try:\n        argv = shlex.split(command)\n    except ValueError:\n        argv = []\n    return {\n        'id': 'app:' + base,\n        'title': name,\n        'subtitle': data.get('Comment') or data.get('GenericName') or base,\n        'desktopId': base,\n        'desktopPath': path,\n        'exec': command,\n        'execArgv': argv,\n        'icon': data.get('Icon', ''),\n        'terminal': truth(data.get('Terminal')),\n        'route': 'desktop-entry'\n    }\n\nroots = []\nhome = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')\nroots.append(home)\nroots.extend([p for p in os.environ.get('XDG_DATA_DIRS', '/usr/local/share:/usr/share').split(':') if p])\nseen = set()\napps = []\nfor root in roots:\n    appdir = os.path.join(root, 'applications')\n    if not os.path.isdir(appdir):\n        continue\n    for current, _, files in os.walk(appdir):\n        for name in files:\n            if not name.endswith('.desktop'):\n                continue\n            path = os.path.join(current, name)\n            rel = os.path.relpath(path, appdir).replace(os.sep, '-')\n            if rel in seen:\n                continue\n            row = parse_desktop(path)\n            if not row:\n                continue\n            row['desktopId'] = rel\n            row['id'] = 'app:' + rel\n            seen.add(rel)\n            apps.append(row)\napps.sort(key=lambda item: item['title'].casefold())\nprint(json.dumps(apps[:400], ensure_ascii=False))\n`;
    }

    function loadDesktopEntries() {
        if (appScan.running)
            return ;

        appScan.exec(["python3", "-c", desktopScanCode()]);
    }

    function applyDesktopEntries(text) {
        try {
            apps = JSON.parse(String(text || "[]"));
            appScanDone = true;
            appScanError = "";
        } catch (error) {
            appScanDone = true;
            appScanError = String(error);
            apps = [];
        }
    }

    function search(raw) {
        const intent = prefixIntent(raw);
        const query = intent.query;
        const results = [];
        const calc = calculatorValue(query);
        if ((intent.provider === "calculator" || intent.provider === "all") && calc.length > 0)
            pushResult(results, {
            "id": `calc:${query}`,
            "title": calc,
            "subtitle": query,
            "value": calc,
            "route": "calculator"
        }, "calculator", intent.provider === "calculator" ? 2000 : 600);

        if (intent.provider === "action" || intent.provider === "all") {
            for (let i = 0; i < actions.length; i++) pushResult(results, actions[i], "action", fuzzyScore(query, actions[i].title, intent.provider === "action" ? 1500 : 300))
        }
        if (intent.provider === "app" || intent.provider === "all") {
            for (let i = 0; i < apps.length; i++) pushResult(results, Object.assign({
                "route": "desktop-entry"
            }, apps[i]), "app", fuzzyScore(query, apps[i].title, 900))
        }
        if (intent.provider === "clipboard" || intent.provider === "all") {
            const clipRows = clipboardProviderRows(query);
            for (let i = 0; i < clipRows.length; i++) pushResult(results, Object.assign({
                "route": "clipboard",
                "backend": "Clipboard.qml"
            }, clipRows[i]), "clipboard", fuzzyScore(query, clipRows[i].title, intent.provider === "clipboard" ? 1400 : 200))
        }
        windowRows(query, intent.provider === "window" ? 1300 : 250, results);
        results.sort((a, b) => {
            return b.score - a.score || String(a.title).localeCompare(String(b.title));
        });
        const selectedIndex = results.length > 0 ? 0 : -1;
        const selectedResult = selectedIndex >= 0 ? results[selectedIndex] : null;
        return JSON.stringify({
            "query": raw,
            "providerIntent": intent.provider,
            "selectedIndex": selectedIndex,
            "singleScoredList": true,
            "keyboardFirst": true,
            "noPluginCommands": true,
            "scrollableListChrome": scrollableListChrome(results.length, selectedIndex),
            "launcherPanelContract": launcherPanelContract(),
            "launcherPreviewPanel": launcherPreviewPanel(selectedResult),
            "results": results
        });
    }

    Component.onCompleted: loadDesktopEntries()

    Process {
        id: appScan

        running: false

        stdout: StdioCollector {
            waitForEnd: true
            onStreamFinished: root.applyDesktopEntries(this.text)
        }

        stderr: StdioCollector {
            waitForEnd: true
            onStreamFinished: root.appScanError = this.text.trim()
        }

    }

}