aboutsummaryrefslogtreecommitdiffstats
path: root/games/Games.qml
blob: ef5576e57fe5e8e01aea78220cb499318e945ff3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// Copyright (C) 2026 Danilo M. <danix@danix.xyz>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

import Quickshell
import Quickshell.Io
import Quickshell.Wayland
import QtQuick

Scope {
    id: root

    property bool open: false
    property string monitor: "DP-1"
    property var items: []
    property string query: ""
    // Down switches the strip to the Steam store, searched as you type.
    property bool store: false
    property var results: []
    property bool searching: false

    // Horizontal shear of the strip's tiles, as a fraction of their height.
    readonly property real slant: -0.25
    readonly property int step: 210

    readonly property var screenObj:
        Quickshell.screens.find(s => s.name === root.monitor) ?? Quickshell.screens[0]

    readonly property var shown: {
        if (root.store) return root.results;
        const q = root.query.toLowerCase();
        return root.items.filter(g => g.name.toLowerCase().includes(q));
    }

    // The strip is a loop, so the list repeats until it fills the screen
    // width: a short library would otherwise leave gaps in the circle.
    readonly property var reel: {
        if (!root.shown.length) return [];
        const slots = Math.ceil(root.screenObj.width / root.step) + 2;
        let out = [];
        while (out.length < slots) out = out.concat(root.shown);
        return out;
    }

    function launch(g) {
        if (!g) return;
        if (root.store) {
            Quickshell.execDetached(["steam", `steam://store/${g.appid}`]);
            root.open = false;
            return;
        }
        // -silent keeps the Steam window down whether or not Steam is running.
        // Ids are strings: a shortcut's game id does not fit a JS number.
        Quickshell.execDetached(["steam", "-silent",
            g.installed ? `steam://rungameid/${g.id}` : `steam://install/${g.appid}`]);
        root.open = false;
    }

    // The list is read on every opening; the owned games come from a cache
    // that a Web API call refreshes in the background, then the list is
    // read again.
    onOpenChanged: if (open) {
        root.query = "";
        root.store = false;
        root.results = [];
        list.running = true;
        refresh.running = true;
    }

    // Local art is a path, store art a URL.
    function src(p) { return p ? (p.startsWith("/") ? `file://${p}` : p) : ""; }

    onQueryChanged: if (store) search.restart()
    onStoreChanged: if (store) search.restart()

    Timer {
        id: search
        interval: 350
        onTriggered: root.storeSearch(root.query.trim())
    }

    // The store's own search endpoint needs no key, but answers nothing
    // without a country, which also sets the prices. The locale is en_US
    // here, so it cannot be derived from that.
    // ponytail: fixed to Italy; a setting when another country matters.
    readonly property string country: "it"

    function storeSearch(term) {
        if (!term) { root.results = []; root.searching = false; return; }
        root.searching = true;
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState !== XMLHttpRequest.DONE || term !== root.query.trim()) return;
            root.searching = false;
            let found = [];
            try { found = JSON.parse(xhr.responseText).items ?? []; } catch (e) {}
            const mine = {};
            for (const g of root.items) if (g.appid) mine[g.appid] = g;
            const cdn = "https://shared.akamai.steamstatic.com/store_item_assets/steam/apps/";
            root.results = found.map(r => {
                const a = String(r.id);
                // Newer apps keep their art under hashed paths, so these
                // can 404; the capsule search returns always exists.
                // installed: drawn like a library game, not greyed.
                return { name: r.name, id: a, appid: a, mine: mine[a],
                         installed: true, last: 0, price: r.price,
                         cover: `${cdn}${a}/library_600x900.jpg`,
                         hero: `${cdn}${a}/library_hero.jpg`, capsule: r.tiny_image };
            });
        };
        xhr.open("GET", `https://store.steampowered.com/api/storesearch/?l=english&cc=${root.country}&term=`
                 + encodeURIComponent(term));
        xhr.send();
    }

    Process {
        id: list
        command: ["/usr/bin/python3", `${Quickshell.shellDir}/games.py`]
        stdout: StdioCollector {
            onStreamFinished: {
                try { root.items = JSON.parse(text); } catch (e) { root.items = []; }
            }
        }
    }

    Process {
        id: refresh
        command: ["/usr/bin/python3", `${Quickshell.shellDir}/games.py`, "--refresh"]
        onExited: code => { if (code === 0 && root.open) list.running = true; }
    }

    // A config with no visible window exits, reporting nothing. This 1x1
    // click-through window holds the shell open while the overlay is hidden.
    PanelWindow {
        anchors { top: true; left: true }
        implicitWidth: 1
        implicitHeight: 1
        color: "transparent"
        exclusionMode: ExclusionMode.Ignore
        mask: Region {}
        WlrLayershell.keyboardFocus: WlrKeyboardFocus.None
    }

    LazyLoader {
        active: root.open

        PanelWindow {
            id: win
            readonly property var game: root.reel[strip.currentIndex]
            readonly property color bg: Qt.rgba(Theme.crust.r, Theme.crust.g, Theme.crust.b, 0.94)

            screen: root.screenObj
            anchors { top: true; left: true; right: true; bottom: true }
            color: win.bg
            exclusionMode: ExclusionMode.Ignore
            WlrLayershell.layer: WlrLayer.Overlay
            WlrLayershell.namespace: "keystone-games"
            WlrLayershell.keyboardFocus: WlrKeyboardFocus.Exclusive

            MouseArea {
                anchors.fill: parent
                onClicked: root.open = false
            }

            // The selected game, large: Steam's wide hero art, or the cover
            // when there is none, fading into the background at the bottom.
            Item {
                anchors { top: parent.top; left: parent.left; right: parent.right; bottom: strip.top }

                // A store result's capsule, under its hero in case that 404s.
                Image {
                    anchors.fill: parent
                    source: root.src(win.game?.capsule)
                    fillMode: Image.PreserveAspectCrop
                    asynchronous: true
                }
                Image {
                    anchors.fill: parent
                    source: win.game ? root.src(win.game.hero || win.game.cover) : ""
                    fillMode: Image.PreserveAspectCrop
                    asynchronous: true
                }

                Rectangle {
                    anchors.fill: parent
                    gradient: Gradient {
                        GradientStop { position: 0.45; color: "transparent" }
                        GradientStop { position: 1.0; color: win.bg }
                    }
                }

                Column {
                    anchors { left: parent.left; bottom: parent.bottom; margins: 80 }
                    spacing: 8

                    Text {
                        text: win.game?.name
                            ?? (!root.store ? (root.items.length ? "No match  ·  Down searches the store" : "")
                                : root.searching ? "Searching the store…"
                                : root.query.trim() ? "Nothing on the store"
                                : "Type to search the Steam store")
                        color: Theme.text
                        font.family: Theme.fontFamily
                        font.pixelSize: 56
                        font.bold: true
                    }
                    Text {
                        visible: !!win.game
                        text: !win.game ? ""
                            : root.store ? [win.game.mine ? (win.game.mine.installed ? "Installed" : "Owned")
                                                          : win.game.price ? `${(win.game.price.final / 100).toFixed(2)} ${win.game.price.currency}`
                                                          : "Free or unpriced",
                                            "Enter opens the store page"].join("  ·  ")
                            : !win.game.installed ? "Not installed  ·  Enter installs"
                            : win.game.last ? `Last played ${new Date(win.game.last * 1000).toLocaleDateString(Qt.locale(), "d MMMM yyyy")}`
                            : "Never played"
                        color: root.store && win.game?.mine ? Theme.green
                            : win.game?.installed ? Theme.subtext : Theme.peach
                        font.family: Theme.fontFamily
                        font.pixelSize: 20
                    }
                }
            }

            // Keys reach a focused item, not a window: the search field
            // takes them all and steers the strip. It shows only what is typed.
            TextInput {
                id: field
                anchors { right: parent.right; top: parent.top; margins: 60 }
                focus: true
                color: Theme.text
                font.family: Theme.fontFamily
                font.pixelSize: 28
                onTextEdited: root.query = text

                Keys.onEscapePressed: { if (root.store) root.store = false; else root.open = false; }
                Keys.onDownPressed: root.store = true
                Keys.onUpPressed: root.store = false
                Keys.onLeftPressed: strip.decrementCurrentIndex()
                Keys.onRightPressed: strip.incrementCurrentIndex()
                Keys.onReturnPressed: root.launch(win.game)
                Keys.onEnterPressed: root.launch(win.game)
            }

            // An endless strip: PathView wraps, and the tile at the centre
            // is the selection.
            PathView {
                id: strip
                anchors { left: parent.left; right: parent.right; bottom: parent.bottom; bottomMargin: 120 }
                height: 300
                model: root.reel
                pathItemCount: Math.min(count, Math.ceil((width + 2 * root.step) / root.step))
                preferredHighlightBegin: 0.5
                preferredHighlightEnd: 0.5
                highlightRangeMode: PathView.StrictlyEnforceRange
                highlightMoveDuration: 220
                onModelChanged: currentIndex = 0

                path: Path {
                    startX: -root.step
                    startY: strip.height / 2
                    PathLine { x: strip.width + root.step; y: strip.height / 2 }
                }

                delegate: Item {
                    id: tile
                    required property var modelData
                    required property int index
                    readonly property bool current: PathView.isCurrentItem
                    width: 160
                    height: 160
                    z: current ? 1 : 0
                    scale: current ? 1.5 : 1
                    Behavior on scale { NumberAnimation { duration: 160 } }

                    // A parallelogram: the tile is sheared about its middle
                    // and clips to that shape; the art inside is sheared back
                    // so it stands straight, and widened to reach both edges.
                    Item {
                        anchors.fill: parent
                        clip: true
                        transform: Matrix4x4 {
                            matrix: Qt.matrix4x4(1, root.slant, 0, -root.slant * tile.height / 2,
                                                 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
                        }

                        Rectangle { anchors.fill: parent; color: Theme.surface }

                        Image {
                            id: cover
                            x: -tile.height * Math.abs(root.slant) / 2
                            width: parent.width + tile.height * Math.abs(root.slant)
                            height: parent.height
                            transform: Matrix4x4 {
                                matrix: Qt.matrix4x4(1, -root.slant, 0, root.slant * tile.height / 2,
                                                     0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
                            }
                            source: root.src(tile.modelData.cover)
                            sourceSize.width: 480
                            fillMode: Image.PreserveAspectCrop
                            asynchronous: true
                            // Not installed: greyed until selected.
                            opacity: tile.modelData.installed || tile.current ? 1 : 0.35
                        }

                        // No cover: the initial stands in for it.
                        Text {
                            anchors.centerIn: parent
                            visible: cover.status !== Image.Ready
                            text: tile.modelData.name.charAt(0)
                            color: Theme.text
                            font.family: Theme.fontFamily
                            font.pixelSize: 64
                            font.bold: true
                        }

                        // Not installed: a peach frame, the colour of the
                        // preview's "Not installed" line.
                        Rectangle {
                            anchors.fill: parent
                            color: "transparent"
                            border.width: tile.current ? 3 : tile.modelData.installed ? 0 : 2
                            border.color: tile.modelData.installed ? Theme.accent : Theme.peach
                        }
                    }

                    MouseArea {
                        anchors.fill: parent
                        onClicked: tile.current ? root.launch(tile.modelData) : strip.currentIndex = tile.index
                    }
                }

                // The wheel steps one tile a notch.
                MouseArea {
                    anchors.fill: parent
                    acceptedButtons: Qt.NoButton
                    onWheel: wheel => {
                        const d = wheel.angleDelta.y || wheel.angleDelta.x;
                        if (d < 0) strip.incrementCurrentIndex();
                        else if (d > 0) strip.decrementCurrentIndex();
                    }
                }
            }
        }
    }
}