Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/PopupHost.qml

Raw
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Window
import Quickshell
import Quickshell.Wayland

PanelWindow {
    id: root

    required property Theme theme
    required property SurfaceManager surfaces
    required property Registry registry
    // An active privilege prompt keeps keyboard focus; null means none.
    required property Privilege privilegeService
    required property var barWindow
    readonly property var contentSize: surfaces ? surfaces.popupContentSize(surfaces.popupName) : ({
            "width": 320,
            "height": 180
        })
    readonly property var cardFrame: surfaces ? surfaces.popupCardFrame(surfaces.popupProgress) : ({
            "currentRect": {
                "x": 8,
                "y": 8,
                "width": 304,
                "height": 164
            },
            "opacity": 1
        })
    readonly property var currentRect: cardFrame.currentRect
    property bool awaitingScrollRestore: false
    readonly property string activeName: surfaces ? surfaces.popupName : ""
    readonly property bool vertical: surfaces && surfaces.orientation === "vertical"
    // subtract the bar on whichever axis it occupies (top for horizontal, left
    // for vertical) so the popup surface covers only the free region.
    readonly property int barInset: surfaces ? surfaces.viewBar() : 0
    readonly property int surfaceWidth: surfaces && surfaces.viewWidth() > 0 ? (root.vertical ? Math.max(1, surfaces.viewWidth() - barInset) : surfaces.viewWidth()) : contentSize.width
    readonly property int surfaceHeight: surfaces && surfaces.viewHeight() > 0 ? (root.vertical ? surfaces.viewHeight() : Math.max(1, surfaces.viewHeight() - barInset)) : contentSize.height
    // An output other than the bar's has its own size and no bar.
    readonly property var targetScreen: screenByName(surfaces ? surfaces.popupOutput : "")
    readonly property bool offBar: !!barWindow && !!targetScreen && !!barWindow.screen && String(targetScreen.name) !== String(barWindow.screen.name)

    function panelScroll(item: var): Flickable {
        return item ? (item.scrollView || (item as Flickable)) : null;
    }

    // Registry features declare their retained view state; copy those same-named
    // panel properties, except the viewport offset the host handles itself.
    // A panel holding the live session object keeps it current itself.
    function copyRetained(name: string, from: var, to: var): void {
        const feature = root.registry ? root.registry.popup(name) : null;
        if (!feature || !from || !to || from.sessionState !== undefined || to.sessionState !== undefined)
            return;
        for (const key of Object.keys(feature.retainedState))
            if (key !== "scrollY" && from[key] !== undefined && to[key] !== undefined)
                to[key] = from[key];
    }

    // The viewport offset survives unless the entry's retainedState leaves out
    // `scrollY`, e.g. a status popup that always opens on its lead.
    function retainsScroll(name: string): bool {
        const feature = root.registry ? root.registry.popup(name) : null;
        return !feature || feature.retainedState.scrollY !== undefined;
    }

    function savePanelState(name) {
        const state = root.surfaces.panelStates[name];
        const item = root.panelScroll(activeLoader.item);
        if (!state || !item)
            return;
        root.copyRetained(name, activeLoader.item, state);
        if (root.retainsScroll(name))
            state.scrollY = item.contentY;
    }

    // A registry panel that declares `sessionState` receives the feature's live
    // session object on load, before its first frame.
    function bindSession(name: string, item: var): void {
        const state = root.surfaces ? root.surfaces.panelStates[name] : null;
        if (item && state && item.sessionState !== undefined && root.registry && root.registry.popup(name))
            item.sessionState = state;
    }

    // A registry panel that declares `closeRequested(reason)` closes its own popup,
    // only while that popup is the open one.
    function bindClose(name: string, item: var): void {
        if (!item || item.closeRequested === undefined || !root.registry || !root.registry.popup(name))
            return;
        item.closeRequested.connect(reason => {
            if (root.surfaces && root.surfaces.popupOpen && root.surfaces.popupName === name)
                root.surfaces.closePopup(String(reason));
        });
    }

    // A registry panel that declares `property Item initialFocus` gets keyboard
    // focus there once the popup window is active, on every open and switch;
    // a hidden or disabled target leaves focus on the card. The restored scroll
    // offset stays as it was.
    function focusInitial(panel: var): void {
        const window = root.contentItem.Window.window;
        const target = panel && window && window.active ? panel.initialFocus : null;
        if (!target || !target.visible || !target.enabled)
            return;
        const scroll = root.panelScroll(panel);
        const offset = scroll ? scroll.contentY : 0;
        target.forceActiveFocus(Qt.OtherFocusReason);
        if (scroll)
            scroll.contentY = offset;
    }

    // A registry panel that declares `naturalHeight` sizes its card (FeatureEntry.qml).
    function naturalHeight(panel: var): real {
        return panel && panel.naturalHeight !== undefined ? Number(panel.naturalHeight) : 0;
    }

    Binding {
        target: root.surfaces
        when: root.surfaces !== null
        property: "popupViewport"
        value: root.offBar ? ({
                "width": root.targetScreen.width,
                "height": root.targetScreen.height
            }) : null
    }

    Binding {
        target: root.surfaces
        when: root.surfaces !== null
        property: "panelHeight"
        value: root.naturalHeight(activeLoader.item)
    }

    function restorePanelState() {
        const name = root.activeName;
        const item = root.panelScroll(activeLoader.item);
        const state = root.surfaces.panelStates[name];
        if (!item || !state)
            return;
        root.copyRetained(name, state, activeLoader.item);
        if (root.retainsScroll(name))
            item.contentY = Math.max(0, Math.min(state.scrollY, item.contentHeight - item.height));
    }

    Connections {
        target: root.surfaces
        function onDismissing(name: string): void {
            root.savePanelState(name);
        }
    }

    Connections {
        target: root.contentItem.Window.window
        enabled: root.awaitingScrollRestore
        function onFrameSwapped() {
            root.restorePanelState();
            root.awaitingScrollRestore = false;
            root.surfaces.panelSettled = true;
        }
    }

    Connections {
        target: root.contentItem.Window.window
        function onActiveChanged() {
            root.focusInitial(activeLoader.item);
        }
    }

    function screenByName(name) {
        const want = String(name || "");
        const screens = Quickshell.screens;
        for (let i = 0; i < screens.length; i++)
            if (String(screens[i].name) === want)
                return screens[i];

        return root.barWindow ? root.barWindow.screen : null;
    }

    function contentComponent(name) {
        const feature = root.registry ? root.registry.popup(name) : null;
        return feature ? feature.panel : null;
    }

    visible: surfaces && surfaces.popupOpen
    screen: root.targetScreen
    implicitWidth: root.surfaceWidth
    implicitHeight: root.surfaceHeight
    color: "transparent"
    exclusionMode: ExclusionMode.Ignore
    WlrLayershell.layer: WlrLayer.Overlay
    WlrLayershell.namespace: "nuguland-popup"
    WlrLayershell.keyboardFocus: root.visible && (!root.privilegeService || !root.privilegeService.active) ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None
    onVisibleChanged: {
        if (!visible && root.surfaces && root.surfaces.popupOpen)
            root.surfaces.closePopup("focus-grab-outside");
    }
    onClosed: {
        if (root.surfaces)
            root.surfaces.closePopup("popup-closed");
    }

    anchors {
        top: true
        left: true
        right: true
        bottom: true
    }

    Shortcut {
        sequence: "Escape"
        context: Qt.WindowShortcut
        onActivated: {
            if (root.surfaces)
                root.surfaces.closePopup("escape-key");
        }
    }

    Item {
        id: popupInputRegion

        // origin sits just past the bar: below it (horizontal) or right of it
        // (vertical), so clicks on the bar itself are never captured here.
        x: root.vertical ? root.barInset : 0
        y: root.vertical ? 0 : root.barInset
        width: Math.max(1, parent.width - x)
        height: Math.max(1, parent.height - y)
    }

    MouseArea {
        id: outsideDismissLayer

        x: popupInputRegion.x
        y: popupInputRegion.y
        width: popupInputRegion.width
        height: popupInputRegion.height
        acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton
        onPressed: mouse => {
            // mouse.x/y are layer-local; the card rect is in root coords. The
            // layer origin is offset on both axes (below the top bar, or right
            // of the left bar), so convert both before the hit test.
            const rootX = mouse.x + outsideDismissLayer.x;
            const rootY = mouse.y + outsideDismissLayer.y;
            const inside = rootX >= card.x && rootX <= card.x + card.width && rootY >= card.y && rootY <= card.y + card.height;
            if (!inside && root.surfaces) {
                mouse.accepted = true;
                root.surfaces.closePopup("outside");
            }
        }
    }

    PopupSurface {
        id: card

        theme: root.theme
        padding: 0
        x: Math.round(root.currentRect.x)
        y: Math.round(root.currentRect.y)
        width: Math.round(root.currentRect.width)
        height: Math.round(root.currentRect.height)
        opacity: root.cardFrame.opacity
        transformOrigin: Item.Top
        focus: root.visible
        onVisibleChanged: {
            if (visible)
                forceActiveFocus();
        }
        Keys.onEscapePressed: event => {
            event.accepted = true;
            if (root.surfaces)
                root.surfaces.closePopup("escape-key");
        }

        Column {
            anchors.fill: parent
            anchors.margins: 16
            spacing: 10

            Item {
                id: loaderStack

                width: parent.width
                height: parent.height - y
                clip: true

                Loader {
                    id: activeLoader

                    anchors.fill: parent
                    opacity: root.surfaces ? root.surfaces.popupProgress : 1
                    sourceComponent: root.activeName.length > 0 ? root.contentComponent(root.activeName) : null
                    onLoaded: {
                        root.bindSession(root.activeName, item);
                        root.bindClose(root.activeName, item);
                        root.awaitingScrollRestore = true;
                        Qt.callLater(root.restorePanelState);
                        Qt.callLater(root.focusInitial, item);
                    }

                    Behavior on opacity {
                        NumberAnimation {
                            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
                            easing.type: Easing.OutCubic
                        }
                    }
                }
            }
        }

        Behavior on y {
            NumberAnimation {
                duration: root.theme && root.theme.lowPowerMode ? 0 : 130
                easing.type: Easing.InOutCubic
            }
        }

        // Content growing or shrinking in the open panel resizes the card in
        // step with its vertical recentring; open and switch take the size at once.
        Behavior on height {
            enabled: !!root.surfaces && root.surfaces.panelSettled

            NumberAnimation {
                duration: root.theme && root.theme.lowPowerMode ? 0 : 130
                easing.type: Easing.InOutCubic
            }
        }

        Behavior on opacity {
            NumberAnimation {
                duration: root.theme && root.theme.lowPowerMode ? 0 : 90
                easing.type: Easing.InOutCubic
            }
        }
    }

    mask: Region {
        item: popupInputRegion
    }

    Behavior on implicitWidth {
        NumberAnimation {
            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
            easing.type: Easing.OutCubic
        }
    }

    Behavior on implicitHeight {
        NumberAnimation {
            duration: root.theme && root.theme.lowPowerMode ? 0 : 180
            easing.type: Easing.OutCubic
        }
    }
}