Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/test-fixtures/ui/bar.qml

Raw
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Window
import Quickshell
import Quickshell.Io
import Quickshell.Services.Notifications
import "../.." as N

Scope {
    id: root

    // Normal xdg-toplevel destination for compositor-level focus-return proof;
    // the shared `focus-target` fixture event maps it.
    Window {
        id: focusReturnApp
        visible: false
        title: "focus target"
        width: 400
        height: 180
        color: "#121212"
    }

    property int layoutFrames: 0
    // The overlaid Usage double records chip activations; production Usage has no `recorded`.
    readonly property var usageDouble: usage
    // Registry features: stable control identities across snapshots.
    property var seenControls: []

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

    function ownedTree(item: var): var {
        const items = [];
        function visit(object) {
            if (!object || items.indexOf(object) >= 0)
                return;
            items.push(object);
            for (const child of object.children || [])
                visit(child);
            const data = typeof object.data === "function" ? [] : (object.data || []);
            for (const datum of data)
                visit(datum);
        }
        visit(item);
        return items;
    }

    function host(): var {
        return ownedTree(bar).find(function (item) {
            return item.activeName !== undefined && item.cardFrame !== undefined;
        }) || null;
    }

    function rect(item: var, window: var): var {
        if (!item || !window)
            return null;
        const point = item.mapToItem(window.contentItem, 0, 0);
        return {
            "x": point.x,
            "y": point.y,
            "width": item.width,
            "height": item.height
        };
    }

    function chip(name: string): var {
        return tree(bar.contentItem).find(function (item) {
            return item.visible && item.popupName === name;
        }) || null;
    }

    // The Bar tooltip's text while it is mapped for this chip or bar control, else "".
    function hint(item: var): string {
        return !!item && bar.hintShown && tree(item).indexOf(bar.hintTarget) >= 0 ? bar.hintText : "";
    }

    function chipState(name: string): var {
        const item = chip(name);
        return {
            "rect": rect(item, bar),
            "hovered": !!item && tree(item).some(function (child) {
                return child.visible && child.containsMouse === true;
            }),
            "focused": !!item && tree(item).some(function (child) {
                return child.visible && child.activeFocus === true;
            }),
            "label": item ? String(item.label) : "",
            // The vertical Bar's glyph and badge in place of the label; empty horizontally.
            "icon": item ? String(item.icon) : "",
            "badge": item ? String(item.badge) : "",
            "title": item ? String(item.title) : "",
            "accessibleName": item ? String(item.Accessible.name) : "",
            "tooltip": root.hint(item),
            "active": !!item && item.active === true,
            // Registry bar emphasis as the chip renders it: `strong` emphasis,
            // resolved `role`, and a visible `busy` underline.
            "strong": !!item && item.activeStrong === true,
            "role": item && item.role !== undefined ? String(item.role) : "",
            "busy": !!item && tree(item).some(child => child.visible && child.objectName === "busyLine"),
            // The visible attention mark: "warning" (an exclamation mark), "activity" (a dot) or "".
            "mark": !!item && tree(item).some(child => child.visible && child.objectName === "warningMark") ? "warning" : (!!item && tree(item).some(child => child.visible && child.objectName === "activeDot") ? "activity" : "")
        };
    }

    // A registry entry's own bar control (FeatureEntry.barControl) as Bar lays it out.
    function barControlState(name: string): var {
        const item = tree(bar.contentItem).find(item => item.visible && item.controlName === name) || null;
        return {
            "rect": rect(item, bar),
            "label": item && item.control ? String(item.control.label) : "",
            "tooltip": root.hint(item),
            "selected": !!item && item.selected === true
        };
    }

    function panelFor(name: string, objects: var): var {
        const feature = featureRegistry.popup(name);
        return feature ? objects.find(item => item.parent && item.parent.sourceComponent === feature.panel) || null : null;
    }

    function named(objects: var, name: string): var {
        return objects.find(function (item) {
            return item.visible && item.objectName === name;
        }) || null;
    }

    // Screenshot reports from niri; ui-test waits for each before going on.
    property int notices: 0
    NotificationServer {
        onNotification: root.notices++
    }

    N.Theme {
        id: palette
        lowPowerMode: true
    }
    N.AuroraBackdrop {
        resourceService: featureRegistry.system
        theme: palette
        lowPowerMode: true
    }
    N.Usage {
        id: usage
        widgets: featureRegistry.chips
    }
    N.Niri {
        id: niri
    }
    N.Privilege {
        id: privilege
    }
    N.Registry {
        id: featureRegistry
        theme: palette
        surfaces: bar.surfaces
        // Long enough that a screenshot, including niri's notification
        // round trip, never races expiry under a full parallel run.
        osd.lifetimeMs: 10000
    }
    // Registry overlays (the OSD) and focus overlays on the fixture's only output.
    N.OverlayHost {
        id: overlays
        registry: featureRegistry
        primaryScreenName: Quickshell.screens.length > 0 ? String(Quickshell.screens[0].name) : ""
        surfaces: surfaces
    }
    N.SurfaceManager {
        id: surfaces
        registry: featureRegistry
    }
    Connections {
        target: surfaces
        function onPopupNameChanged() {
            root.layoutFrames = 0;
        }
    }
    N.Bar {
        id: bar
        theme: palette
        niriService: niri
        registry: featureRegistry
        privilegeService: privilege
        surfaces: surfaces
        usageService: usage
        orientation: featureRegistry.config.orientation
        FrameAnimation {
            running: surfaces.popupOpen && root.layoutFrames < 4
            onTriggered: root.layoutFrames++
        }
    }

    function externalEvent(event: string): void {
        if (event === "vertical" || event === "horizontal")
            featureRegistry.config.setOrientation(event);
        else if (event === "motion-on")
            palette.lowPowerMode = false;
        else if (event === "motion-off")
            palette.lowPowerMode = true;
        else if (event === "focus-target")
            focusReturnApp.visible = true;
        else if (event.startsWith("feature:"))
            root.featureEvent(event);
        else
            console.error("ERROR unknown fixture event: " + event);
    }

    // Registry features, generically: `feature:<name>:<method>:<json args>` calls a
    // method on the feature's service (its double, where it has one).
    function featureEvent(event: string): void {
        const match = /^feature:([a-z][a-z0-9-]*):([A-Za-z]\w*):(.*)$/.exec(event);
        const feature = match ? Array.from(featureRegistry.entries).find(entry => entry.name === match[1]) : null;
        const service = feature ? feature.service : null;
        if (!service || typeof service[match[2]] !== "function") {
            console.error("ERROR unknown feature event: " + event);
            return;
        }
        service[match[2]](...JSON.parse(match[3] || "[]"));
    }

    function controlIdentity(item: var): int {
        let index = seenControls.indexOf(item);
        if (index < 0) {
            seenControls.push(item);
            index = seenControls.length - 1;
        }
        return index;
    }

    // Editable items never report their text, only whether it is `filled`.
    // `checked` is a toggle's state; `levels` a stacked multi-value control's values;
    // `attention`, `destructive` and `highlighted` a card's emphasis, `selected` its
    // selection rail; `masked` a password editor.
    function featureControl(item: var, window: var, originX: real): var {
        const box = rect(item, window);
        if (box)
            box.x += originX;
        const text = typeof item.text === "string" ? item.text : "";
        const editable = root.editableItem(item);
        return {
            "id": controlIdentity(item),
            "rect": box,
            "enabled": item.enabled,
            "focused": item.controlFocused === true || (item.input ? item.input.activeFocus : item.activeFocus),
            "pressed": item.pressed === true,
            "value": item.displayedValue !== undefined ? item.displayedValue : null,
            "text": editable ? "" : text,
            "filled": text.length > 0,
            "masked": item.echoMode === TextInput.Password,
            "tooltip": item.tooltipVisible === true,
            "tooltipText": typeof item.tooltip === "string" ? item.tooltip : "",
            "checked": item.checked === true,
            "levels": !!item.levels && typeof item.levels === "object" ? Array.from(item.levels) : [],
            "attention": item.attention === true,
            "destructive": item.destructive === true,
            "highlighted": item.highlighted === true,
            "selected": item.selectionMarked === true,
            "opacity": item.opacity
        };
    }

    function editableItem(item: var): bool {
        return item.cursorPosition !== undefined || (!!item.input && item.input.cursorPosition !== undefined);
    }

    // Named controls (by accessible name), named items (by objectName) and visible
    // non-editable text of one mapped surface's items.
    function collect(state: var, items: var, window: var, originX: real): void {
        for (const item of items) {
            if (!item.visible)
                continue;
            // The outermost item owning a name wins, e.g. a slider over its inner track.
            const name = item.accessibleName || item.Accessible.name;
            if (name && !state.controls[name])
                state.controls[name] = featureControl(item, window, originX);
            if (item.objectName && !state.items[item.objectName])
                state.items[item.objectName] = featureControl(item, window, originX);
            // Visible non-editable text in tree order, e.g. labels and status lines.
            if (typeof item.text === "string" && item.text.length > 0 && !root.editableItem(item)) {
                state.texts.push(item.text);
                // Text a person or an app wrote, e.g. a notification body (NuguText.qml).
                if (item.userText === true)
                    state.userTexts.push(item.text);
            }
        }
    }

    // An entry's focus overlay while mapped: its full-output surface, controls,
    // items and texts in output coordinates; null while hidden or absent.
    function focusOverlayState(feature: var): var {
        const window = feature.focusOverlay ? overlays.focusSurface(feature.name) : null;
        if (!window)
            return null;
        const state = {
            "surface": {
                "x": 0,
                "y": 0,
                "width": window.width,
                "height": window.height
            },
            "controls": ({}),
            "items": ({}),
            "texts": [],
            "userTexts": []
        };
        collect(state, tree(window.contentItem), window, 0);
        return state;
    }

    // Surface, named controls (by accessible name), named items (by objectName),
    // retained panel state, service state, and focus overlay of one registry feature.
    function featureState(feature: var, popup: var, objects: var, popupHost: var): var {
        const service = feature.service;
        const state = {
            "kind": feature.kind,
            "service": typeof service.fixtureState === "function" ? service.fixtureState() : (typeof service.stateObject === "function" ? service.stateObject() : null),
            "open": false,
            "surface": null,
            "retained": ({}),
            "controls": ({}),
            "items": ({}),
            "texts": [],
            "userTexts": [],
            "focusOverlay": focusOverlayState(feature)
        };
        let window = null;
        let items = [];
        let originX = 0;
        if (feature.kind === "popup") {
            const panel = popup.name === feature.name ? objects.find(item => item.parent && item.parent.sourceComponent === feature.panel) || null : null;
            if (!panel)
                return state;
            window = popupHost;
            items = tree(panel);
            state.surface = rect(panel, window);
            // A panel holding the host's live session object reports it directly.
            for (const key of Object.keys(feature.retainedState))
                state.retained[key] = panel.sessionState !== undefined ? panel.sessionState[key] : (key === "scrollY" ? (panel.scrollView || panel).contentY : panel[key]);
        } else if (feature.kind === "overlay") {
            window = overlays.surface(feature.name);
            if (!window)
                return state;
            items = tree(window.contentItem);
            // OverlayHost anchors overlays top-right of the output.
            originX = surfaces.screenWidth - window.width;
            state.surface = {
                "x": originX,
                "y": 0,
                "width": window.width,
                "height": window.height
            };
        } else {
            // A toggle entry has no surface; its chip is in `chips`.
            return state;
        }
        state.open = true;
        collect(state, items, window, originX);
        return state;
    }

    function state(): string {
        const popupHost = host();
        const objects = popupHost ? tree(popupHost.contentItem) : [];
        const popup = JSON.parse(surfaces.popupState());
        const panel = panelFor(popup.name, objects);
        return JSON.stringify({
            "notices": root.notices,
            "focusTargetActive": focusReturnApp.active,
            "width": surfaces.screenWidth,
            "height": surfaces.screenHeight,
            "orientation": surfaces.orientation,
            "barWidth": bar.width,
            "barThickness": surfaces.barHeight,
            "layoutFrames": root.layoutFrames,
            "themeMode": palette.mode,
            "barEdge": rect(tree(bar.contentItem).find(item => item.color !== undefined && Qt.colorEqual(item.color, palette.withAlpha(palette.ui.accent, 0.55))), bar),
            "popup": {
                "open": popup.open,
                "windowActive": !!popupHost && !!popupHost.contentItem.Window.window && popupHost.contentItem.Window.window.active,
                "phase": popup.phase,
                "name": popup.name,
                "lastCloseReason": popup.lastCloseReason,
                "card": popup.popupCardFrame.currentRect,
                // The open panel's natural height that sizes the card (FeatureEntry.qml).
                "panelHeight": popup.panelHeight
            },
            "panel": rect(panel, popupHost),
            // Every usage-ordered chip the Bar shows, and the chip activations Usage recorded.
            "chips": usage.layoutOrder.reduce((chips, name) => Object.assign(chips, {
                    [name]: chipState(name)
                }), ({})),
            "usage": root.usageDouble.recorded,
            "barControls": featureRegistry.barControls.reduce((controls, feature) => Object.assign(controls, {
                    [feature.name]: barControlState(feature.name)
                }), ({})),
            "features": Array.from(featureRegistry.entries).reduce((features, feature) => Object.assign(features, {
                    [feature.name]: featureState(feature, popup, objects, popupHost)
                }), ({}))
        });
    }

    IpcHandler {
        target: "uiTest"

        function external(event: string): void {
            root.externalEvent(event);
        }

        function snapshot(): string {
            return root.state();
        }
    }
}