forked from FluffyMaguro/SC2_Coop_Overlay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSCO.py
1217 lines (1002 loc) · 53.8 KB
/
SCO.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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main module for StarCraft II Co-op Overlay.
Causal chain:
Setup -> Load Settings -> UI
-> Server manager for websockets (thread)
-> Check replays (loop of threads)
-> Twitch bot (thread)
-> Mass replay analysis -> checking for new games (thread)
-> Generate stats (function)
-> keyboard threads (keyboard module)
-> thread for checking wake status
This is my first big project, so there is a mix of very old code and new one.
Overall it's messy with a lot of coupling, not enough separation between UI and
core functinality, and similar issues. It's a great learning experience nevertheless.
"""
import importlib
import json
import os
import platform
import shutil
import sys
import threading
import traceback
import urllib.request
from datetime import datetime
from functools import partial
from multiprocessing import freeze_support
from types import TracebackType
from typing import Type
import keyboard
from PyQt5 import QtCore, QtGui, QtWidgets
import SCOFunctions.AppFunctions as AF
import SCOFunctions.HelperFunctions as HF
import SCOFunctions.MainFunctions as MF
import SCOFunctions.MassReplayAnalysis as MR
import SCOFunctions.MUserInterface as MUI
import SCOFunctions.Tabs as Tabs
from SCOFunctions.FastExpand import FastExpandSelector
from SCOFunctions.MChatWidget import ChatWidget
from SCOFunctions.MFilePath import innerPath, truePath
from SCOFunctions.MLogging import Logger, catch_exceptions
from SCOFunctions.MSystemInfo import SystemInfo
from SCOFunctions.MTheming import MColors, set_dark_theme
from SCOFunctions.MTwitchBot import TwitchBot
from SCOFunctions.Settings import Setting_manager as SM
logger = Logger('SCO', Logger.levels.INFO)
Logger.file_path = truePath("Logs.txt")
APPVERSION = 247
def excepthook(exc_type: Type[BaseException], exc_value: Exception, exc_tback: TracebackType):
""" Provides the top-most exception handling. Logs unhandled exceptions and cleanly shuts down the app."""
# Log the exception
try:
s = "".join(traceback.format_exception(exc_type, exc_value, exc_tback))
logger.error(f"Unhandled exception!\n{s}")
except Exception:
logger.error("Failed to log error!!!")
# Try to save settings
try:
ui.saveSettings()
except Exception:
logger.error("Failed to save settings.")
# Shut down other threads
try:
TabWidget.tray_icon.hide()
ui.stop_full_analysis()
MF.stop_threads()
except Exception:
logger.error("Failed to order the app to stop checking api")
sys.exit()
sys.excepthook = excepthook
class Signal_Manager(QtCore.QObject):
"""
Small object for emiting signals.
Through this object non-PyQt threads can safely interact with PyQt.
Threads can emit signals, e.g.: signal_manager.showHidePerfOverlay.emit() and
and some method connected to this signal will be called in the primary
PyQt thread.
"""
showHidePerfOverlay = QtCore.pyqtSignal()
class MultipleInstancesRunning(Exception):
""" Custom exception for multiple instance of the app running"""
pass
class UI_TabWidget(object):
def setupUI(self, TabWidget: MUI.CustomQTabWidget):
TabWidget.setWindowTitle(f"StarCraft Co-op Overlay (v{str(APPVERSION)[0]}.{str(APPVERSION)[1:]})")
TabWidget.setWindowIcon(QtGui.QIcon(innerPath('src/OverlayIcon.ico')))
TabWidget.setFixedSize(980, 610)
TabWidget.tray_icon.setToolTip(f'StarCraft Co-op Overlay')
self.signal_manager = Signal_Manager()
self.signal_manager.showHidePerfOverlay.connect(self.show_hide_performance_overlay)
self.write_permissions = True
# Tabs
self.TAB_Main = Tabs.MainTab(self, APPVERSION)
self.TAB_Players = Tabs.PlayerTab(self, TabWidget)
self.TAB_Games = Tabs.GameTab(self, TabWidget)
self.TAB_Stats = Tabs.StatsTab(self)
self.TAB_Randomizer = Tabs.RngTab(self)
self.TAB_TwitchBot = Tabs.TwitchTab(self)
self.TAB_Resources = Tabs.ResourceTab(self)
self.TAB_Links = Tabs.LinkTab(self)
self.TAB_Mutations = Tabs.MutationTab(TabWidget)
# Add tabs to the widget
TabWidget.addTab(self.TAB_Main, "Settings")
TabWidget.addTab(self.TAB_Games, "Games")
TabWidget.addTab(self.TAB_Players, "Players")
TabWidget.addTab(self.TAB_Mutations, "Weeklies")
TabWidget.addTab(self.TAB_Stats, "Statistics")
TabWidget.addTab(self.TAB_Randomizer, "Randomizer")
TabWidget.addTab(self.TAB_TwitchBot, "Twitch")
TabWidget.addTab(self.TAB_Resources, "Performance")
TabWidget.addTab(self.TAB_Links, "Links")
QtCore.QMetaObject.connectSlotsByName(TabWidget)
if not AF.isWindows():
self.TAB_Main.CH_StartWithWindows.setChecked(False)
self.TAB_Main.CH_StartWithWindows.setEnabled(False)
self.FastExpandSelector = None
self.CAnalysis = None
def loadSettings(self):
""" Loads settings from the config file if there is any, updates UI elements accordingly"""
self.downloading = False
SM.load_settings(truePath('Settings.json'))
# Check for multiple instances
if SM.settings['check_for_multiple_instances'] and AF.isWindows():
if HF.app_running_multiple_instances():
logger.error('App running at multiple instances. Closing!')
raise MultipleInstancesRunning
# Update fix font size
font = QtGui.QFont()
if AF.isWindows():
font.fromString(f"MS Shell Dlg 2,{8.25*SM.settings['font_scale']},-1,5,50,0,0,0,0,0")
else:
font.setPointSize(font.pointSize() * SM.settings['font_scale'])
app.setFont(font)
# Charts
SM.width_for_graphs()
# Dark theme
if SM.settings['dark_theme']:
set_dark_theme(self, app, TabWidget, APPVERSION)
# Check if account directory valid, update if not
SM.settings['account_folder'] = HF.get_account_dir(SM.settings['account_folder'])
# Screenshot folder
if SM.settings['screenshot_folder'] in {None, ''} or not os.path.isdir(SM.settings['screenshot_folder']):
SM.settings['screenshot_folder'] = os.path.normpath(os.path.join(os.path.expanduser('~'), 'Desktop'))
self.updateUI()
self.check_for_updates()
if SM.settings['start_minimized']:
TabWidget.hide()
TabWidget.show_minimize_message()
else:
TabWidget.show()
# Check write permissions
self.write_permissions = HF.write_permission_granted()
if not self.write_permissions:
self.sendInfoMessage('Permission denied. Add an exception to your anti-virus for this folder. Sorry', color=MColors.msg_failure)
Logger.LOGGING = SM.settings['enable_logging'] if self.write_permissions else False
self.manage_keyboard_threads()
self.full_analysis_running = False
# Delete install bat if it's there. Show patchnotes
if os.path.isfile(truePath('install.bat')):
os.remove(truePath('install.bat'))
self.show_patchnotes()
def show_patchnotes(self):
""" Shows a widget with the lastest patchnotes.
Usually shown only after an update (after deleting install.bat)"""
try:
file = innerPath('src/patchnotes.json')
if not os.path.isfile(file):
return
with open(file, 'r') as f:
patchnotes = json.load(f)
patchnotes = patchnotes.get(str(APPVERSION), None)
if patchnotes is None:
return
if len(patchnotes) == 0:
return
self.WD_patchnotes = MUI.PatchNotes(APPVERSION, patchnotes=patchnotes, icon=QtGui.QIcon(innerPath('src/OverlayIcon.ico')))
except Exception:
logger.error(traceback.format_exc())
def check_for_updates(self):
""" Checks for updates and changes UI accordingly"""
# Skip if there is already a button (perhaps we have awoken and there is still an update ready)
if hasattr(self, "BT_NewUpdate"):
return
self.new_version = HF.new_version(APPVERSION)
if not self.new_version:
return
TabWidget.show_update_message()
self.TAB_Main.LA_Version.setText('New version available!')
# Create button
self.BT_NewUpdate = QtWidgets.QPushButton(self.TAB_Main)
self.BT_NewUpdate.setGeometry(QtCore.QRect(351, 400, 157, 40))
self.BT_NewUpdate.setText('Download update')
self.BT_NewUpdate.setStyleSheet('font-weight: bold; background-color: #5BD3C4; color: black')
self.BT_NewUpdate.clicked.connect(self.start_download)
self.BT_NewUpdate.show()
# Check if it's already downloaded
save_path = truePath(f'Updates\\{self.new_version["link"].split("/")[-1]}')
if not AF.isWindows():
self.sendInfoMessage('Update available', color=MColors.msg_success)
return
if os.path.isfile(save_path):
self.update_is_ready_for_install()
else:
self.PB_download = QtWidgets.QProgressBar(self.TAB_Main)
self.PB_download.setGeometry(21, 569, 830, 10)
self.PB_download.hide()
def start_download(self):
""" Starts downloading an update"""
if self.downloading:
return
self.downloading = True
self.BT_NewUpdate.setText('Downloading')
self.BT_NewUpdate.setEnabled(False)
self.BT_NewUpdate.setStyleSheet('font-weight: bold; background-color: #CCCCCC')
self.BT_NewUpdate.clicked.disconnect()
self.PB_download.show()
if not os.path.isdir(truePath('Updates')):
os.mkdir(truePath('Updates'))
save_path = truePath(f'Updates\\{self.new_version["link"].split("/")[-1]}')
urllib.request.urlretrieve(self.new_version["link"], save_path, self.download_progress_bar_updater)
def download_progress_bar_updater(self, blocknum, blocksize, totalsize):
""" Updates the progress bar accordingly"""
readed_data = blocknum * blocksize
if totalsize > 0:
download_percentage = readed_data * 100 / totalsize
self.PB_download.setValue(int(download_percentage))
QtWidgets.QApplication.processEvents()
if download_percentage >= 100:
self.update_is_ready_for_install()
self.downloading = False
def update_is_ready_for_install(self):
""" Changes button text and connect it to another function"""
self.BT_NewUpdate.setText('Restart and update')
self.BT_NewUpdate.setEnabled(True)
self.BT_NewUpdate.setStyleSheet('font-weight: bold; background-color: #5BD3C4; color: black')
try:
self.BT_NewUpdate.clicked.disconnect()
except Exception:
pass
self.BT_NewUpdate.clicked.connect(self.install_update)
def install_update(self):
""" Starts the installation """
archive = truePath(f'Updates\\{self.new_version["link"].split("/")[-1]}')
where_to_extract = truePath('Updates\\New')
app_folder = truePath('')
# Check hash
file_hash = HF.get_hash(archive, sha=True)
if self.new_version["hash"] != file_hash:
os.remove(archive)
logger.error(f'Incorrect hash: {self.new_version["hash"]} != {file_hash}')
self.sendInfoMessage("Error! Incorrect hash for the downloaded archive.", color=MColors.msg_failure)
self.BT_NewUpdate.clicked.disconnect()
self.BT_NewUpdate.clicked.connect(self.start_download)
self.BT_NewUpdate.setText('Download update')
return
# Delete previously extracted archive
if os.path.isdir(where_to_extract):
shutil.rmtree(where_to_extract)
# Extract archive
HF.extract_archive(archive, where_to_extract)
# Create and run install.bat file
installfile = truePath('install.bat')
with open(installfile, 'w') as f:
f.write('\n'.join(('@echo off',
'echo Installation will start shortly...',
'timeout /t 7 /nobreak > NUL',
# Copy files
f'robocopy "{where_to_extract}" "{os.path.abspath(app_folder)}" /E',
'timeout /t 7 /nobreak > NUL',
# Remove old directory
f'rmdir /s /q "{truePath("Updates")}"',
'echo Installation completed...',
# Start application
f'"{truePath("SCO.exe")}"'
))) # yapf: disable
self.saveSettings()
os.startfile(installfile)
app.quit()
def updateUI(self):
""" Update UI elements based on the current settings """
self.TAB_Main.CH_StartWithWindows.setChecked(SM.settings['start_with_windows'])
self.TAB_Main.CH_StartMinimized.setChecked(SM.settings['start_minimized'])
self.TAB_Main.CH_EnableLogging.setChecked(SM.settings['enable_logging'])
self.TAB_Main.CH_ShowPlayerWinrates.setChecked(SM.settings['show_player_winrates'])
self.TAB_Main.CH_ForceHideOverlay.setChecked(SM.settings['force_hide_overlay'])
self.TAB_Main.CH_ShowCharts.setChecked(SM.settings['show_charts'])
self.TAB_Main.CH_DarkTheme.setChecked(SM.settings['dark_theme'])
self.TAB_Main.CH_FastExpand.setChecked(SM.settings['fast_expand'])
self.TAB_Main.CH_MinimizeToTray.setChecked(SM.settings['minimize_to_tray'])
self.TAB_Main.CH_MinimizeToTray.stateChanged.connect(self.saveSettings)
self.TAB_Main.SP_Duration.setProperty("value", SM.settings['duration'])
self.TAB_Main.SP_Monitor.setProperty("value", SM.settings['monitor'])
self.TAB_Main.LA_CurrentReplayFolder.setText(SM.settings['account_folder'])
self.TAB_Main.LA_ScreenshotLocation.setText(SM.settings['screenshot_folder'])
self.TAB_Main.CH_ShowSession.setChecked(SM.settings['show_session'])
self.TAB_Main.KEY_ShowHide.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['hotkey_show/hide']))
self.TAB_Main.KEY_Show.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['hotkey_show']))
self.TAB_Main.KEY_Hide.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['hotkey_hide']))
self.TAB_Main.KEY_Newer.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['hotkey_newer']))
self.TAB_Main.KEY_Older.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['hotkey_older']))
self.TAB_Main.KEY_Winrates.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['hotkey_winrates']))
self.TAB_Main.ED_AomAccount.setText(SM.settings['aom_account'])
self.TAB_Main.ED_AomSecretKey.setText(SM.settings['aom_secret_key'])
self.TAB_Main.LA_P1.setText(f"Player 1 | {SM.settings['color_player1']}")
self.TAB_Main.LA_P1.setStyleSheet(f"background-color: {SM.settings['color_player1']}; color: black")
self.TAB_Main.LA_P2.setText(f"Player 2 | {SM.settings['color_player2']}")
self.TAB_Main.LA_P2.setStyleSheet(f"background-color: {SM.settings['color_player2']}; color: black")
self.TAB_Main.LA_Amon.setText(f" Amon | {SM.settings['color_amon']}")
self.TAB_Main.LA_Amon.setStyleSheet(f"background-color: {SM.settings['color_amon']}; color: black")
self.TAB_Main.LA_Mastery.setText(f"Mastery | {SM.settings['color_mastery']}")
self.TAB_Main.LA_Mastery.setStyleSheet(f"background-color: {SM.settings['color_mastery']}; color: black")
self.TAB_Randomizer.FR_RNG_Overlay.setChecked(SM.settings['show_random_on_overlay'])
self.TAB_TwitchBot.ch_twitch.setChecked(SM.settings['twitchbot']['auto_start'])
self.TAB_TwitchBot.ch_twitch_chat.setChecked(SM.settings['show_chat'])
self.TAB_TwitchBot.ED_twitch_channel_name.setText(SM.settings['twitchbot']['channel_name'])
self.TAB_Resources.ch_performance_show.setChecked(SM.settings['performance_show'])
self.TAB_Resources.KEY_Performance.setKeySequence(QtGui.QKeySequence.fromString(SM.settings['performance_hotkey']))
self.TAB_Stats.CH_FA_atstart.setChecked(SM.settings['full_analysis_atstart'])
# RNG choices
self.TAB_Randomizer.load_choices(SM.settings['rng_choices'])
def saveSettings(self):
""" Saves main settings in the settings file. """
previous_settings = SM.settings.copy()
self.save_playernotes_to_settings()
SM.settings['start_with_windows'] = self.TAB_Main.CH_StartWithWindows.isChecked()
SM.settings['start_minimized'] = self.TAB_Main.CH_StartMinimized.isChecked()
SM.settings['enable_logging'] = self.TAB_Main.CH_EnableLogging.isChecked()
SM.settings['show_player_winrates'] = self.TAB_Main.CH_ShowPlayerWinrates.isChecked()
SM.settings['force_hide_overlay'] = self.TAB_Main.CH_ForceHideOverlay.isChecked()
SM.settings['show_charts'] = self.TAB_Main.CH_ShowCharts.isChecked()
SM.settings['dark_theme'] = self.TAB_Main.CH_DarkTheme.isChecked()
SM.settings['fast_expand'] = self.TAB_Main.CH_FastExpand.isChecked()
SM.settings['minimize_to_tray'] = self.TAB_Main.CH_MinimizeToTray.isChecked()
SM.settings['show_session'] = self.TAB_Main.CH_ShowSession.isChecked()
SM.settings['duration'] = self.TAB_Main.SP_Duration.value()
SM.settings['monitor'] = self.TAB_Main.SP_Monitor.value()
self.check_to_remove_hotkeys()
SM.settings['hotkey_show/hide'] = self.TAB_Main.KEY_ShowHide.get_hotkey_string()
SM.settings['hotkey_show'] = self.TAB_Main.KEY_Show.get_hotkey_string()
SM.settings['hotkey_hide'] = self.TAB_Main.KEY_Hide.get_hotkey_string()
SM.settings['hotkey_newer'] = self.TAB_Main.KEY_Newer.get_hotkey_string()
SM.settings['hotkey_older'] = self.TAB_Main.KEY_Older.get_hotkey_string()
SM.settings['hotkey_winrates'] = self.TAB_Main.KEY_Winrates.get_hotkey_string()
SM.settings['aom_account'] = self.TAB_Main.ED_AomAccount.text()
SM.settings['aom_secret_key'] = self.TAB_Main.ED_AomSecretKey.text()
SM.settings['twitchbot']['auto_start'] = self.TAB_TwitchBot.ch_twitch.isChecked()
SM.settings['twitchbot']['channel_name'] = self.TAB_TwitchBot.ED_twitch_channel_name.text()
SM.settings['full_analysis_atstart'] = self.TAB_Stats.CH_FA_atstart.isChecked()
SM.settings['show_random_on_overlay'] = self.TAB_Randomizer.FR_RNG_Overlay.isChecked()
SM.width_for_graphs()
SM.settings['show_chat'] = self.TAB_TwitchBot.ch_twitch_chat.isChecked()
if hasattr(self, 'chat_widget'):
SM.settings['chat_geometry'] = [
self.chat_widget.pos().x(),
self.chat_widget.pos().y(),
self.chat_widget.width(), self.chat_widget.height()
]
SM.settings['performance_show'] = self.TAB_Resources.ch_performance_show.isChecked()
SM.settings['performance_hotkey'] = self.TAB_Resources.KEY_Performance.keySequence().toString()
if hasattr(self, 'performance_overlay'):
SM.settings['performance_geometry'] = [
self.performance_overlay.pos().x(),
self.performance_overlay.pos().y(),
self.performance_overlay.width(),
self.performance_overlay.height()
]
# RNG choices
SM.settings['rng_choices'] = self.TAB_Randomizer.get_choices()
# Save settings
SM.save_settings()
# Message
self.sendInfoMessage('Settings applied')
# Check for overlapping hoykeys
hotkeys = [
SM.settings['performance_hotkey'], SM.settings['hotkey_show/hide'], SM.settings['hotkey_show'], SM.settings['hotkey_hide'],
SM.settings['hotkey_newer'], SM.settings['hotkey_older'], SM.settings['hotkey_winrates']
]
hotkeys = [h for h in hotkeys if not h in {None, ''}]
if len(hotkeys) > len(set(hotkeys)):
self.sendInfoMessage('Warning: Overlapping hotkeys!', color=MColors.msg_failure)
# Logging
Logger.LOGGING = SM.settings['enable_logging'] if self.write_permissions else False
# Update settings for other threads
MF.update_init_message()
# Compare
changed_keys = set()
for key in previous_settings:
if previous_settings[key] != SM.settings[key] and not (previous_settings[key] is None and SM.settings[key] == ''):
if key == 'aom_secret_key':
logger.info(f'Changed: {key}: ... → ...')
else:
logger.info(f'Changed: {key}: {previous_settings[key]} → {SM.settings[key]}')
changed_keys.add(key)
# Registry
if 'start_with_windows' in changed_keys:
out = HF.add_to_startup(SM.settings['start_with_windows'])
if out is not None:
self.sendInfoMessage(f'Warning: {out}', color=MColors.msg_failure)
SM.settings['start_with_windows'] = False
self.TAB_Main.CH_StartWithWindows.setChecked(SM.settings['start_with_windows'])
# Resend init message if duration has changed. Colors are handle in color picker.
if 'duration' in changed_keys:
MF.resend_init_message()
# Monitor update
if 'monitor' in changed_keys and hasattr(self, 'WebView'):
self.set_WebView_size_location(SM.settings['monitor'])
# Update keyboard threads
self.manage_keyboard_threads(previous_settings=previous_settings)
# Show/hide overlay
if hasattr(self, 'WebView') and SM.settings['force_hide_overlay'] and self.WebView.isVisible():
self.WebView.hide()
elif hasattr(self, 'WebView') and not SM.settings['force_hide_overlay'] and not self.WebView.isVisible():
self.WebView.show()
def hotkey_changed(self):
""" Wait a bit for the sequence to update, and then check if not to delete the key"""
self.wait_ms(50)
try:
self.check_to_remove_hotkeys()
except Exception:
logger.error(traceback.format_exc())
def check_to_remove_hotkeys(self):
""" Checks if a key is 'Del' and sets it to None """
key_dict = {
self.TAB_Main.KEY_ShowHide: 'hotkey_show/hide',
self.TAB_Main.KEY_Show: 'hotkey_show',
self.TAB_Main.KEY_Hide: 'hotkey_hide',
self.TAB_Main.KEY_Newer: 'hotkey_newer',
self.TAB_Main.KEY_Older: 'hotkey_older',
self.TAB_Main.KEY_Winrates: 'hotkey_winrates',
self.TAB_Resources.KEY_Performance: 'performance_hotkey'
}
for key in key_dict:
if key.keySequence().toString() == 'Del':
key.setKeySequence(QtGui.QKeySequence.fromString(""))
logger.info(f"Removed key for {key_dict[key]}")
self.saveSettings()
break
def manage_keyboard_threads(self, previous_settings=None):
""" Compares previous settings with current ones, and restarts keyboard threads if necessary.
if `previous_settings` is None, then init hotkeys instead """
hotkey_func_dict = {
'performance_hotkey': self.signal_manager.showHidePerfOverlay.emit,
'hotkey_show/hide': MF.keyboard_SHOWHIDE,
'hotkey_show': MF.keyboard_SHOW,
'hotkey_hide': MF.keyboard_HIDE,
'hotkey_newer': MF.keyboard_NEWER,
'hotkey_older': MF.keyboard_OLDER,
'hotkey_winrates': MF.keyboard_PLAYERWINRATES
}
# Init
if previous_settings is None:
self.hotkey_hotkey_dict = dict()
for key in hotkey_func_dict:
if not SM.settings[key] in {None, ''}:
try:
self.hotkey_hotkey_dict[key] = keyboard.add_hotkey(SM.settings[key], hotkey_func_dict[key])
except Exception:
logger.error(traceback.format_exc())
self.sendInfoMessage(f'Failed to initialize hotkey ({key.replace("hotkey_","")})! Try a different one.',
color=MColors.msg_failure)
# Update
else:
for key in hotkey_func_dict:
# Update current value if the hotkey changed
if previous_settings[key] != SM.settings[key] and not SM.settings[key] in {None, ''}:
if key in self.hotkey_hotkey_dict:
keyboard.remove_hotkey(self.hotkey_hotkey_dict[key])
try:
self.hotkey_hotkey_dict[key] = keyboard.add_hotkey(SM.settings[key], hotkey_func_dict[key])
logger.info(f'Changed hotkey of {key} to {SM.settings[key]}')
except Exception:
logger.error(f'Failed to change hotkey {key}\n{traceback.format_exc()}')
# Remove current hotkey no value
elif SM.settings[key] in {None, ''} and key in self.hotkey_hotkey_dict:
try:
keyboard.remove_hotkey(self.hotkey_hotkey_dict[key])
del self.hotkey_hotkey_dict[key]
logger.info(f'Removing hotkey of {key}')
except Exception:
logger.error(f'Failed to remove hotkey {key}\n{traceback.format_exc()}')
def resetSettings(self):
""" Resets settings to default values and updates UI """
previous_settings = SM.settings.copy()
SM.settings = SM.default_settings.copy()
SM.settings['account_folder'] = HF.get_account_dir(path=SM.settings['account_folder'])
SM.settings['screenshot_folder'] = previous_settings['screenshot_folder']
SM.settings['aom_account'] = self.TAB_Main.ED_AomAccount.text()
SM.settings['aom_secret_key'] = self.TAB_Main.ED_AomSecretKey.text()
SM.settings['player_notes'] = previous_settings['player_notes']
SM.settings['twitchbot'] = previous_settings['twitchbot']
self.updateUI()
self.saveSettings()
self.sendInfoMessage('All settings have been reset!')
MF.update_init_message()
MF.resend_init_message()
self.manage_keyboard_threads(previous_settings=previous_settings)
def chooseScreenshotFolder(self):
""" Changes screenshot folder location """
dialog = QtWidgets.QFileDialog()
dialog.setDirectory(SM.settings['screenshot_folder'])
dialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly)
if dialog.exec_():
folder = os.path.normpath(dialog.selectedFiles()[0])
logger.info(f'Changing screenshot_folder to {folder}')
self.TAB_Main.LA_ScreenshotLocation.setText(folder)
SM.settings['screenshot_folder'] = folder
self.sendInfoMessage(f'Screenshot folder set succesfully! ({folder})', color=MColors.msg_success)
def findReplayFolder(self):
""" Finds and sets account folder """
dialog = QtWidgets.QFileDialog()
if not SM.settings['account_folder'] in {None, ''}:
dialog.setDirectory(SM.settings['account_folder'])
dialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly)
if dialog.exec_():
folder = dialog.selectedFiles()[0]
if 'StarCraft' in folder and '/Accounts' in folder:
logger.info(f'Changing accountdir to {folder}')
SM.settings['account_folder'] = folder
self.TAB_Main.LA_CurrentReplayFolder.setText(folder)
self.sendInfoMessage(f'Account folder set succesfully! ({folder})', color=MColors.msg_success)
MF.update_names_and_handles(folder, MF.AllReplays)
if self.CAnalysis is not None:
self.updating_maps = QtWidgets.QWidget()
self.updating_maps.setWindowTitle('Adding replays')
self.updating_maps.setGeometry(700, 500, 300, 100)
self.updating_maps.setWindowIcon(QtGui.QIcon(innerPath('src/OverlayIcon.ico')))
self.updating_maps_label = QtWidgets.QLabel(self.updating_maps)
self.updating_maps_label.setGeometry(QtCore.QRect(10, 10, 280, 80))
self.updating_maps_label.setText('<b>Please wait</b><br><br>You might need to restart for the game list and stats to update.')
self.updating_maps_label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
self.updating_maps_label.setWordWrap(True)
self.updating_maps.show()
self.CAnalysis.update_accountdir(folder)
self.updating_maps.hide()
self.TAB_Stats.generate_stats()
self.update_winrate_data()
else:
self.sendInfoMessage('Invalid account folder!', color=MColors.msg_failure)
def create_reset_overlay(self):
""" Creates or resets the webwidget overlay"""
# Hide and delete old web windget if we are resetting
if hasattr(self, "WebView"):
logger.info("Resetting overlay")
self.WebView.hide()
self.WebView.deleteLater()
# Custom CSS/JS
if not os.path.isfile(truePath('Layouts/custom.css')):
with open(truePath('Layouts/custom.css'), 'w') as f:
f.write('/* insert custom css here */')
if not os.path.isfile(truePath('Layouts/custom.js')):
with open(truePath('Layouts/custom.js'), 'w') as f:
f.write('// insert custom javascript here')
# Load overlay
if not os.path.isfile(truePath('Layouts/Layout.html')):
self.sendInfoMessage("Error! Failed to locate the html file", color=MColors.msg_failure)
logger.error("Error! Failed to locate the html file")
return
self.WebView = MUI.CustomWebView()
self.WebView.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowTransparentForInput | QtCore.Qt.WindowStaysOnTopHint
| eval(f"QtCore.Qt.{SM.settings['webflag']}") | QtCore.Qt.NoDropShadowWindowHint
| QtCore.Qt.WindowDoesNotAcceptFocus)
self.WebView.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.WebPage = MUI.WebEnginePage(self.WebView)
self.WebView.setPage(self.WebPage)
self.WebPage.setBackgroundColor(QtCore.Qt.transparent)
self.set_WebView_size_location(SM.settings['monitor'])
self.WebView.load(QtCore.QUrl().fromLocalFile(truePath('Layouts/Layout.html')))
if not SM.settings['force_hide_overlay']:
self.WebView.show()
MF.WEBPAGE = self.WebPage
def start_main_functionality(self):
""" Doing the main work of looking for replays, analysing, etc. """
logger.info(f'\n>>> Starting (v{APPVERSION/100:.2f})'
f' [{AF.app_type()}]'
f' [{platform.system()} {platform.release()}]'
f'\n{SM.settings_for_logs()}')
self.create_reset_overlay()
# Pass current settings
MF.update_init_message()
# Init randomization
self.TAB_Randomizer.randomize_commander()
# Start server thread
self.thread_server = threading.Thread(target=MF.server_thread, daemon=True)
self.thread_server.start()
# Init replays, names & handles. This should be fast
MF.initialize_replays_names_handles()
# PyQt threadpool
self.threadpool = QtCore.QThreadPool()
# Check for new replays
thread_replays = MUI.Worker(MF.check_replays)
thread_replays.signals.result.connect(self.check_replays_finished)
self.threadpool.start(thread_replays)
# Start mass replay analysis
thread_mass_analysis = MUI.Worker(MR.mass_replay_analysis_thread, SM.settings['account_folder'], progress_callback=True)
thread_mass_analysis.signals.progress.connect(self.mass_analysis_progress_update)
thread_mass_analysis.signals.result.connect(self.mass_analysis_finished)
if TabWidget.taskbar_progress is not None:
TabWidget.taskbar_progress.setValue(0)
TabWidget.taskbar_progress.resume()
TabWidget.taskbar_progress.show()
self.threadpool.start(thread_mass_analysis)
logger.info('Starting mass replay analysis')
# Check for the PC to be awoken from sleep
thread_awakening = MUI.Worker(MF.wait_for_wake)
thread_awakening.signals.result.connect(self.pc_waken_from_sleep)
self.threadpool.start(thread_awakening)
# Create chat widget
if SM.settings['show_chat']:
self.create_twitch_chat()
# Create the twitch bot
if SM.settings['twitchbot']['auto_start']:
self.run_twitch_bot()
# Performance overlay
self.performance_overlay = SystemInfo(geometry=SM.settings['performance_geometry'], process_names=SM.settings['performance_processes'])
if SM.settings['performance_show']:
self.TAB_Resources.ch_performance_show.setChecked(True)
self.performance_overlay.start()
# Find MM Integration banks
self.TAB_TwitchBot.find_and_update_banks()
self.update_selected_bank_item(SM.settings['twitchbot']['bank_locations'].get('Current'))
def mass_analysis_progress_update(self, progress):
""" Update progress bar in taskbar when doing basic mass analysis"""
if TabWidget.taskbar_progress is not None and progress[1] != 0:
TabWidget.taskbar_progress.setValue(int(100 * progress[0] / progress[1]))
def change_bank(self):
""" Update currently used bank in the twitch bot.
Used when user changes combo-box directly"""
bank_path = self.bank_name_to_location_dict.get(self.TAB_TwitchBot.CB_twitch_banks.currentText(),
self.TAB_TwitchBot.CB_twitch_banks.currentText())
logger.info(f'Changing bank to {bank_path}')
SM.settings['twitchbot']['bank_locations']['Current'] = bank_path
try:
self.TwitchBot.bank = bank_path
except Exception:
logger.info('Failed to set bank for twitch bot')
def update_selected_bank_item(self, bank_path):
""" Updates selected bank indirectly (when user didn't click it directly)"""
if bank_path in {'', None}:
logger.info('Not valid bank path, not changing')
return
logger.info(f'Changing bank indirectly to {bank_path.strip()}')
for i in range(self.TAB_TwitchBot.CB_twitch_banks.count()):
if bank_path in self.TAB_TwitchBot.CB_twitch_banks.itemText(i):
SM.settings['twitchbot']['bank_locations']['Current'] = bank_path
self.TAB_TwitchBot.CB_twitch_banks.setCurrentIndex(i)
try:
self.TwitchBot.bank = bank_path
except Exception:
logger.info('Failed to set bank for twitch bot')
break
logger.info('Bank changed indirectly succesfully')
def run_twitch_bot(self):
"""Runs the twitch bot. But first checks if bot name and oauth are set. If not, tries to fallback on my bot settings. """
twitchbot_settings = SM.settings['twitchbot'].copy()
# Fallback to my bot if the user doesn't have its own bot
if SM.settings['twitchbot']['channel_name'] != '' and SM.settings['twitchbot']['bot_name'] == '' and SM.settings['twitchbot'][
'bot_oauth'] == '':
file = innerPath('src/bot')
if os.path.isfile(file):
with open(file, 'r') as f:
fallback = json.load(f)
logger.info('Falling back on my twitch bot settings')
twitchbot_settings['bot_name'] = fallback['bot_name']
twitchbot_settings['bot_oauth'] = fallback['bot_oauth']
# Run the both if settings are ok
if twitchbot_settings['channel_name'] == '' or twitchbot_settings['bot_name'] == '' or twitchbot_settings['bot_oauth'] == '':
logger.error(
f"Invalid data for the bot\nchannel_name={SM.settings['twitchbot']['channel_name']}\nbot_name={SM.settings['twitchbot']['bot_name']}\nbot_oauth={SM.settings['twitchbot']['bot_oauth']}"
)
self.TAB_TwitchBot.LA_InfoTwitch.setText('Twitch bot not started. Check your settings!')
else:
self.TwitchBot = TwitchBot(twitchbot_settings, widget=self.chat_widget if hasattr(self, 'chat_widget') else None)
self.thread_twitch_bot = threading.Thread(target=self.TwitchBot.run_bot, daemon=True)
self.thread_twitch_bot.start()
self.TAB_TwitchBot.bt_twitch.setText('Stop the bot')
def show_charts(self, show):
""" Show/hide charts. Update BG width."""
SM.settings['show_charts'] = show
if show:
MF.sendEvent('showhide_charts(true)', raw=True)
else:
MF.sendEvent('showhide_charts(false)', raw=True)
def set_WebView_size_location(self, monitor):
""" Set correct size and width for the widget. Setting it to full shows black screen on my machine, works fine on notebook (thus -1 offset) """
try:
sg = QtWidgets.QDesktopWidget().screenGeometry(int(SM.settings['monitor'] - 1))
self.WebView.setFixedSize(int(sg.width() * SM.settings['width']),
int(sg.height() * SM.settings['height']) - SM.settings['subtract_height'])
offset = QtCore.QPoint(-self.WebView.width() + 1 + int(SM.settings['right_offset']), int(SM.settings['top_offset']))
self.WebView.move(sg.topRight() + offset)
logger.info(f'Using monitor {int(monitor)} ({sg.width()}x{sg.height()})')
except Exception:
logger.error(f"Failed to set to monitor {monitor}\n{traceback.format_exc()}")
def pc_waken_from_sleep(self, diff):
""" This function is run when the PC is awoken """
if diff is None:
return
logger.info(f'The computer just awoke! ({HF.strtime(diff, show_seconds=True)})')
thread_awakening = MUI.Worker(MF.wait_for_wake)
thread_awakening.signals.result.connect(self.pc_waken_from_sleep)
self.threadpool.start(thread_awakening)
# Check for new updates & reset keyboard threads
self.check_for_updates()
self.reset_keyboard_thread()
def reset_keyboard_thread(self):
""" Resets keyboard thread"""
global keyboard
try:
keyboard.unhook_all()
keyboard = importlib.reload(keyboard)
self.manage_keyboard_threads()
logger.info(f'Resetting keyboard thread')
except Exception:
logger.error(f"Failed to reset keyboard\n{traceback.format_exc}")
def check_replays_finished(self, replay_dict):
""" Launches function again. Adds game to game tab. Updates player winrate data. """
# Show/hide overlay (just to make sure)
if hasattr(self, 'WebView') and SM.settings['force_hide_overlay'] and self.WebView.isVisible():
self.WebView.hide()
elif hasattr(self, 'WebView') and not SM.settings['force_hide_overlay']:
self.WebView.show()
# Launch thread anew
thread_replays = MUI.Worker(MF.check_replays)
thread_replays.signals.result.connect(self.check_replays_finished)
self.threadpool.start(thread_replays)
# Delay updating new data to prevent lag when showing the overlay
self.wait_ms(2000)
self.TAB_Games.add_new_game_data(replay_dict)
if self.CAnalysis is not None and replay_dict['mutators']:
self.TAB_Mutations.update_data(self.CAnalysis.get_weekly_data())
def save_playernotes_to_settings(self):
""" Saves player notes from UI to settings dict"""
for player in self.TAB_Players.player_winrate_UI_dict:
if not self.TAB_Players.player_winrate_UI_dict[player].get_note() in {None, ''}:
SM.settings['player_notes'][player] = self.TAB_Players.player_winrate_UI_dict[player].get_note()
elif player in SM.settings['player_notes']:
del SM.settings['player_notes'][player]
def wait_ms(self, time):
""" Pause executing for `time` in miliseconds"""
loop = QtCore.QEventLoop()
QtCore.QTimer.singleShot(time, loop.quit)
loop.exec_()
@catch_exceptions(logger)
def mass_analysis_finished(self, result):
self.CAnalysis = result
if TabWidget.taskbar_progress is not None:
TabWidget.taskbar_progress.setValue(100)
TabWidget.taskbar_progress.hide()
# Update game tab
self.TAB_Games.initialize_data(self.CAnalysis)
# Update stats tab
player_names = (', ').join(self.CAnalysis.main_names)
self.TAB_Stats.LA_IdentifiedPlayers.setText(f"Main players: {player_names}")
self.TAB_Stats.LA_GamesFound.setText(f"Games found: {len(self.CAnalysis.ReplayData)}")
self.TAB_Stats.LA_Stats_Wait.deleteLater()
self.TAB_Games.LA_Games_Wait.deleteLater()
self.TAB_Stats.generate_stats()
self.TAB_Mutations.update_data(self.CAnalysis.get_weekly_data())
self.update_winrate_data()
MF.check_names_handles()
MF.CAnalysis = self.CAnalysis
# Show player winrates
if SM.settings['show_player_winrates']:
thread_check_for_newgame = MUI.Worker(MF.check_for_new_game, progress_callback=True)
thread_check_for_newgame.signals.progress.connect(self.map_identified)
self.threadpool.start(thread_check_for_newgame)
# Connect & run full analysis if set
self.TAB_Stats.BT_FA_run.setEnabled(True)
self.TAB_Stats.BT_FA_run.clicked.connect(self.run_f_analysis)
if SM.settings['full_analysis_atstart']:
self.run_f_analysis()
# If try to find
self.find_default_bank_location()
# Change bank names
self.bank_name_to_location_dict = self.TAB_TwitchBot.change_bank_names(self.CAnalysis)
# Enable selecting banks
self.TAB_TwitchBot.CB_twitch_banks.currentIndexChanged.connect(self.change_bank)
self.TAB_TwitchBot.CB_twitch_banks.setEnabled(True)
# Dump & reinit
self.TAB_Stats.BT_FA_dump.setEnabled(True)
self.TAB_Stats.BT_FA_dump.clicked.connect(self.dump_all)
def map_identified(self, data):
"""Shows fast expand widget when a valid new map is identified"""
logger.info(f'Identified map: {data}')
# Don't proceed if the function disabled or not a valid map
if not SM.settings['fast_expand'] or not data[0] in FastExpandSelector.valid_maps:
return
if self.FastExpandSelector is None:
self.FastExpandSelector = FastExpandSelector()
self.FastExpandSelector.setData(data)
self.FastExpandSelector.show()
def dump_all(self):
""" Dumps all replay data from mass analysis into a file """
self.TAB_Stats.BT_FA_dump.setEnabled(False)
thread_dump_all = MUI.Worker(self.CAnalysis.dump_all)
thread_dump_all.signals.result.connect(partial(self.TAB_Stats.BT_FA_dump.setEnabled, True))
self.threadpool.start(thread_dump_all)
def run_f_analysis(self):
""" runs full analysis """
if self.full_analysis_running:
logger.error('Full analysis is already running')
return
if TabWidget.taskbar_progress is not None:
TabWidget.taskbar_progress.setValue(0)
TabWidget.taskbar_progress.resume()
TabWidget.taskbar_progress.show()
self.TAB_Stats.BT_FA_run.setEnabled(False)
self.TAB_Stats.BT_FA_stop.setEnabled(True)
self.full_analysis_running = True
thread_full_analysis = MUI.Worker(self.CAnalysis.run_full_analysis, progress_callback=True)
thread_full_analysis.signals.result.connect(self.full_analysis_finished)
thread_full_analysis.signals.progress.connect(self.full_analysis_progress)
self.threadpool.start(thread_full_analysis)
def full_analysis_progress(self, progress):
""" Updates progress from full analysis"""
self.TAB_Stats.CH_FA_status.setText(progress[2])
if TabWidget.taskbar_progress is not None and progress[1] != 0:
TabWidget.taskbar_progress.setValue(int(100 * progress[0] / progress[1]))