-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
476 lines (361 loc) · 17.1 KB
/
main.py
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import sys
from typing import Optional, NamedTuple
from PySide6.QtWidgets import *
from PySide6.QtCore import * # type: ignore
from PySide6.QtGui import * # type: ignore
import qdarktheme # type: ignore
import storage
from storage import Config, Library, Game
from Sidebar import Sidebar, SidebarButton
from GameTile import GameTile
from AddGameWindow import AddGameWindow
from CoupledPropertyAnimation import CoupledPropertyAnimation
class GameTileInfo(NamedTuple):
tile: GameTile
game: Game
class RunningProcess(NamedTuple):
process: QProcess
id: int
def main(argv: list[str]) -> None:
config = Config()
library = Library()
app = QApplication(argv)
qss = '''
QPushButton {
border-width: 0px;
}
QPushButton:!hover {
background-color: #2c669ff5;
}
QPushButton:hover {
background-color: #5c669ff5;
}
QPushButton:pressed {
background-color: #9a5796f4;
}
/* For some reason, this stops the item's text from moving when you hover over it */
QAbstractItemView::item {
background-color: #00000000;
}
'''
qdarktheme.setup_theme(theme='dark', additional_qss=qss)
window = MainWindow(library, config)
window.show()
app.exec()
class MainWindow(QMainWindow):
def __init__(self, library: Library, config: Config) -> None:
super().__init__()
self.MAIN_CONTENT_PADDING = 20
self.runningProcess: Optional[RunningProcess] = None
self.library = library
self.config = config
self.addGameWindow = AddGameWindow(self.library, self.config, self.refresh, self)
# Sidebar
testButton1 = SidebarButton(
QStaticText('Alphabetical order'),
lambda: self.sortGamesByName(True),
icon = QIcon.fromTheme('view-sort-ascending-name'),
)
testButton2 = SidebarButton(
QStaticText('Alphabetical order'),
lambda: self.sortGamesByName(False),
icon = QIcon.fromTheme('view-sort-descending-name'),
)
self.sidebar = Sidebar(buttons = [testButton1, testButton2])
self.sidebar.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Expanding)
# Scroll area with games
self.scrollLayout = QHBoxLayout()
self.scrollLayout.setContentsMargins(self.MAIN_CONTENT_PADDING, 0, self.MAIN_CONTENT_PADDING, self.MAIN_CONTENT_PADDING)
self.scrollLayout.setSpacing(10)
scrollBarHeight = self.style().pixelMetric(QStyle.PixelMetric.PM_ScrollBarExtent)
self.tiles: list[GameTileInfo] = []
self.defaultImage = QPixmap(600, 900)
self.defaultImage.fill(Qt.GlobalColor.white)
self.imageHeight = 450
self.expandedImageHeight = 540
for i, game in enumerate(library.games):
image = storage.getLibraryImage(game['id'])
if image is None:
image = self.defaultImage
tile = GameTile(image, self.imageHeight, self.expandedImageHeight, self)
tile.clicked.connect(lambda i=i: self.tileClicked(i))
self.tiles.append(GameTileInfo(tile, game))
self.scrollLayout.addWidget(tile)
self.selectedTile: Optional[int] = None
self.scrollWidget = QWidget()
self.scrollWidget.setLayout(self.scrollLayout)
self.scrollArea = AnimatedScrollArea(self)
self.scrollArea.setWidget(self.scrollWidget)
self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOn)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setFrameShape(QFrame.Shape.NoFrame)
# Extra 4 pixels I think is because:
# tile.height() == tile.pixmap.height() + 2
# scrollArea.height() = tile.height() + 2
self.scrollArea.setFixedHeight(
int(self.expandedImageHeight + scrollBarHeight + self.MAIN_CONTENT_PADDING + 4)
)
self.runningAnimations = QSequentialAnimationGroup(self)
# Buttons at the top
settingsButtonSize = 50
settingsIconSize = int(settingsButtonSize * 0.8)
self.settingsButton = QPushButton(QIcon.fromTheme('settings'), '')
self.settingsButton.setFixedSize(settingsButtonSize, settingsButtonSize)
self.settingsButton.setIconSize(QSize(settingsIconSize, settingsIconSize))
self.settingsButton.setToolTip('Settings')
self.addGameButton = QPushButton(QIcon.fromTheme('add'), '')
self.addGameButton.setFixedSize(settingsButtonSize, settingsButtonSize)
self.addGameButton.setIconSize(QSize(settingsIconSize, settingsIconSize))
self.addGameButton.setToolTip('Add game')
self.addGameButton.clicked.connect(self.addGameClicked)
topBar = QHBoxLayout()
topBar.addStretch()
topBar.addWidget(self.addGameButton)
topBar.addWidget(self.settingsButton)
topBar.setContentsMargins(0, 10, 10, 0)
topBar.setSpacing(10)
# Game info
self.gameTitle = QLabel("Title")
font = self.font()
font.setPointSize(36)
font.setBold(True)
self.gameTitle.setFont(font)
self.gameDescription = QLabel("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.")
font = self.font()
font.setPointSize(20)
self.gameDescription.setFont(font)
self.gameDescription.setWordWrap(True)
self.gameDescription.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Expanding)
self.gameDescription.setAlignment(Qt.AlignmentFlag.AlignTop)
self.gameDescription.setMaximumHeight(125)
self.gameDescription.setMinimumWidth(20)
self.playButton = PlayButton('Play', self)
font = self.font()
font.setPointSize(24)
font.setBold(True)
self.playButton.setFont(font)
self.playButton.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred)
self.playButton.setMinimumWidth(150)
self.playButton.setMaximumHeight(75)
self.playButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.playButton.clicked.connect(self.playButtonClicked)
playButtonLayout = QHBoxLayout()
playButtonLayout.addWidget(self.playButton)
playButtonLayout.addStretch()
gameInfoLayout = QVBoxLayout()
gameInfoLayout.addWidget(self.gameTitle)
gameInfoLayout.addWidget(self.gameDescription)
gameInfoLayout.addStretch()
gameInfoLayout.addLayout(playButtonLayout)
gameInfoLayout.setContentsMargins(self.MAIN_CONTENT_PADDING, 0, 0, 0)
# Main layouts
mainContentsLayout = QVBoxLayout()
mainContentsLayout.addLayout(topBar)
mainContentsLayout.addLayout(gameInfoLayout)
mainContentsLayout.addWidget(self.scrollArea)
layout = QHBoxLayout()
layout.addWidget(self.sidebar)
layout.addLayout(mainContentsLayout)
layout.setContentsMargins(0, 0, 0, 0)
centralWidget = QWidget(self)
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
self.tileClicked(0)
self.scrollArea.setFocus(Qt.FocusReason.OtherFocusReason)
self.setMinimumSize(1000, 875)
self.resize(1200, 875)
self.showMaximized()
# self.showFullScreen()
def tileClicked(self, index: int, animate: bool = True) -> None:
"""Select a tile and optionally start the selection animation"""
if index == self.selectedTile:
return
if index >= self.scrollLayout.count():
return
currTile: Optional[GameTile]
if self.selectedTile is not None:
currTile = self.tiles[self.selectedTile].tile
else:
currTile = None
newTile = self.tiles[index].tile
if animate:
animationGroup = QParallelAnimationGroup()
tileAnimation: QPropertyAnimation
if currTile is not None:
# Shrink currTile and grow newTile at the same time
tileAnimation = CoupledPropertyAnimation(currTile, 'imageWidth', newTile, 'imageWidth')
tileAnimation.setStartValues(currTile.expandedImageWidth, newTile.baseImageWidth)
tileAnimation.setEndValues(currTile.baseImageWidth, newTile.expandedImageWidth)
else:
tileAnimation = QPropertyAnimation(newTile, b'imageWidth')
tileAnimation.setEndValue(newTile.expandedImageWidth)
tileAnimation.setEasingCurve(QEasingCurve.Type.InOutCubic)
tileAnimation.setDuration(100)
animationGroup.addAnimation(tileAnimation)
scrollAnimation = self.scrollArea.ensureWidgetVisibleAnimation(newTile, 200)
if scrollAnimation is not None:
animationGroup.addAnimation(scrollAnimation)
if self.runningAnimations.state() == QAbstractAnimation.State.Stopped:
# self.runningAnimations.clear() sometimes causes an error.
# This is seemingly because of over-eager garbage collection,
# see https://stackoverflow.com/a/60410713.
# So instead, we remove animations one by one.
while self.runningAnimations.animationCount() > 0:
self.runningAnimations.takeAnimation(0)
self.runningAnimations.addAnimation(animationGroup)
self.runningAnimations.start(policy=QAbstractAnimation.DeletionPolicy.KeepWhenStopped)
else:
if currTile is not None:
currTile.imageWidth = currTile.baseImageWidth # type: ignore
newTile.imageWidth = newTile.expandedImageWidth # type: ignore
self.scrollArea.ensureWidgetVisible(newTile, 200, 200)
self.selectedTile = index
self.updateGameInfo(self.tiles[index].game)
def updateGameInfo(self, game: Game) -> None:
self.gameTitle.setText(game['name'])
if 'description' not in game.keys() or game['description'] is None:
self.gameDescription.setText('No description')
else:
self.gameDescription.setText(game['description'])
if self.runningProcess is not None:
if game['id'] == self.runningProcess.id:
self.playButton.setText('Stop')
else:
self.playButton.setText('Play')
def playButtonClicked(self) -> None:
if self.playButton.text() == 'Play':
if self.selectedTile is None:
return
game = self.tiles[self.selectedTile].game
self.launchGame(game)
self.playButton.setText('Stop')
else:
assert self.runningProcess is not None, "Tried to stop non-existent RunningProcess"
self.runningProcess.process.terminate()
def launchGame(self, game: Game) -> None:
if self.runningProcess is not None:
QMessageBox.warning(self, 'Game already running', 'Please close the running game before you launch another game')
return
process = QProcess()
if game['source'] == 'steam':
process.start('steam', [f'steam://rungameid/{game["data"]["appID"]}'])
elif game['source'] == 'native':
if 'args' not in game['data'].keys():
raise AttributeError("Entry in library file missing args")
args = game['data']['args']
process.start(game['data']['filepath'], args)
self.runningProcess = RunningProcess(process, game['id'])
process.finished.connect(self.processFinished)
def processFinished(self) -> None:
self.playButton.setText('Play')
self.runningProcess = None
def sortGamesByName(self, ascending: bool = True) -> None:
self.library.games.sort(key = lambda x: x['name'], reverse = not ascending)
self.refresh()
def refresh(self, selectedTile: int = 0) -> None:
'''Refreshes game tiles'''
for gameTile in self.tiles:
self.scrollLayout.removeWidget(gameTile.tile)
gameTile.tile.deleteLater()
self.tiles = []
for i, game in enumerate(self.library.games):
image = storage.getLibraryImage(game['id'])
if image is None:
image = self.defaultImage
tile = GameTile(image, self.imageHeight, self.expandedImageHeight, self)
tile.clicked.connect(lambda i=i: self.tileClicked(i))
self.tiles.append(GameTileInfo(tile, game))
self.scrollLayout.addWidget(tile)
self.selectedTile = None
self.tileClicked(selectedTile, animate=False)
self.scrollLayout.update()
self.scrollWidget.update()
self.scrollArea.update()
def addGameClicked(self) -> None:
self.addGameWindow.show()
def keyPressEvent(self, e: QKeyEvent) -> None:
match e.key():
case Qt.Key.Key_Left:
if not self.sidebar.hasFocus():
# Don't queue a bunch of animations at once
if numAnimationsLeft(self.runningAnimations) > 1:
return
if self.selectedTile == 0 or self.selectedTile is None:
# TODO: Maybe wait until animation is finished?
# Or even better, require an extra keypress
self.sidebar.setFocus(Qt.FocusReason.OtherFocusReason)
else:
self.tileClicked(self.selectedTile - 1)
case Qt.Key.Key_Right:
if self.sidebar.hasFocus() or self.selectedTile is None:
self.tileClicked(0)
else:
# Don't queue a bunch of animations at once
if numAnimationsLeft(self.runningAnimations) > 1:
return
self.tileClicked(self.selectedTile + 1)
self.scrollArea.setFocus(Qt.FocusReason.OtherFocusReason)
case Qt.Key.Key_Up:
if self.scrollArea.hasFocus():
self.playButton.setFocus(Qt.FocusReason.OtherFocusReason)
case Qt.Key.Key_Down:
if self.playButton.hasFocus():
self.scrollArea.setFocus(Qt.FocusReason.OtherFocusReason)
case Qt.Key.Key_Return:
if self.scrollArea.hasFocus():
self.playButton.click()
case Qt.Key.Key_L:
self.playButton.setFocus(Qt.FocusReason.OtherFocusReason)
case Qt.Key.Key_K:
print(self.playButton.hasFocus())
print(self.keyboardGrabber())
return super().keyPressEvent(e)
def numAnimationsLeft(animationGroup: QSequentialAnimationGroup) -> int:
'''
Returns the total number of animations left, *including the currently running one*
'''
currAnimation = animationGroup.currentAnimation()
currIndex = animationGroup.indexOfAnimation(currAnimation)
total = animationGroup.animationCount()
return total - currIndex
class PlayButton(QPushButton):
def keyPressEvent(self, e: QKeyEvent) -> None:
if e.key() == Qt.Key.Key_Return:
self.click()
else:
e.ignore()
class AnimatedScrollArea(QScrollArea):
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
self.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
def ensureWidgetVisibleAnimation(
self, childWidget: QWidget, xMargin: int = 0, yMargin: int = 0
) -> QPropertyAnimation | None:
contentsRect = childWidget.contentsRect()
pos = childWidget.pos()
scrollBarValue: int = self.horizontalScrollBar().value()
viewWidth = self.width()
isLeft = pos.x() < scrollBarValue + xMargin
if isLeft:
xPos = pos.x() - xMargin
doScroll = (xPos < self.horizontalScrollBar().value())
else:
xPosInLayout = pos.x() + contentsRect.width() + xMargin
xPos = xPosInLayout - viewWidth
doScroll = (xPos > self.horizontalScrollBar().value())
if doScroll:
scrollAnimation = QPropertyAnimation(self.horizontalScrollBar(), b'value')
scrollAnimation.setDuration(100)
scrollAnimation.setEasingCurve(QEasingCurve.Type.InOutCubic)
scrollAnimation.setEndValue(xPos)
return scrollAnimation
else:
return None
def wheelEvent(self, e: QWheelEvent) -> None:
delta = e.angleDelta().y()
newValue = self.horizontalScrollBar().value() - delta
self.horizontalScrollBar().setValue(newValue)
def keyPressEvent(self, e: QKeyEvent) -> None:
e.ignore()
if __name__ == '__main__':
main(sys.argv)