foxygit / TV-Launcher Log in
commits tags

/qml/HomeScreen.qml · 14.71 KB

raw
import QtQuick
import QtQuick.Controls
import TvLauncher

// Hemskärm: toppfält med klocka och ikonknappar (Bigscreen), en stor
// header som visar markerad app (Netflix) och rader per kategori under
// varandra där varje rad skrollar åt höger.
FocusScope {
    id: home

    signal launch(var app)
    signal editApp(var app)
    signal editAppearance(var app)
    signal action(string name, Item source)

    property string rememberId: ""
    property var current: null
    readonly property int heroHeight: Theme.dp(600)
    readonly property int rowHeight: Theme.dp(70) + Theme.tile(310)

    function itemsFor(key) {
        return key === "__recent" ? apps.recent(12) : apps.appsIn(key)
    }

    // Alla fält som strängar så att ListModel får samma roller överallt.
    function norm(a) {
        return { id: a.id || "", name: a.name || "", type: a.type || "", icon: a.icon || "",
                 url: a.url || "", command: a.command || "", engine: a.engine || "",
                 category: a.category || "", userAgent: a.userAgent || "",
                 color: a.color || "", heroImage: a.heroImage || "", heroText: a.heroText || "",
                 heroShowIcon: a.heroShowIcon !== false,
                 chromiumAppId: a.chromiumAppId || "", chromiumProfile: a.chromiumProfile || "",
                 chromiumBin: a.chromiumBin || "", controllerMode: a.controllerMode || "" }
    }

    function hostOf(url) { return url.replace(/^[a-z]+:\/\//i, "").replace(/\/.*$/, "") }

    function subtitleFor(a) {
        if (a.type === "web") return hostOf(a.url)
        const first = (a.command || "").trim().split(/\s+/)[0] || ""
        return first.split("/").pop()
    }

    function syncRows() {
        const r = []
        if (apps.recent(1).length > 0) r.push({ key: "__recent", label: "Senaste" })
        for (const c of apps.categories) r.push({ key: c, label: c })

        let same = r.length === rowsModel.count
        for (let i = 0; same && i < r.length; ++i)
            same = rowsModel.get(i).key === r[i].key
        if (same)
            return
        const keepKey = rows.currentIndex >= 0 && rows.currentIndex < rowsModel.count
                        ? rowsModel.get(rows.currentIndex).key : ""
        const hadRowFocus = rows.activeFocus
        rowsModel.clear()
        for (const row of r) rowsModel.append(row)
        const idx = r.findIndex(x => x.key === keepKey)
        rows.currentIndex = idx >= 0 ? idx : 0
        Qt.callLater(() => {
            if (hadRowFocus) focusRows()
            updateCurrent()
        })
    }

    function updateCurrent() {
        const row = rows.currentItem
        const l = row ? row.list : null
        if (l && l.currentIndex >= 0 && l.currentIndex < l.count)
            home.current = norm(l.model.get(l.currentIndex))
        else if (!home.current)
            home.current = null
    }

    function focusRows() {
        if (rowsModel.count > 0) rows.forceActiveFocus()
        else topBar.forceActiveFocus()
    }
    function focusTopBar() { topBar.forceActiveFocus() }
    function restoreFocus() { focusRows(); updateCurrent() }

    Keys.onUpPressed: focusTopBar()
    Keys.onPressed: (event) => {
        if (event.key === Qt.Key_PageUp) { rows.decrementCurrentIndex(); focusRows(); event.accepted = true }
        else if (event.key === Qt.Key_PageDown) { rows.incrementCurrentIndex(); focusRows(); event.accepted = true }
    }

    ListModel { id: rowsModel }

    Connections {
        target: apps
        function onChanged() { home.syncRows() }
    }
    Component.onCompleted: {
        syncRows()
        Qt.callLater(focusRows)
    }

    // Mörkare nertill så att raderna syns mot bakgrundsbilden.
    Rectangle {
        anchors.fill: parent
        gradient: Gradient {
            GradientStop { position: 0.0; color: "#00000000" }
            GradientStop { position: 0.45; color: "#30000000" }
            GradientStop { position: 1.0; color: "#c0000000" }
        }
    }

    // ---------------------------------------------------------------- hero
    Item {
        id: hero
        anchors.fill: parent

        property var shown: null

        Connections {
            target: home
            function onCurrentChanged() {
                const a = hero.shown, b = home.current
                if (!a || !b || a.id !== b.id || a.heroImage !== b.heroImage) swap.restart()
                else hero.shown = b
            }
        }
        SequentialAnimation {
            id: swap
            NumberAnimation { target: heroContent; property: "opacity"; to: 0; duration: 90 }
            ScriptAction { script: hero.shown = home.current }
            NumberAnimation { target: heroContent; property: "opacity"; to: 1; duration: 220; easing.type: Easing.OutCubic }
        }

        // Mörkt från vänster bakom texten (hela höjden så att ingen kant syns).
        Rectangle {
            x: 0; y: 0
            width: parent.width
            height: home.height
            gradient: Gradient {
                orientation: Gradient.Horizontal
                GradientStop { position: 0.0; color: "#b0000000" }
                GradientStop { position: 0.45; color: "#60000000" }
                GradientStop { position: 0.75; color: "#00000000" }
            }
        }

        HeroView {
            id: heroContent
            anchors.fill: parent
            heroHeight: home.heroHeight
            app: hero.shown
        }
    }

    // ------------------------------------------------------------ toppfält
    component TopButton: Item {
        id: tb
        property string icon
        property string label
        signal clicked()

        width: Theme.dp(82); height: width
        Keys.onReturnPressed: tb.clicked()
        Keys.onEnterPressed: tb.clicked()

        Rectangle {
            anchors.fill: parent
            radius: width / 2
            color: tb.activeFocus ? "#40ffffff" : "transparent"
            border.width: tb.activeFocus ? Theme.dp(3) : 0
            border.color: Theme.accent
        }
        Icon {
            anchors.centerIn: parent
            width: Theme.dp(42); height: width
            name: tb.icon
        }
        Text {
            visible: tb.activeFocus
            anchors { top: parent.bottom; topMargin: Theme.dp(8); horizontalCenter: parent.horizontalCenter }
            text: tb.label
            color: Theme.text
            font.family: Theme.fontFamily
            font.pixelSize: Theme.dp(20)
        }
        MouseArea {
            anchors.fill: parent
            onClicked: { tb.forceActiveFocus(); tb.clicked() }
        }
    }

    FocusScope {
        id: topBar
        anchors { left: parent.left; right: parent.right; top: parent.top }
        height: Theme.dp(190)

        property int idx: 0
        readonly property var buttons: [
            { icon: "search", label: "Sök", action: "search" },
            { icon: "add", label: "Lägg till", action: "add" },
            { icon: "settings", label: "Inställningar", action: "settings" },
            { icon: "volume", label: "Ljud", action: "audio" },
            { icon: "wifi", label: "Wi‑Fi", action: "wifi" },
            { icon: "bluetooth", label: "Bluetooth", action: "bluetooth" },
            { icon: "power", label: "Ström", action: "power" }
        ]

        Keys.onLeftPressed: idx = Math.max(0, idx - 1)
        Keys.onRightPressed: idx = Math.min(buttons.length - 1, idx + 1)
        Keys.onDownPressed: home.focusRows()
        Keys.onUpPressed: {}

        Row {
            anchors { left: parent.left; leftMargin: Theme.dp(110); verticalCenter: parent.verticalCenter }
            spacing: Theme.dp(30)
            Text {
                id: clock
                anchors.baseline: date.baseline
                color: Theme.text
                font.family: Theme.fontFamily
                font.pixelSize: Theme.dp(64)
                font.weight: Font.Light
            }
            Text {
                id: date
                color: Theme.text
                opacity: 0.85
                font.family: Theme.fontFamily
                font.pixelSize: Theme.dp(34)
            }
            Timer {
                interval: 5000; running: true; repeat: true; triggeredOnStart: true
                onTriggered: {
                    const now = new Date()
                    clock.text = Qt.formatTime(now, "HH:mm")
                    const d = now.toLocaleDateString(Qt.locale("sv_SE"), "dddd d MMMM yyyy")
                    date.text = d.charAt(0).toUpperCase() + d.slice(1)
                }
            }
        }

        Row {
            anchors { right: parent.right; rightMargin: Theme.dp(100); verticalCenter: parent.verticalCenter }
            spacing: Theme.dp(14)

            Icon {
                anchors.verticalCenter: parent.verticalCenter
                visible: input.connected
                width: Theme.dp(40); height: width
                opacity: 0.6
                name: "gamepad"
            }
            Item { width: Theme.dp(20); height: 1; visible: input.connected }

            Repeater {
                model: topBar.buttons
                delegate: TopButton {
                    id: topButton
                    required property var modelData
                    required property int index
                    focus: index === topBar.idx
                    icon: modelData.icon
                    label: modelData.label
                    onClicked: {
                        topBar.idx = index
                        home.action(modelData.action, topButton)
                    }
                }
            }
        }
    }

    // --------------------------------------------------------- app-raderna
    ListView {
        id: rows
        anchors { left: parent.left; right: parent.right; top: parent.top; topMargin: home.heroHeight; bottom: parent.bottom }
        focus: true
        clip: true
        model: rowsModel
        cacheBuffer: 10000
        spacing: 0
        highlightRangeMode: ListView.StrictlyEnforceRange
        preferredHighlightBegin: Theme.dp(10)
        preferredHighlightEnd: Theme.dp(10) + home.rowHeight
        highlightMoveDuration: 280
        boundsBehavior: Flickable.StopAtBounds
        onCurrentIndexChanged: Qt.callLater(home.updateCurrent)

        delegate: FocusScope {
            id: row
            required property string key
            required property string label
            required property int index
            property alias list: list

            width: rows.width
            height: home.rowHeight
            focus: ListView.isCurrentItem
            opacity: ListView.isCurrentItem || !rows.activeFocus ? 1 : 0.7
            Behavior on opacity { NumberAnimation { duration: 200 } }

            Text {
                id: title
                x: Theme.dp(110)
                text: row.label
                color: Theme.text
                font.family: Theme.fontFamily
                font.pixelSize: Theme.dp(44)
                font.weight: Font.Light
            }

            ListView {
                id: list
                anchors { left: parent.left; right: parent.right; top: title.bottom; topMargin: Theme.dp(14) }
                height: Theme.tile(310)
                orientation: ListView.Horizontal
                focus: true
                spacing: Theme.dp(28)
                leftMargin: Theme.dp(110)
                rightMargin: Theme.dp(110)
                clip: false
                highlightRangeMode: ListView.ApplyRange
                preferredHighlightBegin: Theme.dp(110)
                preferredHighlightEnd: width - Theme.tile(460)
                highlightMoveDuration: 220
                boundsBehavior: Flickable.StopAtBounds
                model: ListModel { id: lm }

                onCurrentIndexChanged: if (row.index === rows.currentIndex) home.updateCurrent()

                // Uppdatera på plats så att markeringen inte hoppar.
                function sync() {
                    const items = home.itemsFor(row.key).map(home.norm)
                    let same = items.length === lm.count
                    for (let i = 0; same && i < items.length; ++i)
                        same = lm.get(i).id === items[i].id
                    if (same) {
                        for (let i = 0; i < items.length; ++i) lm.set(i, items[i])
                    } else {
                        const oldIndex = currentIndex
                        const oldId = oldIndex >= 0 && oldIndex < lm.count ? lm.get(oldIndex).id : ""
                        lm.clear()
                        for (const it of items) lm.append(it)
                        let idx = items.findIndex(a => a.id === home.rememberId)
                        if (idx < 0) idx = items.findIndex(a => a.id === oldId)
                        if (idx < 0) idx = Math.min(Math.max(oldIndex, 0), items.length - 1)
                        currentIndex = idx
                    }
                    if (row.index === rows.currentIndex) home.updateCurrent()
                }

                delegate: AppTile {
                    id: tile
                    required property var model
                    required property int index
                    focus: ListView.isCurrentItem
                    name: model.name
                    subtitle: home.subtitleFor(model)
                    icon: model.icon
                    customColor: model.color
                    isWeb: model.type === "web"

                    onActivated: {
                        const item = home.norm(model)
                        home.rememberId = item.id
                        home.launch(item)
                    }
                    onMenuRequested: {
                        const item = home.norm(model)
                        home.rememberId = item.id
                        tileMenu.app = item
                        tileMenu.popup(tile, tile.width / 2, Theme.dp(60))
                    }
                    onHovered: {
                        rows.currentIndex = row.index
                        list.currentIndex = index
                        rows.forceActiveFocus()
                    }
                }
            }

            Connections {
                target: apps
                function onChanged() { list.sync() }
            }
            Component.onCompleted: list.sync()
        }
    }

    TvMenu {
        id: tileMenu
        property var app: ({})

        Action { text: "Starta"; onTriggered: home.launch(tileMenu.app) }
        Action { text: "Utseende och förhandsvisning"; onTriggered: home.editAppearance(tileMenu.app) }
        Action { text: "Redigera"; onTriggered: home.editApp(tileMenu.app) }
        Action { text: "Flytta vänster"; onTriggered: apps.move(tileMenu.app.id, -1) }
        Action { text: "Flytta höger"; onTriggered: apps.move(tileMenu.app.id, 1) }
        Action { text: "Ta bort"; onTriggered: apps.remove(tileMenu.app.id) }
    }
}