/
dialogs.py
844 lines (632 loc) · 30.6 KB
/
dialogs.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# -*- coding: utf-8 -*-
import os
import ctypes
import time
import urllib2
import threading
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, pyqtSignal
from ctypes import byref
from win32api import *
try:
from winxpgui import *
except ImportError:
from win32gui import *
from win32gui_struct import *
import win32com.client
usr32 = ctypes.windll.user32
from widgets import IconSizeComboBox, AutoSelectAllLineEdit, OverviewRenderArea, LibraryListWidget
from steamapi import SteamApi
from util import formatTime
from entries import SteamEntry
lastdir = "."
class SteamProfileDialog(QtGui.QDialog):
FailedSteamIdQuery = pyqtSignal()
FailedPlayerSummaryQuery = pyqtSignal()
FailedAvatarDl = pyqtSignal()
InvalidUserQuery = pyqtSignal()
SuccessfulAvatarDl = pyqtSignal()
SuccessfulSteamIdQuery = pyqtSignal(str)
SuccessfulPlayerSummaryQuery = pyqtSignal(object)
class enterUsernameWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.usernameLe = QtGui.QLineEdit(self)
self.usernameLe.setFocus()
dlgNavLay = QtGui.QHBoxLayout()
self.nextBtn = QtGui.QPushButton("&Next >>", self)
self.nextBtn.setDefault(True)
self.nextBtn.clicked.connect(self.parent().UsernameEntered)
#self.okBtn.setEnabled(False)
self.cancelBtn = QtGui.QPushButton("&Cancel", self)
self.cancelBtn.clicked.connect(self.parent().reject)
dlgNavLay.addWidget(self.cancelBtn)
dlgNavLay.addStretch(1)
dlgNavLay.addWidget(self.nextBtn)
layout = QtGui.QGridLayout()
layout.addWidget(QtGui.QLabel("Please enter your Steam username (found in your profile URL):"), 0, 0, 1, 2)
layout.addWidget(QtGui.QLabel("http://steamcommunity.com/id/"), 1, 0, QtCore.Qt.AlignRight)
layout.addWidget(self.usernameLe, 1, 1)
layout.addLayout(dlgNavLay, 3, 0, 1, 2)
self.setLayout(layout)
class confirmProfileWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.avatarLbl = QtGui.QLabel()
self.nameLbl = QtGui.QLabel()
self.steamIdLbl = QtGui.QLabel()
self.lastOnlineLbl = QtGui.QLabel()
self.nextBtn = QtGui.QPushButton("&Yes", self)
self.nextBtn.setDefault(True)
self.nextBtn.setFocus()
self.nextBtn.clicked.connect(self.parent().accept)
self.backBtn = QtGui.QPushButton("<< &Back", self)
self.backBtn.clicked.connect(self.parent().BackToUsernameWdg)
self.cancelBtn = QtGui.QPushButton("&Cancel", self)
self.cancelBtn.clicked.connect(self.parent().reject)
self.downloadInfoCb = QtGui.QCheckBox("&Download profile data", self)
self.downloadInfoCb.setChecked(True)
dlgNavLay = QtGui.QHBoxLayout()
dlgNavLay.addWidget(self.cancelBtn)
dlgNavLay.addStretch(1)
dlgNavLay.addWidget(self.backBtn)
dlgNavLay.addWidget(self.nextBtn)
layout = QtGui.QGridLayout()
layout.addWidget(QtGui.QLabel("Connect to profile?"), 0, 0, 1, 2)
layout.addWidget(self.avatarLbl, 1, 0, 4, 1, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
layout.addWidget(self.nameLbl, 1, 1)
layout.addWidget(self.steamIdLbl, 2, 1)
layout.addWidget(self.lastOnlineLbl, 3, 1)
layout.addWidget(self.downloadInfoCb, 4, 1)
layout.addLayout(dlgNavLay, 5, 0, 1, 2)
layout.setRowStretch(1, 1)
self.setLayout(layout)
def Fill(self, username, playerSummary):
avatar = QtGui.QPixmap(os.path.join('cache', '%s.jpg' % playerSummary.steamid))
if avatar.isNull():
avatar = QtGui.QPixmap(os.path.join('gfx', 'noavatar.png'))
self.avatarLbl.setPixmap(avatar)
self.nameLbl.setText('<b>%s</b> (%s)' % (username, playerSummary.personaname))
self.steamIdLbl.setText('Steam ID: <b>%s</b>' % playerSummary.steamid)
if int(playerSummary.personastate) == 0:
timeStr = time.strftime('%a %d. %b %Y, %H:%M', time.localtime(float(playerSummary.lastlogoff)))
self.lastOnlineLbl.setText('Last online: <b>%s</b>' % timeStr)
else:
self.lastOnlineLbl.setText('<span style="color: green;"><b>Currently online</b></span>')
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.steamapi = SteamApi()
self.tries = 0
self.setWindowTitle("Add Steam profile")
#self.resize(370,180)
self.confirmProfileWdg = SteamProfileDialog.confirmProfileWidget(self)
self.enterUsernameWdg = SteamProfileDialog.enterUsernameWidget(self)
self.setLayout(QtGui.QStackedLayout())
self.layout().addWidget(self.enterUsernameWdg)
self.layout().addWidget(self.confirmProfileWdg)
# init connections
self.FailedSteamIdQuery.connect(self.RetrySteamIdQuery)
self.FailedPlayerSummaryQuery.connect(self.NoPlayerSummaryFound)
self.FailedAvatarDl.connect(self.AvatarNotReceived)
self.InvalidUserQuery.connect(self.InvalidUsernameDetected)
self.SuccessfulSteamIdQuery.connect(self.SteamIdReceived)
self.SuccessfulPlayerSummaryQuery.connect(self.PlayerSummaryReceived)
self.SuccessfulAvatarDl.connect(self.AvatarReceived)
def __del__(self):
self.steamapi.__del__()
def accept(self):
self.downloadProfileData = self.confirmProfileWdg.downloadInfoCb.isChecked()
QtGui.QDialog.accept(self)
def reject(self):
# disconnect all connections to not respond to any threads still working when they finish
self.FailedSteamIdQuery.disconnect()
self.FailedPlayerSummaryQuery.disconnect()
self.FailedAvatarDl.disconnect()
self.InvalidUserQuery.disconnect()
self.SuccessfulSteamIdQuery.disconnect()
self.SuccessfulPlayerSummaryQuery.disconnect()
self.SuccessfulAvatarDl.disconnect()
QtGui.QDialog.reject(self)
# shut down query thread, if it is still working
# --- not needed anymore, as this dialog is a member of the MainWindow object,
# --- it will be kept until closing the program, so the already disconnected
# --- threads have enough time to finish whatever they are currently doing.
#if hasattr(self, 'queryThread') and self.queryThread.isAlive():
# self.queryThread.join(0.1)
# if self.queryThread.isAlive():
# raise Exception('SteamProfileDialog could not shut down query thread!')
def Thread_DownloadAvatar(self, url, steamid):
try:
with open(os.path.join('cache', '%i.jpg' % steamid), 'wb') as localFile:
avatarFile = urllib2.urlopen(url, timeout=10)
localFile.write(avatarFile.read())
avatarFile.close()
except (IOError, urllib2.URLError):
self.FailedAvatarDl.emit()
return
self.SuccessfulAvatarDl.emit()
def Thread_GetSteamIdByUsername(self, username):
# start query ... this takes a while
steamid = self.steamapi.GetSteamIdByUsername(username)
if steamid is None:
self.FailedSteamIdQuery.emit()
elif steamid is SteamApi.ERR_INVALID_USER:
self.InvalidUserQuery.emit()
else:
self.SuccessfulSteamIdQuery.emit(str(steamid))
def Thread_GetPlayerSummary(self, steamid):
# start query ... this might take a bit
playerSummary = self.steamapi.GetPlayerSummary(steamid)
if playerSummary is None:
self.FailedPlayerSummaryQuery.emit()
else:
self.SuccessfulPlayerSummaryQuery.emit(playerSummary)
def BackToUsernameWdg(self):
self.CancelSteamQueries()
self.layout().setCurrentWidget(self.enterUsernameWdg)
def CancelSteamQueries(self):
self.progressBar.hide()
self.pbLbl.hide()
self.enterUsernameWdg.nextBtn.setEnabled(True)
self.enterUsernameWdg.cancelBtn.setEnabled(True)
self.enterUsernameWdg.usernameLe.setEnabled(True)
def RetrySteamIdQuery(self):
if self.tries >= 10:
self.CancelSteamQueries()
QtGui.QMessageBox.critical(self, "Error", "Could not fetch profile information.\nPlease check your internet connection and/or try again later.")
return
self.progressBar.setValue(self.tries)
self.pbLbl.setText("Please wait a moment.\nRequesting Steam ID ... (%i)" % self.tries)
self.tries += 1
self.queryThread = threading.Thread(target=self.Thread_GetSteamIdByUsername, args=(self.username,))
self.queryThread.start()
def SteamIdReceived(self, steamid):
self.progressBar.setValue(10)
self.pbLbl.setText("Found profile %s!\nFetching profile summary ..." % steamid)
self.steamId = int(steamid)
# start player summary query
self.queryThread = threading.Thread(target=self.Thread_GetPlayerSummary, args=(int(steamid),))
self.queryThread.start()
def NoPlayerSummaryFound(self):
result = QtGui.QMessageBox.critical(self, "Error", "Could not find player information for steam ID %i." % self.steamId, QtGui.QMessageBox.Retry | QtGui.QMessageBox.Cancel)
if result == QtGui.QMessageBox.Retry:
self.tries = 0
self.RetrySteamIdQuery()
elif result == QtGui.QMessageBox.Cancel:
self.CancelSteamQueries()
def InvalidUsernameDetected(self):
QtGui.QMessageBox.critical(self, "Error", "Steam did not return a profile for username %s.\nPlease check the username and try again." % self.username)
self.CancelSteamQueries()
self.enterUsernameWdg.usernameLe.selectAll()
self.enterUsernameWdg.usernameLe.setFocus()
def PlayerSummaryReceived(self, playerSummary):
self.progressBar.setValue(20)
self.pbLbl.setText("Received profile summary.\nDownloading avatar ...")
self.playerSummary = playerSummary
self.queryThread = threading.Thread(target=self.Thread_DownloadAvatar, args=(playerSummary.avatarmedium, self.steamId))
self.queryThread.start()
def AvatarReceived(self):
self.progressBar.setValue(25)
self.pbLbl.setText("Downloaded Avatar ... Proceeding.")
QtGui.qApp.processEvents()
time.sleep(0.6)
# proceed to next dialog page
self.layout().setCurrentWidget(self.confirmProfileWdg)
self.confirmProfileWdg.Fill(self.username, self.playerSummary)
self.enterUsernameWdg.nextBtn.setEnabled(True)
self.enterUsernameWdg.cancelBtn.setEnabled(True)
def AvatarNotReceived(self):
result = QtGui.QMessageBox.warning(self, "Warning", "Unable to download avatar. Please check if the folder 'cache' exists in your FireStarter directory.", QtGui.QMessageBox.Retry | QtGui.QMessageBox.Ignore | QtGui.QMessageBox.Cancel)
if result == QtGui.QMessageBox.Retry:
# try again
self.queryThread = threading.Thread(target=self.Thread_DownloadAvatar, args=(self.playerSummary.avatarmedium, self.steamId))
self.queryThread.start()
elif result == QtGui.QMessageBox.Ignore:
# proceed to next dialog page
self.layout().setCurrentWidget(self.confirmProfileWdg)
self.confirmProfileWdg.Fill(self.username, self.playerSummary)
self.enterUsernameWdg.nextBtn.setEnabled(True)
self.enterUsernameWdg.cancelBtn.setEnabled(True)
elif result == QtGui.QMessageBox.Cancel:
self.CancelSteamQueries()
return
def UsernameEntered(self):
# try to fetch profile
self.username = str(self.enterUsernameWdg.usernameLe.text())
if len(self.username) == 0:
QtGui.QMessageBox.critical(self, "Error", "Please enter a valid Steam username!")
return
self.tries = 0
#self.enterUsernameWdg.cancelBtn.setEnabled(False)
self.enterUsernameWdg.nextBtn.setEnabled(False)
self.enterUsernameWdg.usernameLe.setEnabled(False)
self.pbLbl = QtGui.QLabel("Please wait a moment.\nRequesting Steam ID ... (1)")
self.progressBar = QtGui.QProgressBar(self.enterUsernameWdg)
self.progressBar.setMaximum(30) # 0-10 = 10 tries of receiving steam ID, 10-20 = Summary, 20-25 = Avatar, 25-30 = finished
self.enterUsernameWdg.layout().addWidget(self.pbLbl, 2, 0)
self.enterUsernameWdg.layout().addWidget(self.progressBar, 2, 1)
# start query thread and return, waiting for the Thread's finished signal
self.tries += 1
self.queryThread = threading.Thread(target=self.Thread_GetSteamIdByUsername, args=(self.username,))
self.queryThread.start()
return
class ChooseIconDialog(QtGui.QDialog):
""" Dialog which loads icons from one or several files, displays them in a list widget, and allows to choose one of them.
When called with exec_(), the call returns 'None' if Cancel was pressed, otherwise it returns a tuple of (filename,id)
for the icon in 'filename' with id 'id'. """
def __init__(self, parent=None, file=None, suggestions=False):
global lastdir
QtGui.QDialog.__init__(self, parent)
self.setWindowTitle("Choose icon")
self.resize(600,380)
self.basefile = file
if self.basefile:
lastdir = os.path.dirname(self.basefile)
self.noIcon = False # only set true if 'No icon' is clicked
# create widgets
self.okBtn = QtGui.QPushButton("&Ok", self)
self.okBtn.setDefault(True)
self.okBtn.clicked.connect(self.accept)
self.okBtn.setEnabled(False)
self.noIconBtn = QtGui.QPushButton("&No icon", self)
self.noIconBtn.clicked.connect(self.ReturnNoIcon)
self.cancelBtn = QtGui.QPushButton("&Cancel", self)
self.cancelBtn.clicked.connect(self.reject)
self.cancelBtn.setFocus()
self.selectFileBtn = QtGui.QPushButton("&Select file...", self)
self.selectFileBtn.clicked.connect(self.SelectFile)
self.countLabel = QtGui.QLabel("0 icons found.")
size = QtCore.QSize(128,128)
self.iconsList = QtGui.QListWidget(self)
self.iconsList.setViewMode(QtGui.QListView.IconMode)
self.iconsList.setIconSize(size)
#self.iconsList.setGridSize(size)
self.iconsList.setMovement(QtGui.QListView.Static)
self.iconsList.itemDoubleClicked.connect(self.accept)
self.iconSizeComboBox = IconSizeComboBox(self)
self.iconSizeComboBox.IconSizeChanged.connect(self.SetIconSize)
# init layout
buttonsLayout= QtGui.QHBoxLayout()
buttonsLayout.addWidget(self.okBtn)
buttonsLayout.addWidget(self.cancelBtn)
buttonsLayout.addWidget(self.noIconBtn)
buttonsLayout.addWidget(self.selectFileBtn)
buttonsLayout.addWidget(self.countLabel)
mainLayout = QtGui.QVBoxLayout(self)
topLayout = QtGui.QHBoxLayout()
if suggestions: topLayout.addWidget(QtGui.QLabel("Suggested icons:"))
topLayout.addStretch(1)
topLayout.addWidget(self.iconSizeComboBox)
mainLayout.addLayout(topLayout)
mainLayout.addWidget(self.iconsList)
mainLayout.addLayout(buttonsLayout)
self.setLayout(mainLayout)
# fill icon list
self.Fill(file, suggestions)
self.iconsList.itemSelectionChanged.connect(self.SelectionChanged)
def exec_(self):
result = QtGui.QDialog.exec_(self)
if result == QtGui.QDialog.Accepted and self.noIcon:
return "", -1
elif result == QtGui.QDialog.Accepted and len(self.iconsList.selectedItems())==1:
icon = self.iconsList.selectedItems()[0]
return icon.file, icon.id
else: return None
def AddIcons(self, file):
iconSize = 256
# determine number of icons in file
numIcons = win32gui.ExtractIconEx(file, -1, 1)
if (numIcons == 0):
# try to load as image
icon = QtGui.QIcon(file)
id = -2
if icon is None:
return 0
else:
for id in range(numIcons):
# load icon
hIcon = ctypes.c_int()
iconId = ctypes.c_int()
# this is used instead of win32gui.ExtractIconEx because we need arbitrarily sized icons
res = usr32.PrivateExtractIconsW(ctypes.c_wchar_p(file), id, iconSize,\
iconSize, byref(hIcon), byref(iconId), 1, 0)
if (res == 0):
raise IOError("Could not extract icon #%i from file %s." % (id+1, file))
return
hIcon = hIcon.value # unpack c_int
pm = QtGui.QPixmap.fromWinHICON(hIcon)
DestroyIcon(hIcon)
icon = QtGui.QIcon()
icon.addPixmap(pm)
# add to list
listEntry = QtGui.QListWidgetItem(self.iconsList)
listEntry.setIcon(icon)
listEntry.file = os.path.abspath(file)
listEntry.id = id
# return number of successfully loaded icons
return id+1
def Fill(self, file, suggestions=False):
count = 0
if not suggestions:
count = self.AddIcons(file)
else:
for f in self.SuggestFiles(file):
count += self.AddIcons(f)
if count == 0:
QtGui.QMessageBox.warning(self, "Warning", "No icons found! Please select one or more files with icons manually.")
self.countLabel.setText("%i icon%s found." % (count, "" if count==1 else "s"))
def FillList(self, files):
count = 0
for f in files:
count += self.AddIcons(str(f)) # need to convert from QString to python string
if count == 0:
QtGui.QMessageBox.warning(self, "Warning", "No icons found! Please select one or more files with icons manually.")
self.countLabel.setText("%i icon%s found." % (count, "" if count==1 else "s"))
def ReturnNoIcon(self):
self.noIcon = True
self.accept()
def SelectFile(self):
global lastdir
if lastdir == ":" and self.basefile:
lastdir = os.path.dirname(self.basefile)
files = QtGui.QFileDialog.getOpenFileNames(self, "Select icon file(s):", lastdir,\
"Files containing images or icons (*.bmp *.png *.jpg *.gif *.exe *.dll *.ico);;All files (*.*)" )
if len(files)>0:
self.iconsList.clear()
self.FillList(files)
lastdir = os.path.dirname(str(files[0]))
def SelectionChanged(self):
self.okBtn.setEnabled(len(self.iconsList.selectedItems())==1)
def SetIconSize(self, size):
self.iconsList.setIconSize(QtCore.QSize(size, size))
def SuggestFiles(self, file):
files = []
dir = os.path.dirname(file)
dirList = os.listdir(dir) if os.path.isdir(dir) else ["."]
for f in dirList:
if os.path.join(dir,f) != file and (f.endswith(".exe") or f.endswith(".dll") or f.endswith(".ico") or f.endswith(".bmp")):
files.append(os.path.join(dir,f))
return files
class ProfileSettingsDialog(QtGui.QDialog):
def __init__(self, profile, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setWindowTitle("Profile settings")
#self.resize(300,500)
self.profile = profile
class ManualTrackingDialog(QtGui.QDialog):
AddTimeSignal = pyqtSignal(object, int)
def __init__(self, entry, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setWindowTitle(entry.label)
self.entry = entry
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.UpdateTime)
# init layout
lay = QtGui.QHBoxLayout()
picture = entry.icon.pixmap(128,128)
pictureLabel = QtGui.QLabel()
pictureLabel.setPixmap(picture)
self.setWindowIcon(entry.icon)
lay.addWidget(pictureLabel)
lay2 = QtGui.QVBoxLayout()
lay.addLayout(lay2)
descLabel = QtGui.QLabel("It seems that FireStarter was unable to track your game time for <b>%s</b>.<br>This is a common issue when a game" % entry.label
+" uses a launcher or an auto-updater.")
self.timeLabel = QtGui.QLabel("A playing time of <b>0s</b> has been tracked.")
descLabel2 = QtGui.QLabel("Once you finished playing, click <b>Add time to game</b> to<br>manually add your game time, or <b>Discard</b> to discard it.")
lay2.addWidget(descLabel)
lay2.addWidget(self.timeLabel)
lay2.addWidget(descLabel2)
btnLay = QtGui.QHBoxLayout()
self.addBtn = QtGui.QPushButton("&Add time to game")
self.addBtn.setDefault(True)
self.addBtn.clicked.connect(self.AddTime)
self.discardBtn = QtGui.QPushButton("&Discard")
self.discardBtn.clicked.connect(self.reject)
btnLay.addWidget(self.addBtn)
btnLay.addWidget(self.discardBtn)
lay2.addLayout(btnLay)
self.setLayout(lay)
# start timer
self.runtime = 0.
self.timer.start(1000)
def __del__(self):
self.timer.stop()
def AddTime(self):
self.timer.stop()
self.AddTimeSignal.emit(self.entry, self.runtime)
self.accept()
def UpdateTime(self):
self.runtime += 1.
self.timeLabel.setText("A playing time of <b>%s</b> has been tracked." % formatTime(self.runtime, escapeLt=True))
class ProfileSelectionDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.newProfile = False
self.profileName = ""
self.newProfileText = " >> New profile ..."
self.setWindowTitle("Select profile:")
self.resize(120,150)
# init children
self.profileList = QtGui.QListWidget(self)
self.profileList.addItem(self.newProfileText)
dirList = os.listdir('.')
for f in dirList:
if f.endswith(".dat"):
self.profileList.addItem(f)
self.okBtn = QtGui.QPushButton("&Ok", self)
self.okBtn.setDefault(True)
self.okBtn.setEnabled(False)
self.cancelBtn = QtGui.QPushButton("&Cancel", self)
# init layout
buttonsLayout= QtGui.QHBoxLayout()
buttonsLayout.addWidget(self.okBtn)
buttonsLayout.addWidget(self.cancelBtn)
self.layout = lay = QtGui.QVBoxLayout()
lay.addWidget(self.profileList)
lay.addLayout(buttonsLayout)
self.setLayout(lay)
# init connections
self.okBtn.clicked.connect(self.Accepted)
self.cancelBtn.clicked.connect(self.reject)
self.profileList.itemSelectionChanged.connect(self.SelectionChanged)
self.profileList.itemActivated.connect(self.Accepted)
def Accepted(self):
selectedText = str(self.profileList.selectedItems()[0].text())
if selectedText == self.newProfileText: # new profile
name,accepted = QtGui.QInputDialog.getText(self, "New profile", "Please enter a name for your new profile:", text="%s" % os.environ.get("USERNAME"))
name += ".dat"
if accepted:
self.newProfile = True
self.profileName = str(name)
self.accept()
else: # existing profile
self.newProfile = False
self.profileName = selectedText
self.accept()
def SelectionChanged(self):
self.okBtn.setEnabled(len(self.profileList.selectedItems()) == 1)
class EntryPropertiesDialog(QtGui.QDialog):
def __init__(self, entry, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setWindowTitle("Properties")
#self.resize(300,500)
self.entry = entry
# dialog flags
self.iconChanged = False # icon update necessary
# create widgets
self.okBtn = QtGui.QPushButton("&Ok", self)
self.okBtn.setDefault(True)
self.okBtn.clicked.connect(self.accept)
self.cancelBtn = QtGui.QPushButton("&Cancel", self)
self.cancelBtn.clicked.connect(self.reject)
self.labelLe = AutoSelectAllLineEdit(entry.label, self)
self.filenameLe = AutoSelectAllLineEdit(entry.filename, self)
self.chooseExecutable = QtGui.QPushButton(QtGui.QIcon(os.path.join("gfx", "folder-open-icon.png")), "")
self.cmdLineArgsLe = AutoSelectAllLineEdit(entry.cmdLineArgs, self)
self.workingDirLe = AutoSelectAllLineEdit(entry.workingDir, self)
self.chooseWorkingDir = QtGui.QPushButton(QtGui.QIcon(os.path.join("gfx", "folder-open-icon.png")), "")
iconTxt = "\"" + entry.iconPath + "\",%i" % entry.preferredIcon if entry.preferredIcon > -1 else "-"
self.iconLe = AutoSelectAllLineEdit(iconTxt)
self.chooseIcon = QtGui.QPushButton(QtGui.QIcon(os.path.join("gfx", "folder-open-icon.png")), "")
# init layout
buttonsLayout= QtGui.QHBoxLayout()
buttonsLayout.addWidget(self.okBtn)
buttonsLayout.addWidget(self.cancelBtn)
formLayout = QtGui.QGridLayout()
formLayout.addWidget(QtGui.QLabel("Name:"), 0, 0)
formLayout.addWidget(self.labelLe, 0, 1, 1, 2)
formLayout.addWidget(QtGui.QLabel("Executable:"), 1, 0)
formLayout.addWidget(self.filenameLe, 1, 1, 1, 1)
formLayout.addWidget(self.chooseExecutable, 1, 2, 1, 1)
formLayout.addWidget(QtGui.QLabel("Additional arguments:"), 2, 0)
formLayout.addWidget(self.cmdLineArgsLe, 2, 1, 1, 2)
formLayout.addWidget(QtGui.QLabel("Working directory:"), 3, 0)
formLayout.addWidget(self.workingDirLe, 3, 1, 1, 1)
formLayout.addWidget(self.chooseWorkingDir, 3, 2, 1, 1)
formLayout.addWidget(QtGui.QLabel("Icon:"), 4, 0)
formLayout.addWidget(self.iconLe, 4, 1, 1, 1)
formLayout.addWidget(self.chooseIcon, 4, 2, 1, 1)
#formLayout.addRow("Name:", self.labelLe)
#formLayout.addRow("Executable:", self.filenameLe)
#formLayout.addRow("Additional arguments:", self.cmdLineArgsLe)
#formLayout.addRow("Working directory:", self.workingDirLe)
#formLayout.addRow("Icon path:", iconWdg)
mainLayout = QtGui.QVBoxLayout()
mainLayout.addLayout(formLayout)
mainLayout.addLayout(buttonsLayout)
self.setLayout(mainLayout)
self.InitConnections()
def exec_(self):
""" If the icon has been changed, return the new icon path """
result = QtGui.QDialog.exec_(self)
if result == QtGui.QDialog.Accepted:
self.entry.label = str(self.labelLe.text())
self.entry.filename = str(self.filenameLe.text())
self.entry.workingDir = str(self.workingDirLe.text())
self.entry.cmdLineArgs = str(self.cmdLineArgsLe.text())
if self.iconChanged:
self.entry.iconPath = self.newIconPath
self.entry.preferredIcon = self.newIconId
self.entry.LoadIcon()
self.entry.UpdateIcon.emit()
self.entry.UpdateText.emit()
self.entry.UpdateProfile.emit()
return result
def ChangeExecutable(self):
file = QtGui.QFileDialog.getOpenFileName(self, "Choose executable:", self.filenameLe.text(), "Executable files (*.exe)")
if file != "":
self.filenameLe.setText(file)
self.workingDirLe.setText(os.path.dirname(str(file)))
def ChangeIcon(self):
dlg = ChooseIconDialog(self, file=self.entry.iconPath, suggestions=True)
result = dlg.exec_()
if result == None: return
else:
path, id = result
if self.entry.iconPath != path or self.entry.preferredIcon != id:
self.newIconPath = path
self.newIconId = id
self.iconChanged = True
self.changed = True
iconTxt = "\"" + path + "\",%i" % id if id > -1 else "-"
self.iconLe.setText(iconTxt)
def ChangeWorkingDir(self):
wd = QtGui.QFileDialog.getExistingDirectory(self, "Choose working directory:", self.workingDirLe.text())
if wd != "":
self.workingDirLe.setText(wd)
def InitConnections(self):
self.chooseIcon.clicked.connect(self.ChangeIcon)
self.chooseExecutable.clicked.connect(self.ChangeExecutable)
self.chooseWorkingDir.clicked.connect(self.ChangeWorkingDir)
class StatsOverviewDialog(QtGui.QMainWindow):
def __init__(self, entries, parent=None, steamGames=[]):
QtGui.QMainWindow.__init__(self, parent)
self.setWindowTitle(u"Games overview")
self.resize(645,640) # width 645 magic number
games = []
games.extend(entries)
games.extend(steamGames)
self.entries = sorted(games, key=lambda entry: entry.totalTime, reverse=True)
self.InitLayout()
self.InitConnections()
def InitLayout(self):
self.ra = OverviewRenderArea(self.entries, self)
self.toolBar = QtGui.QToolBar()
sc = "Ctrl+S"
saveViewShortcut = QtGui.QKeySequence(sc)
self.saveAct = QtGui.QAction(QtGui.QIcon('gfx/save.png'), "Bild speichern (%s)" % sc.replace("Ctrl", "Strg"), self)
self.saveAct.setShortcut(saveViewShortcut)
self.toolBar.addAction(self.saveAct)
sa = QtGui.QScrollArea()
sa.setBackgroundRole(QtGui.QPalette.Shadow)
sa.setAutoFillBackground(True)
sa.setWidget(self.ra)
sa.setAlignment(Qt.AlignCenter)
self.setCentralWidget(sa)
self.addToolBar(self.toolBar)
def InitConnections(self):
self.saveAct.triggered.connect(self.SaveImage)
def SaveImage(self):
pm = QtGui.QPixmap.grabWidget(self.ra)
filename = QtGui.QFileDialog.getSaveFileName(self, "Save image...", "export", "Images (*.png *.jpg *.gif *.bmp);;All files (*.*)")
if filename != "":
pm.save(filename, format=None, quality=100)
# def ChangeZoom(self, zoomlevel):
# zoom = self.zoomSlider.steps[zoomlevel]
# self.zoomLbl.setText("%i%%" % int(100.*zoom))
# self.ra.SetZoom(zoom)
# self.ra.repaint()
class ManageLibraryDialog(QtGui.QDialog):
def __init__(self, entries, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setWindowTitle("Manage library")
self.resize(640,640)
lay = QtGui.QVBoxLayout()
self.libWdg = LibraryListWidget()
self.libWdg.Fill(entries)
lay.addWidget(self.libWdg)
self.setLayout(lay)
def exec_(self):
QtGui.QDialog.exec_(self)
print self.libWdg.modifications