-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCLASSIC_Interface.py
More file actions
1646 lines (1374 loc) · 58.9 KB
/
CLASSIC_Interface.py
File metadata and controls
1646 lines (1374 loc) · 58.9 KB
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
import asyncio
import sys
import traceback
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from types import TracebackType
from typing import Literal
import regex as re
from PySide6.QtCore import QEvent, QObject, Qt, QThread, QTimer, QUrl, Signal, Slot
from PySide6.QtGui import QCloseEvent, QDesktopServices, QFontMetrics, QIcon, QPixmap
from PySide6.QtMultimedia import QSoundEffect
from PySide6.QtWidgets import (
QApplication,
QBoxLayout,
QButtonGroup,
QCheckBox,
QComboBox,
QDialog,
QDialogButtonBox,
QFileDialog,
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QLayout,
QLineEdit,
QMainWindow,
QMessageBox,
QPlainTextEdit,
QPushButton,
QSizePolicy,
QTabWidget,
QTextEdit,
QVBoxLayout,
QWidget,
)
@dataclass
class PapyrusStats:
"""Data class to hold Papyrus log statistics"""
timestamp: datetime
dumps: int
stacks: int
warnings: int
errors: int
ratio: float
def __eq__(self, other: object) -> bool:
if not isinstance(other, PapyrusStats):
return NotImplemented
return (self.dumps == other.dumps and
self.stacks == other.stacks and
self.warnings == other.warnings and
self.errors == other.errors)
class PapyrusMonitorWorker(QObject):
"""Worker class to monitor Papyrus logs in a separate thread"""
# Signal when new stats are available
statsUpdated = Signal(PapyrusStats)
# Signal for errors
error = Signal(str)
def __init__(self) -> None:
super().__init__()
self._should_run = True
self._last_stats: PapyrusStats | None = None
self._error_sound_played = False # Track if error sound has played this session
def stop(self) -> None:
"""Stop the monitoring loop"""
self._should_run = False
@Slot()
def run(self) -> None:
"""Main monitoring loop"""
while self._should_run:
try:
message, count = CGame.papyrus_logging()
# Parse the message to extract stats
current_stats = self._parse_stats(message, count)
# Only emit if stats have changed
if self._last_stats != current_stats:
self.statsUpdated.emit(current_stats)
self._last_stats = current_stats
# Sleep for a short interval to prevent excessive CPU usage
QThread.msleep(1000) # Check every second
except (OSError, ValueError) as e:
self.error.emit(str(e))
break
@staticmethod
def _parse_stats(message: str, dump_count: int) -> PapyrusStats:
"""Parse the papyrus log message into statistics"""
stats = {
'dumps': dump_count,
'stacks': 0,
'warnings': 0,
'errors': 0
}
for line in message.splitlines():
if ': ' in line:
key, value = line.split(': ')
key = key.strip().lower()
if key == 'number of stacks':
stats['stacks'] = int(value)
elif key == 'number of warnings':
stats['warnings'] = int(value)
elif key == 'number of errors':
stats['errors'] = int(value)
ratio = 0.0 if stats['dumps'] == 0 else stats['dumps'] / stats['stacks']
return PapyrusStats(
timestamp=datetime.now(),
dumps=stats['dumps'],
stacks=stats['stacks'],
warnings=stats['warnings'],
errors=stats['errors'],
ratio=ratio
)
# Example fix for pastebin fetch
class PastebinFetchWorker(QObject):
finished = Signal()
error = Signal(str)
success = Signal(str)
def __init__(self, url: str) -> None:
super().__init__()
self.url = url
@Slot()
def run(self) -> None:
try:
CLogs.pastebin_fetch(self.url)
self.success.emit(self.url)
except (OSError, ValueError) as e:
self.error.emit(str(e))
finally:
self.finished.emit()
class CustomAboutDialog(QDialog):
def __init__(self, parent: QMainWindow | QDialog | None = None) -> None:
super().__init__(parent)
self.setWindowTitle("About")
self.setFixedSize(600, 200) # Adjust size for icon and text
# Create a layout with margins similar to QMessageBox.about
layout: QVBoxLayout = QVBoxLayout(self)
layout.setContentsMargins(15, 15, 15, 15) # Adjust margins (left, top, right, bottom)
# Horizontal layout for icon and text
h_layout: QHBoxLayout = QHBoxLayout()
# Add the icon
icon_label: QLabel = QLabel(self)
icon: QIcon = QIcon("CLASSIC Data/graphics/CLASSIC.ico")
pixmap: QPixmap = icon.pixmap(128, 128) # Request the 64x64 icon size
if not pixmap.isNull():
icon_label.setPixmap(pixmap)
icon_label.setAlignment(Qt.AlignmentFlag.AlignTop) # Align icon at the top
h_layout.addWidget(icon_label)
# Add the text next to the icon
text_label: QLabel = QLabel(
"Crash Log Auto Scanner & Setup Integrity Checker\n\n"
"Made by: Poet\n"
"Contributors: evildarkarchon | kittivelae | AtomicFallout757 | wxMichael"
)
text_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) # Align text to top-left
text_label.setWordWrap(True) # Allow text wrapping for better formatting
h_layout.addWidget(text_label)
layout.addLayout(h_layout)
# Add a Close button at the bottom
close_button: QPushButton = QPushButton("Close", self)
close_button.clicked.connect(self.accept)
layout.addWidget(close_button)
# Align the Close button to the right and add some space at the bottom
layout.setAlignment(close_button, Qt.AlignmentFlag.AlignRight)
class ErrorDialog(QDialog):
def __init__(self, error_text: str) -> None:
super().__init__()
self.setWindowTitle("Error")
self.setMinimumSize(600, 300)
layout = QVBoxLayout(self)
self.text_edit = QPlainTextEdit(self)
self.text_edit.setReadOnly(True)
self.text_edit.setPlainText(error_text)
layout.addWidget(self.text_edit)
copy_button = QPushButton("Copy to Clipboard", self)
copy_button.clicked.connect(self.copy_to_clipboard)
layout.addWidget(copy_button)
def copy_to_clipboard(self) -> None:
QApplication.clipboard().setText(self.text_edit.toPlainText())
def show_exception_box(error_text: str) -> None:
dialog = ErrorDialog(error_text)
dialog.show()
dialog.exec()
def custom_excepthook(exc_type: type[BaseException], exc_value: BaseException, exc_traceback: TracebackType | None) -> None:
error_text = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
print(error_text) # Still print to console
show_exception_box(error_text)
sys.excepthook = custom_excepthook
import CLASSIC_Main as CMain # noqa: E402
import CLASSIC_ScanGame as CGame # noqa: E402
import CLASSIC_ScanLogs as CLogs # noqa: E402
class AudioPlayer(QObject):
# Define signals for different sounds
play_error_signal = Signal()
play_notify_signal = Signal()
play_custom_signal = Signal(str) # Signal to play a custom sound with a path
def __init__(self) -> None:
super().__init__()
self.audio_enabled = CMain.classic_settings(bool, "Audio Notifications")
if self.audio_enabled is None:
CMain.yaml_settings(bool, CMain.YAML.Settings, "CLASSIC_Settings.Audio Notifications", True)
self.audio_enabled = True
# Setup QSoundEffect objects for the preset sounds
self.error_sound = QSoundEffect()
self.error_sound.setSource(QUrl.fromLocalFile("CLASSIC Data/sounds/classic_error.wav"))
self.error_sound.setVolume(1.0) # Set max volume
self.notify_sound = QSoundEffect()
self.notify_sound.setSource(QUrl.fromLocalFile("CLASSIC Data/sounds/classic_notify.wav"))
self.notify_sound.setVolume(1.0) # Set max volume
# Connect signals to respective slots
if self.audio_enabled:
self.play_error_signal.connect(self.play_error_sound)
self.play_notify_signal.connect(self.play_notify_sound)
self.play_custom_signal.connect(lambda file: self.play_custom_sound(file)) # Use custom path
def play_error_sound(self) -> None:
if self.audio_enabled and self.error_sound.isLoaded():
self.error_sound.play()
def play_notify_sound(self) -> None:
if self.audio_enabled and self.notify_sound.isLoaded():
self.notify_sound.play()
def play_custom_sound(self, sound_path: str) -> None:
custom_sound = QSoundEffect()
custom_sound.setSource(QUrl.fromLocalFile(sound_path))
custom_sound.setVolume(1.0)
custom_sound.play()
def toggle_audio(self, state: bool) -> None:
self.audio_enabled = state
if not state:
self.play_notify_signal.disconnect()
self.play_error_signal.disconnect()
self.play_custom_signal.disconnect()
else:
self.play_notify_signal.connect(self.play_notify_sound)
self.play_error_signal.connect(self.play_error_sound)
self.play_custom_signal.connect(lambda file: self.play_custom_sound(file))
class ManualPathDialog(QDialog):
def __init__(self, parent: QMainWindow | None = None) -> None:
super().__init__(parent)
self.setWindowTitle("Set INI Files Directory")
self.setFixedSize(700, 150)
# Create layout and input field
layout = QVBoxLayout(self)
# Add a label
label = QLabel(f"Enter the path for the {CMain.gamevars["game"]} INI files directory (Example: c:\\users\\<name>\\Documents\\My Games\\{CMain.gamevars["game"]})", self)
layout.addWidget(label)
inputlayout = QHBoxLayout()
self.input_field = QLineEdit(self)
self.input_field.setPlaceholderText("Enter the INI directory or click 'Browse'...")
inputlayout.addWidget(self.input_field)
# Create the "Browse" button
browse_button = QPushButton("Browse...", self)
browse_button.clicked.connect(self.browse_directory)
inputlayout.addWidget(browse_button)
layout.addLayout(inputlayout)
# Create standard OK button
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def browse_directory(self) -> None:
# Open directory browser and update the input field
manual_path = QFileDialog.getExistingDirectory(self, "Select Directory for INI Files")
if manual_path:
self.input_field.setText(manual_path)
def get_path(self) -> str:
return self.input_field.text()
class GamePathDialog(QDialog):
def __init__(self, parent: QMainWindow | None = None) -> None:
super().__init__(parent)
self.setWindowTitle("Set INI Files Directory")
self.setFixedSize(700, 150)
# Create layout and input field
layout = QVBoxLayout(self)
# Add a label
label = QLabel(f"Enter the path for the {CMain.gamevars["game"]} directory (example: C:\\Steam\\steamapps\\common\\{CMain.gamevars["game"]})", self)
layout.addWidget(label)
inputlayout = QHBoxLayout()
self.input_field = QLineEdit(self)
self.input_field.setPlaceholderText("Enter the Game's directory or click 'Browse'...")
inputlayout.addWidget(self.input_field)
# Create the "Browse" button
browse_button = QPushButton("Browse...", self)
browse_button.clicked.connect(self.browse_directory)
inputlayout.addWidget(browse_button)
layout.addLayout(inputlayout)
# Create standard OK button
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def browse_directory(self) -> None:
# Open directory browser and update the input field
manual_path = QFileDialog.getExistingDirectory(self, f"Select Directory for {CMain.gamevars["game"]}")
if manual_path:
self.input_field.setText(manual_path)
def get_path(self) -> str:
return self.input_field.text()
class OutputRedirector(QObject):
outputWritten = Signal(str)
def write(self, text: str) -> None:
self.outputWritten.emit(str(text))
def flush(self) -> None:
pass
class CrashLogsScanWorker(QObject):
finished = Signal()
notify_sound_signal = Signal()
error_sound_signal = Signal()
custom_sound_signal = Signal(str) # In case a custom sound needs to be played
@Slot()
def run(self) -> None:
# Here you can determine the appropriate sound to play.
# For simplicity, we're triggering the notify sound when the scan completes.
try:
CLogs.crashlogs_scan()
self.notify_sound_signal.emit() # Emit signal to play notify sound
except Exception as e: # noqa: BLE001
if CMain.classic_settings(bool, "Audio Notifications"):
self.error_sound_signal.emit() # Emit signal to play error sound in case of exception
else:
ErrorDialog(str(e)).exec()
finally:
self.finished.emit()
class GameFilesScanWorker(QObject):
finished = Signal()
notify_sound_signal = Signal()
error_sound_signal = Signal()
custom_sound_signal = Signal(str)
@Slot()
def run(self) -> None:
try:
CGame.write_combined_results()
self.notify_sound_signal.emit() # Emit signal to play notify sound
except Exception as e: # noqa: BLE001
if CMain.classic_settings(bool, "Audio Notifications"):
self.error_sound_signal.emit() # Emit signal to play error sound in case of exception
else:
ErrorDialog(str(e)).exec()
finally:
self.finished.emit()
class MainWindow(QMainWindow):
papyrus_monitor_thread: QThread | None
papyrus_monitor_worker: PapyrusMonitorWorker | None
_last_stats: PapyrusStats | None
def __init__(self) -> None:
super().__init__()
self.pastebin_url_regex: re.Pattern = re.compile(r"^https?://pastebin\.com/(\w+)$")
CMain.initialize(is_gui=True)
self.setWindowTitle(
f"Crash Log Auto Scanner & Setup Integrity Checker | {CMain.yaml_settings(str, CMain.YAML.Main, "CLASSIC_Info.version")}"
)
self.setWindowIcon(QIcon("CLASSIC Data/graphics/CLASSIC.ico"))
dark_style = """
QWidget {
background-color: #2b2b2b;
color: #ffffff;
font-family: "Segoe UI", sans-serif;
font-size: 13px;
}
QLineEdit, QPlainTextEdit, QTextEdit, QSpinBox, QPushButton {
background-color: #3c3c3c;
border: 1px solid #5c5c5c;
color: #ffffff;
}
/* ComboBox Styling */
QComboBox {
background-color: #3c3c3c;
border: 1px solid #5c5c5c;
border-radius: 4px;
padding: 4px 8px;
min-height: 24px;
color: #ffffff;
}
QComboBox:hover {
background-color: #444444;
border-color: #666666;
}
QComboBox:focus {
border-color: #0078d4;
}
QComboBox::drop-down {
border: none;
width: 24px;
}
QComboBox::down-arrow {
image: url(CLASSIC Data/graphics/arrow-down.svg);
width: 12px;
height: 12px;
}
QComboBox:disabled {
background-color: #2b2b2b;
color: #666666;
}
/* ScrollBar Styling */
QScrollBar:vertical {
background-color: #202020;
width: 14px;
border: none;
border-radius: 7px;
margin: 0;
}
QScrollBar::groove:vertical {
background-color: #202020;
border: none;
border-radius: 7px;
}
QScrollBar::handle:vertical {
background-color: #686868;
min-height: 30px;
border-radius: 5px;
margin: 2px 2px;
}
QScrollBar::handle:vertical:hover {
background-color: #7f7f7f;
}
QScrollBar::add-line:vertical,
QScrollBar::sub-line:vertical,
QScrollBar::add-page:vertical,
QScrollBar::sub-page:vertical {
background: #202020;
border: none;
height: 0px;
}
QScrollBar:horizontal {
background-color: #202020;
height: 14px;
border: none;
border-radius: 7px;
margin: 0;
}
QScrollBar::groove:horizontal {
background-color: #202020;
border: none;
border-radius: 7px;
}
QScrollBar::handle:horizontal {
background-color: #686868;
min-width: 30px;
border-radius: 5px;
margin: 2px 2px;
}
QScrollBar::handle:horizontal:hover {
background-color: #7f7f7f;
}
QScrollBar::add-line:horizontal,
QScrollBar::sub-line:horizontal,
QScrollBar::add-page:horizontal,
QScrollBar::sub-page:horizontal {
background: #202020;
border: none;
width: 0px;
}
QScrollBar::corner {
background: #202020;
}
/* Tab Widget Styling */
QTabWidget::pane {
border: 1px solid #444444;
}
QTabBar::tab {
background-color: #3c3c3c;
border: 1px solid #5c5c5c;
color: #ffffff;
padding: 5px;
}
QTabBar::tab:selected {
background-color: #2b2b2b;
color: #ffffff;
}
/* Button Styling */
QPushButton {
background-color: #3c3c3c;
border: 1px solid #5c5c5c;
color: #ffffff;
padding: 5px;
}
QPushButton:hover {
background-color: #444444;
}
QPushButton:pressed {
background-color: #222222;
}
/* Label Styling */
QLabel {
color: #ffffff;
}
"""
self.setStyleSheet(dark_style)
# self.setMinimumSize(700, 950) # Increase minimum width from 650 to 700
self.setFixedSize(700, 950) # Set fixed size to prevent resizing, for now.
# Set up the custom exception handler for the main window
self.installEventFilter(self)
self.audio_player = AudioPlayer()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.main_layout = QVBoxLayout(self.central_widget)
self.main_layout.setContentsMargins(10, 10, 10, 10)
self.main_layout.setSpacing(10)
self.tab_widget = QTabWidget()
self.main_layout.addWidget(self.tab_widget)
self.main_tab = QWidget()
self.backups_tab = QWidget()
self.tab_widget.addTab(self.main_tab, "MAIN OPTIONS")
self.tab_widget.addTab(self.backups_tab, "FILE BACKUP")
self.scan_button_group = QButtonGroup()
self.setup_main_tab()
self.setup_backups_tab()
# In __init__ method, after setting up the main tab:
self.initialize_folder_paths()
self.setup_output_redirection()
self.output_buffer = ""
CMain.main_generate_required()
# Perform initial update check
if CMain.classic_settings(bool, "Update Check"):
QTimer.singleShot(0, self.update_popup)
self.update_check_timer = QTimer()
self.update_check_timer.timeout.connect(self.perform_update_check)
self.is_update_check_running = False
# Initialize thread attributes
self.crash_logs_thread: QThread | None = None
self.game_files_thread: QThread | None = None
if CMain.manual_docs_gui is None or CMain.game_path_gui is None:
raise TypeError("CMain not initialized")
CMain.manual_docs_gui.manual_docs_path_signal.connect(self.show_manual_docs_path_dialog)
CMain.game_path_gui.game_path_signal.connect(self.show_game_path_dialog)
def eventFilter(self, watched: QObject, event: QEvent) -> bool:
"""if event.type() == QEvent.KeyPress:
key_event = QKeyEvent(event)
if key_event.key() == Qt.Key_F12:
# Simulate an exception when F12 is pressed (for testing)
raise Exception("This is a test exception")"""
return super().eventFilter(watched, event)
def closeEvent(self, event: QCloseEvent) -> None:
"""Stop the Papyrus monitor thread when the window is closed"""
self.stop_papyrus_monitoring()
super().closeEvent(event)
def setup_pastebin_elements(self, layout: QVBoxLayout) -> None:
"""Set up the Pastebin fetch UI elements."""
pastebin_layout = QHBoxLayout()
self.pastebin_label = QLabel("PASTEBIN LOG FETCH", self)
self.pastebin_label.setToolTip("Fetch a log file from Pastebin. Can be used more than once.")
pastebin_layout.addWidget(self.pastebin_label)
pastebin_layout.addSpacing(50)
self.pastebin_id_input = QLineEdit(self)
self.pastebin_id_input.setPlaceholderText("Enter Pastebin URL or ID")
self.pastebin_id_input.setToolTip("Enter the Pastebin URL or ID to fetch the log. Can be used more than once.")
pastebin_layout.addWidget(self.pastebin_id_input)
self.pastebin_fetch_button = QPushButton("Fetch Log", self)
self.pastebin_fetch_button.clicked.connect(self.fetch_pastebin_log)
self.pastebin_fetch_button.clicked.connect(self.pastebin_id_input.clear)
self.pastebin_fetch_button.setToolTip("Fetch the log file from Pastebin. Can be used more than once.")
pastebin_layout.addWidget(self.pastebin_fetch_button)
# Add the layout to the main layout (add it to an appropriate tab or section)
layout.addLayout(pastebin_layout)
def fetch_pastebin_log(self) -> None:
input_text = self.pastebin_id_input.text().strip()
url = input_text if self.pastebin_url_regex.match(input_text) else f"https://pastebin.com/{input_text}"
# Create thread and worker
pastebin_thread = QThread()
pastebin_worker = PastebinFetchWorker(url)
pastebin_worker.moveToThread(pastebin_thread)
# Connect signals
pastebin_thread.started.connect(pastebin_worker.run)
pastebin_worker.finished.connect(pastebin_thread.quit)
pastebin_worker.success.connect(lambda url: QMessageBox.information(self, "Success", f"Log fetched from: {url}"))
pastebin_worker.error.connect(lambda err: QMessageBox.warning(self, "Error", f"Failed to fetch log: {err}", QMessageBox.StandardButton.NoButton, QMessageBox.StandardButton.NoButton))
# Start thread
pastebin_thread.start()
def show_manual_docs_path_dialog(self) -> None:
dialog = ManualPathDialog(self)
if dialog.exec() == QDialog.DialogCode.Accepted:
manual_path = dialog.get_path()
CMain.get_manual_docs_path_gui(manual_path)
def show_game_path_dialog(self) -> None:
if CMain.game_path_gui is None:
raise TypeError("CMain not initialized")
dialog = GamePathDialog(self)
if dialog.exec() == QDialog.DialogCode.Accepted:
manual_path = dialog.get_path()
CMain.game_path_gui.get_game_path_gui(manual_path)
def update_popup(self) -> None:
if not self.is_update_check_running:
self.is_update_check_running = True
self.update_check_timer.start(0) # Start immediately
def update_popup_explicit(self) -> None:
self.update_check_timer.timeout.disconnect(self.perform_update_check)
self.update_check_timer.timeout.connect(self.force_update_check)
if not self.is_update_check_running:
self.is_update_check_running = True
self.update_check_timer.start(0)
def perform_update_check(self) -> None:
self.update_check_timer.stop()
asyncio.run(self.async_update_check())
def force_update_check(self) -> None:
# Directly perform the update check without reading from settings
self.is_update_check_running = True
self.update_check_timer.stop()
asyncio.run(self.async_update_check_explicit()) # Perform async check
async def async_update_check(self) -> None:
try:
is_up_to_date = await CMain.is_latest_version(quiet=True)
self.show_update_result(is_up_to_date)
except CMain.UpdateCheckError as e:
self.show_update_error(str(e))
finally:
self.is_update_check_running = False
self.update_check_timer.stop() # Ensure the timer is always stopped
async def async_update_check_explicit(self) -> None:
try:
is_up_to_date = await CMain.is_latest_version(
quiet=True, gui_request=True
)
self.show_update_result(is_up_to_date)
except CMain.UpdateCheckError as e:
self.show_update_error(str(e))
finally:
self.is_update_check_running = False
self.update_check_timer.stop() # Ensure the timer is always stopped
def show_update_result(self, is_up_to_date: bool) -> None:
if is_up_to_date:
QMessageBox.information(
self, "CLASSIC UPDATE", "You have the latest version of CLASSIC!"
)
else:
update_popup_text = CMain.yaml_settings(str, CMain.YAML.Main, "CLASSIC_Interface.update_popup_text") or ""
result = QMessageBox.question(
self,
"CLASSIC UPDATE",
update_popup_text,
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.NoButton
)
if result == QMessageBox.StandardButton.Yes:
QDesktopServices.openUrl(
QUrl(
"https://github.com/evildarkarchon/CLASSIC-Fallout4/releases/latest"
)
)
def show_update_error(self, error_message: str) -> None:
QMessageBox.warning(
self, "Update Check Failed", f"Failed to check for updates: {error_message}", QMessageBox.StandardButton.NoButton, QMessageBox.StandardButton.NoButton
)
def setup_main_tab(self) -> None:
layout = QVBoxLayout(self.main_tab)
layout.setContentsMargins(20, 10, 20, 10)
layout.setSpacing(10)
# Top section
self.mods_folder_edit = self.setup_folder_section(
layout, "STAGING MODS FOLDER", "Box_SelectedMods", self.select_folder_mods
)
self.mods_folder_edit.setToolTip("Select the folder where you stage your mods.")
self.mods_folder_edit.setPlaceholderText("Optional: Select the folder where you stage your mods.")
self.scan_folder_edit = self.setup_folder_section(
layout, "CUSTOM SCAN FOLDER", "Box_SelectedScan", self.select_folder_scan
)
self.scan_folder_edit.setToolTip("Select a custom folder to scan for log files.")
self.scan_folder_edit.setPlaceholderText("Optional: Select a custom folder to scan for log files.")
self.setup_pastebin_elements(layout)
# Add first separator
layout.addWidget(self.create_separator())
# Main buttons section
self.setup_main_buttons(layout)
# Add second separator
layout.addWidget(self.create_separator())
# Checkbox section
self.setup_checkboxes(layout)
# Articles section
self.setup_articles_section(layout)
# Add a separator before bottom buttons
layout.addWidget(self.create_separator())
# Bottom buttons
self.setup_bottom_buttons(layout)
# Add output text box
self.setup_output_text_box(layout)
# Add some spacing
layout.addSpacing(10)
# Set the layout to be stretchable
layout.setStretchFactor(self.output_text_box, 1)
def setup_backups_tab(self) -> None:
layout = QVBoxLayout(self.backups_tab)
layout.setContentsMargins(20, 10, 20, 10)
layout.setSpacing(10)
# Add explanation labels
layout.addWidget(
QLabel(
"BACKUP > Backup files from the game folder into the CLASSIC Backup folder."
)
)
layout.addWidget(
QLabel(
"RESTORE > Restore file backup from the CLASSIC Backup folder into the game folder."
)
)
layout.addWidget(
QLabel(
"REMOVE > Remove files only from the game folder without removing existing backups."
)
)
# Add separators and category buttons
categories = ["XSE", "RESHADE", "VULKAN", "ENB"]
for category in categories:
layout.addWidget(self.create_separator())
category_label = QLabel(category)
category_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(category_label)
button_layout = QHBoxLayout()
backup_button = QPushButton(f"BACKUP {category}")
backup_button.clicked.connect(
lambda _, c=category: self.classic_files_manage(f"Backup {c}", "BACKUP")
)
button_layout.addWidget(backup_button)
restore_button = QPushButton(f"RESTORE {category}")
restore_button.clicked.connect(
lambda _, c=category: self.classic_files_manage(
f"Backup {c}", "RESTORE"
)
)
restore_button.setEnabled(False) # Initially disabled
setattr(
self, f"RestoreButton_{category}", restore_button
) # Store reference to the button
button_layout.addWidget(restore_button)
remove_button = QPushButton(f"REMOVE {category}")
remove_button.clicked.connect(
lambda _, c=category: self.classic_files_manage(f"Backup {c}", "REMOVE")
)
button_layout.addWidget(remove_button)
layout.addLayout(button_layout)
# Check if backups exist and enable restore buttons accordingly
self.check_existing_backups()
# Add a button to open the backups folder
open_backups_button = QPushButton("OPEN CLASSIC BACKUPS")
open_backups_button.clicked.connect(self.open_backup_folder)
layout.addWidget(open_backups_button)
def check_existing_backups(self) -> None:
for category in ["XSE", "RESHADE", "VULKAN", "ENB"]:
backup_path = Path(f"CLASSIC Backup/Game Files/Backup {category}")
if backup_path.is_dir() and any(backup_path.iterdir()):
restore_button = getattr(self, f"RestoreButton_{category}", None)
if restore_button:
restore_button.setEnabled(True)
restore_button.setStyleSheet(
"""
QPushButton {
color: black;
background: rgb(250, 250, 250);
border-radius: 10px;
border: 2px solid black;
}
"""
)
def add_backup_section(self, layout: QBoxLayout, title: str, backup_type: Literal["XSE", "RESHADE", "VULKAN", "ENB"]) -> None:
layout.addWidget(self.create_separator())
title_label = QLabel(title)
title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
title_label.setStyleSheet("color: white; font-weight: bold; font-size: 14px;")
layout.addWidget(title_label)
buttons_layout = QHBoxLayout()
backup_button = QPushButton(f"BACKUP {backup_type}")
restore_button = QPushButton(f"RESTORE {backup_type}")
remove_button = QPushButton(f"REMOVE {backup_type}")
for button, action in [
(backup_button, "BACKUP"),
(restore_button, "RESTORE"),
(remove_button, "REMOVE"),
]:
button.clicked.connect(
lambda _, b=backup_type, a=action: self.classic_files_manage(
f"Backup {b}", a # type: ignore
)
)
button.setStyleSheet(
"""
QPushButton {
color: white;
background: rgba(10, 10, 10, 0.75);
border-radius: 10px;
border: 1px solid white;
font-size: 11px;
min-height: 48px;
max-height: 48px;
min-width: 180px;
max-width: 180px;
}
"""
)
buttons_layout.addWidget(button)
layout.addLayout(buttons_layout)
def classic_files_manage(self, selected_list: str, selected_mode: Literal["BACKUP", "RESTORE", "REMOVE"] = "BACKUP") -> None:
list_name = selected_list.split(" ", 1)
try:
CGame.game_files_manage(selected_list, selected_mode)
if selected_mode == "BACKUP":
# Enable the corresponding restore button
restore_button = getattr(self, f"RestoreButton_{list_name[1]}", None)
if restore_button:
restore_button.setEnabled(True)
restore_button.setStyleSheet(
"""
QPushButton {
color: black;
background: rgb(250, 250, 250);
border-radius: 10px;
border: 2px solid black;
}
"""
)
except PermissionError:
QMessageBox.critical(
self,
"Error",
"Unable to access files from your game folder. Please run CLASSIC in admin mode to resolve this problem.",
QMessageBox.StandardButton.NoButton,
QMessageBox.StandardButton.NoButton,
)
def help_popup_backup(self) -> None:
help_popup_text = CMain.yaml_settings(str, CMain.YAML.Main, "CLASSIC_Interface.help_popup_backup") or ""
QMessageBox.information(self, "NEED HELP?", help_popup_text)
@staticmethod
def open_backup_folder() -> None:
backup_path = Path.cwd() / "CLASSIC Backup/Game Files"
QDesktopServices.openUrl(QUrl.fromLocalFile(backup_path))
def setup_output_text_box(self, layout: QLayout) -> None:
self.output_text_box = QTextEdit(self)
self.output_text_box.setReadOnly(True)
self.output_text_box.setStyleSheet(
"""
QTextEdit {