Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/media/Media.qml

Raw
import QtQuick
import Quickshell
import Quickshell.Services.Mpris
import "../audio"
import "../osd"

Item {
    id: root

    property Osd osdService
    property Audio audioService
    property bool panelOpen: false
    property string manualSelection: ""
    property var lastAction: ({})
    property var trackChange: ({
            "direction": "none",
            "reverse": false,
            "fromTitle": "",
            "toTitle": ""
        })
    readonly property ObjectModel playerModel: Mpris.players
    // Registry empty state: no MPRIS player to show.
    readonly property bool hasPlayers: (root.playerModel.values || []).length > 0
    // Panel rows: every player and the one the panel shows, as plain records
    // that rebind as MPRIS players and their tracks change.
    readonly property var players: servicePlayers().map(player => clonePlayer(player))
    readonly property var activePlayer: clonePlayer(activePlayerRaw())
    // cheap reactive "something playing" signal for the bar chip active dot
    readonly property bool playing: {
        const players = root.playerModel.values || [];
        for (let i = 0; i < players.length; i++)
            if (players[i].playbackState === MprisPlaybackState.Playing)
                return true;

        return false;
    }

    Timer {
        interval: 1000
        repeat: true
        running: root.panelOpen && root.activePlayer.playbackState === "playing"
        onTriggered: {
            const player = root.nativePlayerById(root.activePlayer.id);
            if (player)
                player.positionChanged();
        }
    }

    function playbackStateText(player) {
        return String(MprisPlaybackState.toString(player.playbackState || MprisPlaybackState.Stopped)).toLowerCase();
    }

    function loopStateText(player) {
        const text = String(MprisLoopState.toString(player.loopState || MprisLoopState.None)).toLowerCase();
        if (text === "playlist")
            return "all";

        if (text === "track")
            return "one";

        return "none";
    }

    function playerId(player) {
        return String(player.dbusName || player.uniqueId || player.identity || "mpris-player");
    }

    function nativePlayerById(id) {
        const players = root.playerModel.values || [];
        for (let i = 0; i < players.length; i++)
            if (playerId(players[i]) === id) {
                return players[i];
            }
        return null;
    }

    function clonePlayer(player) {
        const id = playerId(player);
        const title = String(player.trackTitle || "");
        const artist = String(player.trackArtist || "");
        const album = String(player.trackAlbum || "");
        const position = Math.round(Number(player.position || 0));
        const length = Math.max(0, Math.round(Number(player.length || 0)));
        const cover = String(player.trackArtUrl || "");
        return {
            "id": id,
            "identity": String(player.identity || id),
            "title": title,
            "artist": artist,
            "album": album,
            "playbackState": playbackStateText(player),
            "position": position,
            "length": length,
            "progress": length > 0 ? Math.round(position * 1000 / length) / 1000 : 0,
            "shuffle": !!player.shuffle,
            "repeat": loopStateText(player),
            "canSeek": !!player.canSeek,
            "canShuffle": !!player.shuffleSupported,
            "canRepeat": !!player.loopSupported,
            "cover": cover,
            "artAvailable": cover.length > 0
        };
    }

    function servicePlayers() {
        return root.playerModel.values || [];
    }

    function activeIndex() {
        const players = servicePlayers();
        if (manualSelection.length > 0) {
            for (let i = 0; i < players.length; i++)
                if (playerId(players[i]) === manualSelection) {
                    return i;
                }
        }
        for (let j = 0; j < players.length; j++)
            if (playbackStateText(players[j]) === "playing") {
                return j;
            }
        return players.length > 0 ? 0 : -1;
    }

    function activePlayerRaw() {
        const players = servicePlayers();
        const index = activeIndex();
        return index >= 0 ? players[index] : ({
                "dbusName": "",
                "identity": "",
                "trackTitle": "",
                "trackArtist": "",
                "trackAlbum": "",
                "playbackState": MprisPlaybackState.Stopped,
                "position": 0,
                "length": 1,
                "shuffle": false,
                "loopState": MprisLoopState.None,
                "trackArtUrl": ""
            });
    }

    function osd(eventText) {
        if (!osdService)
            return {
                "event": "media",
                "value": eventText,
                "role": "info"
            };

        try {
            return osdService.trigger("media", eventText);
        } catch (error) {
            return {
                "event": "media",
                "value": eventText,
                "role": "info"
            };
        }
    }

    function setTrackChange(direction, reverse, fromTitle, toTitle) {
        trackChange = {
            "direction": direction,
            "reverse": reverse,
            "fromTitle": fromTitle,
            "toTitle": toTitle
        };
    }

    function stateObject(osdState) {
        const active = activePlayer;
        return {
            "manualSelection": manualSelection,
            "players": players,
            "activePlayer": active,
            "cover": {
                "source": active.artAvailable ? active.cover : `nugu-media:${active.id}`,
                "artAvailable": active.artAvailable,
                "role": active.artAvailable ? "content.normal" : "ui.accent"
            },
            "compact": {
                "label": "media",
                "title": active.title,
                "artist": active.artist,
                "playing": active.playbackState === "playing"
            },
            "rich": {
                "canSeek": active.canSeek,
                "shuffle": active.shuffle,
                "repeat": active.repeat
            },
            "trackChange": trackChange,
            "lastAction": lastAction,
            "osd": osdState || {}
        };
    }

    function stateJson() {
        return JSON.stringify(stateObject({}));
    }

    // Media keys and IPC echo each change on the OSD; the open panel passes
    // `quiet`, because it already shows the result.
    function action(kind, quiet) {
        const active = activePlayer;
        const playerIdValue = active.id;
        const name = String(kind);
        const nativePlayer = nativePlayerById(playerIdValue);
        if (name === "next")
            setTrackChange("next", false, active.title, "pending");
        else if (name === "previous")
            setTrackChange("previous", true, active.title, "pending");
        if (nativePlayer) {
            if (name === "playPause")
                nativePlayer.togglePlaying();
            else if (name === "next" && nativePlayer.canGoNext)
                nativePlayer.next();
            else if (name === "previous" && nativePlayer.canGoPrevious)
                nativePlayer.previous();
            else if (name === "stop")
                nativePlayer.stop();
            else if (name === "shuffle" && nativePlayer.shuffleSupported)
                nativePlayer.shuffle = !nativePlayer.shuffle;
            else if (name === "repeat" && nativePlayer.loopSupported)
                nativePlayer.loopState = nativePlayer.loopState === MprisLoopState.Playlist ? MprisLoopState.None : MprisLoopState.Playlist;
        }
        lastAction = {
            "kind": name,
            "id": playerIdValue
        };
        return JSON.stringify(stateObject(quiet ? {} : osd(name)));
    }

    function seek(position, quiet) {
        const playerIdValue = activePlayer.id;
        const nativePlayer = nativePlayerById(playerIdValue);
        if (nativePlayer && nativePlayer.canSeek)
            nativePlayer.position = Number(position);

        lastAction = {
            "kind": "seek",
            "id": playerIdValue,
            "position": position
        };
        return JSON.stringify(stateObject(quiet ? {} : osd(`seek ${position}`)));
    }

    function select(id, quiet) {
        manualSelection = String(id);
        lastAction = {
            "kind": "select",
            "id": manualSelection
        };
        return JSON.stringify(stateObject(quiet ? {} : osd(`select ${manualSelection}`)));
    }
}