-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModpackManager-main.py
4152 lines (3398 loc) · 175 KB
/
ModpackManager-main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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 tarfile, io, subprocess, math, os, random, re, shutil, requests, webbrowser, zipfile, stat, json, logging, time, platform
from PyQt6.QtGui import QColor, QPixmap
from PyQt6.QtCore import Qt, QTimer, QProcess, QThread, pyqtSignal, QPoint
from PyQt6.QtWidgets import QTabWidget, QSplashScreen, QInputDialog, QMenu, QSplitter, QListWidgetItem, QScrollArea, QProgressDialog, QHBoxLayout, QFileDialog, QMessageBox, QApplication, QCheckBox, QLineEdit, QDialog, QLabel, QPushButton, QComboBox, QGridLayout, QWidget, QVBoxLayout
import git
from git import Repo, GitCommandError
from packaging.version import Version
from urllib.parse import urlparse
import pandas as pd
from io import BytesIO
############################################################
# Detect OS and set default settings
############################################################
DATE = "2025/02/03"
ITERATION = "30"
VERSION = Version("1.10.0") # Current version of the Modpack Manager
system_platform = platform.system()
is_steam_deck = False
if system_platform == "Linux":
with open("/etc/os-release", "r") as f:
os_release = f.read()
if "steamdeck" in os_release.lower():
is_steam_deck = True
if system_platform == "Windows":
SETTINGS_FOLDER = os.path.abspath(os.path.expandvars(r"%AppData%\\Balatro\\ManagerSettings"))
DEFAULT_SETTINGS = {
"game_directory": "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Balatro",
"profile_name": "Balatro",
"mods_directory": "%AppData%\\Balatro\\Mods",
"default_modpack": "Dimserenes-Modpack",
"backup_mods": False,
"remove_mods": True,
"skip_mod_selection": False,
"auto_install": False,
"debug_mode": False,
"disable_rainbow_title": False,
"modpack_downloaded": "",
"modpack_installed": "",
}
elif system_platform == "Linux":
if is_steam_deck:
internal_game_dir = "/home/deck/.steam/steam/steamapps/common/Balatro/"
external_game_dir = "/run/media/deck/STEAM/steamapps/common/Balatro/"
# Check if the game exists on internal storage, else fall back to external storage
game_directory = internal_game_dir if os.path.exists(os.path.join(internal_game_dir, "Balatro.exe")) else external_game_dir
SETTINGS_FOLDER = os.path.expanduser("~/.steam/steam/steamapps/compatdata/2379780/pfx/drive_c/users/steamuser/AppData/Roaming/Balatro/ManagerSettings")
DEFAULT_SETTINGS = {
"game_directory": game_directory,
"profile_name": "Balatro",
"mods_directory": "/home/deck/.steam/steam/steamapps/compatdata/2379780/pfx/drive_c/users/steamuser/AppData/Roaming/Balatro/Mods",
"default_modpack": "Dimserenes-Modpack",
"backup_mods": False,
"remove_mods": True,
"skip_mod_selection": False,
"auto_install": False,
"debug_mode": False,
"disable_rainbow_title": False,
"modpack_downloaded": "",
"modpack_installed": "",
}
else:
SETTINGS_FOLDER = os.path.abspath(os.path.expandvars("/home/$USER/.steam/steam/steamapps/compatdata/2379780/pfx/drive_c/users/steamuser/AppData/Roaming/Balatro/ManagerSettings"))
DEFAULT_SETTINGS = {
"game_directory": "/home/$USER/.steam/steam/steamapps/common/Balatro",
"profile_name": "Balatro",
"mods_directory": "/home/$USER/.steam/steam/steamapps/compatdata/2379780/pfx/drive_c/users/steamuser/AppData/Roaming/Balatro/Mods",
"default_modpack": "Dimserenes-Modpack",
"backup_mods": False,
"remove_mods": True,
"skip_mod_selection": False,
"auto_install": False,
"debug_mode": False,
"disable_rainbow_title": False,
"modpack_downloaded": "",
"modpack_installed": "",
}
elif system_platform == "Darwin":
SETTINGS_FOLDER = os.path.abspath(os.path.expanduser("~/Library/Application Support/Balatro/ManagerSettings"))
DEFAULT_SETTINGS = {
"game_directory": "~/Library/Application Support/Steam/steamapps/common/Balatro/",
"profile_name": "Balatro",
"mods_directory": "~/Library/Application Support/Balatro/Mods",
"default_modpack": "Dimserenes-Modpack",
"backup_mods": False,
"remove_mods": True,
"skip_mod_selection": False,
"auto_install": False,
"debug_mode": False,
"disable_rainbow_title": False,
"modpack_downloaded": "",
"modpack_installed": "",
}
ASSETS_FOLDER = os.path.join(SETTINGS_FOLDER, "assets")
SETTINGS_FILE = os.path.join(SETTINGS_FOLDER, "user_settings.json")
INSTALL_FILE = os.path.join(SETTINGS_FOLDER, "excluded_mods.json")
FAVORITES_FILE = os.path.join(SETTINGS_FOLDER, "favorites.json")
PRESETS_FILE = os.path.join(SETTINGS_FOLDER, "modpack_presets.json")
CACHE_FILE = os.path.join(SETTINGS_FOLDER, "modpack_cache.json")
CSV_CACHE_FILE = os.path.join(SETTINGS_FOLDER, "cached_data.csv")
LOGO_URL = "https://raw.githubusercontent.com/Dimserene/Dimserenes-Modpack/refs/heads/main/NewFullPackLogo%20New%20Year.png"
LOGO_PATH = os.path.join(ASSETS_FOLDER, "logoNewYear.png") # File name to save the downloaded logo
CHECKBOX_URL = "https://github.com/Dimserene/Balatro-ModpackManager/raw/main/assets/assets.zip"
INFORMATION_URL = "https://raw.githubusercontent.com/Dimserene/ModpackManager/main/information.json"
CSV_URL = "https://docs.google.com/spreadsheets/d/1L2wPG5mNI-ZBSW_ta__L9EcfAw-arKrXXVD-43eU4og/export?format=csv&gid=510782711"
MODPACKS_FOLDER = os.path.join(os.getcwd(), "Modpacks") # Folder to store downloaded modpacks
LIGHT_THEME = """
QWidget {
background-color: #fefefe; /* Set background color */
color: #000000; /* Set text color */
}
QMainWindow, QDialog, QWidget {
background-color: #fefefe; /* Force window background to white */
}
QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QSpinBox {
color: #000000;
}
QLineEdit {
border: 1px solid gray;
}
QPushButton {
border: 1px solid gray;
padding-top: 8px; /* Equivalent to ipady */
padding-bottom: 8px; /* Equivalent to ipady */
padding-left: 5px; /* Equivalent to ipadx */
padding-right: 5px; /* Equivalent to ipadx */
background-color: #fefefe; /* Default background color */
}
QPushButton:hover {
background-color: #dadada; /* Hover color */
}
QPushButton:pressed {
background-color: #fefefe; /* Press color */
}
QPushButton:disabled {
background-color: #e0e0e0; /* Disabled background color */
color: #a0a0a0; /* Disabled text color */
border: 1px solid #cccccc; /* Disabled border color */
}
QSpinBox {
padding: 10px; /* Set padding for spinbox */
border: 1px solid gray; /* Dropdown border */
}
QComboBox {
padding: 6px; /* Padding inside the dropdown */
font: 10pt 'Helvetica'; /* Font size for the dropdown */
background-color: #fefefe; /* Default background color */
border: 1px solid gray; /* Dropdown border */
}
QComboBox QLineEdit {
padding: 20px; /* Padding inside the editable field */
background-color: #fefefe; /* Background color for editable field */
border: none; /* Remove the border for the internal QLineEdit */
}
QCheckBox {
background-color: transparent; /* Transparent background for checkboxes */
}
QTabWidget::pane {
border: 1px solid #bbb;
padding: 6px;
}
QTabBar::tab {
color: black;
padding: 6px 14px;
border: 1px solid #aaa;
margin-right: 4px;
font-weight: bold;
font: 10pt 'Helvetica';
min-width: 110px;
}
QTabBar::tab:selected {
background: #0078d7;
color: white;
border: 1px solid #005ea0;
}
QTabBar::tab:hover {
background: #ccc;
color: white;
}
QCheckBox::indicator {
width: 24px;
height: 24px;
}
QCheckBox::indicator:unchecked {
image: url("ManagerSettings/assets/icons8-checkbox-unchecked.png");
}
QCheckBox::indicator:unchecked:hover {
image: url("ManagerSettings/assets/icons8-checkbox-hoverunchecked.png");
}
QCheckBox::indicator:checked {
image: url("ManagerSettings/assets/icons8-checkbox-checked.png");
}
QCheckBox::indicator:checked:hover {
image: url("ManagerSettings/assets/icons8-checkbox-hoverchecked.png");
}
QMenu {
background-color: #fefefe; /* Dark background */
border: 1px solid #555; /* Slightly lighter border */
padding: 5px;
font-size: 14px;
color: black;
}
QMenu::item {
padding: 5px 20px;
}
QMenu::item:selected {
background-color: #454545; /* Hover effect */
color: #000000;
}
QMenu::separator {
height: 1px;
background: #666; /* Separator color */
margin: 5px 10px;
}
"""
DARK_THEME = """
QWidget {
background-color: #222222; /* Set background color */
color: #ffffff; /* Set text color */
}
QMainWindow, QDialog, QWidget {
background-color: #222222; /* Force window background to white */
}
QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox, QSpinBox {
color: #ffffff;
}
QLineEdit {
border: 1px solid gray;
}
QPushButton {
border: 1px solid gray;
padding-top: 8px; /* Equivalent to ipady */
padding-bottom: 8px; /* Equivalent to ipady */
padding-left: 5px; /* Equivalent to ipadx */
padding-right: 5px; /* Equivalent to ipadx */
background-color: #222222; /* Default background color */
}
QPushButton:hover {
background-color: #dadada; /* Hover color */
}
QPushButton:pressed {
background-color: #222222; /* Press color */
}
QPushButton:disabled {
background-color: #e0e0e0; /* Disabled background color */
color: #a0a0a0; /* Disabled text color */
border: 1px solid #cccccc; /* Disabled border color */
}
QSpinBox {
padding: 10px; /* Set padding for spinbox */
border: 1px solid gray; /* Dropdown border */
}
QComboBox {
padding: 6px; /* Padding inside the dropdown */
font: 10pt 'Helvetica'; /* Font size for the dropdown */
background-color: #222222; /* Default background color */
border: 1px solid gray; /* Dropdown border */
}
QComboBox QLineEdit {
padding: 20px; /* Padding inside the editable field */
background-color: #222222; /* Background color for editable field */
border: none; /* Remove the border for the internal QLineEdit */
}
QCheckBox {
background-color: transparent; /* Transparent background for checkboxes */
}
QTabWidget::pane {
border: 1px solid #bbb;
padding: 6px;
}
QTabBar::tab {
color: white;
padding: 6px 14px;
border: 1px solid #aaa;
margin-right: 4px;
font-weight: bold;
font: 10pt 'Helvetica';
min-width: 110px;
}
QTabBar::tab:selected {
background: #0078d7;
color: white;
border: 1px solid #005ea0;
}
QTabBar::tab:hover {
background: #ccc;
color: black;
}
QCheckBox::indicator {
width: 24px;
height: 24px;
}
QCheckBox::indicator:unchecked {
image: url("ManagerSettings/assets/icons8-checkbox-uncheckedwhite.png");
}
QCheckBox::indicator:unchecked:hover {
image: url("ManagerSettings/assets/icons8-checkbox-uncheckedwhite.png");
}
QCheckBox::indicator:checked {
image: url("ManagerSettings/assets/icons8-checkbox-checkedwhite.png");
}
QCheckBox::indicator:checked:hover {
image: url("ManagerSettings/assets/icons8-checkbox-checkedwhite.png");
}
QMenu {
background-color: #222222; /* Dark background */
border: 1px solid #555; /* Slightly lighter border */
padding: 5px;
font-size: 14px;
color: white;
}
QMenu::item {
padding: 5px 20px;
}
QMenu::item:selected {
background-color: #454545; /* Hover effect */
color: #ffffff;
}
QMenu::separator {
height: 1px;
background: #666; /* Separator color */
margin: 5px 10px;
}
"""
def get_assets_path(filename):
"""Get the absolute path for assets."""
return os.path.abspath(os.path.join("ManagerSettings", "assets", filename))
# Ensure the Mods folder and required files exist
def ensure_settings_folder_exists():
if not os.path.exists(SETTINGS_FOLDER):
os.makedirs(SETTINGS_FOLDER)
print(f"Created Settings folder at: {SETTINGS_FOLDER}")
if not os.path.exists(ASSETS_FOLDER):
os.makedirs(ASSETS_FOLDER)
print(f"Created Assets folder at: {ASSETS_FOLDER}")
# Create default JSON files if they don't exist
for file_path, default_content in [
(SETTINGS_FILE, DEFAULT_SETTINGS),
(INSTALL_FILE, []),
(FAVORITES_FILE, [])
]:
if not os.path.exists(file_path):
with open(file_path, "w") as f:
json.dump(default_content, f, indent=4)
print(f"Created file: {file_path}")
ensure_settings_folder_exists()
def set_git_buffer_size():
try:
# Increase the buffer size globally
subprocess.run(['git', 'config', '--global', 'http.postBuffer', '524288000'], check=True)
subprocess.run(['git', 'config', '--global', 'http.maxRequestBuffer', '524288000'], check=True)
subprocess.run(['git', 'config', '--global', 'core.compression', '0'], check=True)
except subprocess.CalledProcessError as e:
print(f"Failed to set Git buffer size: {e}")
# Call this function before performing Git operations
set_git_buffer_size()
def cache_modpack_data(data):
"""Cache modpack data to a local JSON file."""
try:
with open(CACHE_FILE, "w") as f:
json.dump(data, f, indent=4)
print("Modpack data cached successfully.")
except Exception as e:
print(f"Failed to cache modpack data: {e}")
def load_cached_modpack_data():
"""Load cached modpack data, with a check for availability."""
try:
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, "r") as f:
print("Cached modpack data loaded.")
return json.load(f)
else:
print("No cached modpack data found.")
except Exception as e:
print(f"Failed to load cached modpack data: {e}")
return {}
def download_logo(url, save_path):
"""Download the logo from the given URL."""
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
with open(save_path, "wb") as f:
f.write(response.content)
print(f"Logo downloaded successfully: {save_path}")
except requests.RequestException as e:
print(f"Failed to download logo: {e}")
exit(1)
def download_and_extract_icons(url):
"""Download and extract icons from the specified URL into ManagerSettings/assets."""
try:
# Download the ZIP file
response = requests.get(url)
response.raise_for_status() # Check for request errors
# Extract the ZIP file into the assets directory
with zipfile.ZipFile(BytesIO(response.content)) as zip_ref:
zip_ref.extractall(ASSETS_FOLDER)
print("Icons downloaded and extracted successfully.")
except Exception as e:
print(f"An error occurred: {e}")
def remove_debug_folders(mods_directory):
"""
Check for folders other than 'Steamodded' that contain 'tk_debug_window.py'
and remove them.
"""
for folder in os.listdir(mods_directory):
folder_path = os.path.join(mods_directory, folder)
if folder != "Steamodded" and os.path.isdir(folder_path):
debug_file_path = os.path.join(folder_path, "tk_debug_window.py")
if os.path.isfile(debug_file_path):
print(f"Removing folder: {folder_path}")
shutil.rmtree(folder_path)
def is_online(test_url="https://www.google.com", parent=None):
"""Check if the system is connected to the internet."""
try:
response = requests.get(test_url, timeout=5)
return response.status_code == 200
except requests.RequestException:
if parent:
QMessageBox.warning(parent, "Offline Mode", "Unable to fetch modpack data. Using cached data if available.")
return False
def apply_debug_settings(self):
"""Enable or disable debug mode logging."""
debug_enabled = self.settings.get("debug_mode", False)
if debug_enabled:
logging.basicConfig(
filename="debug.log",
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.debug("Debug Mode Activated")
print("[DEBUG] Debug Mode Activated")
QMessageBox.information(self, "Debug Mode", "Debug Mode has been enabled. Logs will be saved to debug.log.")
else:
logging.disable(logging.CRITICAL) # Disable all logging
print("[DEBUG] Debug Mode Deactivated")
QMessageBox.warning(self, "Debug Mode", "Debug Mode has been disabled.")
############################################################
# Worker class for downloading/updating modpack in the background
############################################################
def fetch_modpack_data(url):
"""Fetch modpack data, with fallback to offline cache if offline."""
if is_online():
print("Online: Fetching modpack data...")
try:
response = requests.get(url)
response.raise_for_status() # Raise exception for HTTP errors
data = response.json() # Parse JSON data
cache_modpack_data(data) # Cache the data for offline use
return data
except requests.RequestException as e:
print(f"Failed to fetch data: {e}")
else:
print("Offline: Using cached modpack data.")
# Fallback to cached data if offline
return load_cached_modpack_data()
modpack_data = fetch_modpack_data(INFORMATION_URL)
# Extract `recommanded_lovely` if available
recommanded_lovely = modpack_data.get("recommanded_lovely", "https://github.com/ethangreen-dev/lovely-injector/releases/latest/download/")
print("Recommanded Lovely URL:", recommanded_lovely)
def fetch_dependencies(url):
"""
Fetch dependencies from the `information.json` file.
Args:
url (str): URL of the `information.json` file.
parent (QWidget or None): Optional parent for QMessageBox.
Returns:
dict: Dictionary of dependencies from the JSON file.
"""
if is_online():
print(f"Fetching dependencies from {url}...")
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
# Cache the dependencies locally
cache_modpack_data(data)
print("Dependencies fetched successfully:", data.get("dependencies", {}))
return data.get("dependencies", {})
except requests.RequestException as e:
print(f"Failed to fetch dependencies: {e}")
else:
print("Offline: Using cached dependency data.")
# Load cached data as fallback
cached_data = load_cached_modpack_data()
return cached_data.get("dependencies", {}) if cached_data else {}
dependencies = fetch_dependencies(INFORMATION_URL)
# Download and load CSV data
import io
def fetch_csv_data(url, parent=None):
"""
Fetch CSV data with fallback to offline mode and caching.
Args:
url (str): URL of the CSV file.
parent (QWidget or None): Optional parent for QMessageBox.
Returns:
pd.DataFrame or None: Pandas DataFrame with CSV data, or None on failure.
"""
if is_online():
print(f"Fetching CSV data from {url}...")
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
csv_data = response.text
# Save the CSV data to cache
with open(CSV_CACHE_FILE, "w", encoding="utf-8") as cache_file:
cache_file.write(csv_data)
print("CSV data cached successfully.")
# Load the data into a DataFrame
return pd.read_csv(io.StringIO(csv_data))
except requests.RequestException as e:
print(f"Error fetching CSV data: {e}")
if parent:
QMessageBox.warning(parent, "Offline Mode", "Failed to fetch CSV data. Using cached data if available.")
else:
print("Offline: Cannot fetch CSV data without an internet connection.")
if parent:
QMessageBox.information(parent, "Offline Mode", "No internet connection detected. Using cached CSV data.")
# Fallback to cached CSV data
return load_cached_csv_data()
def load_cached_csv_data():
"""
Load cached CSV data from the local file.
Returns:
pd.DataFrame or None: Cached CSV data as a DataFrame, or None if not available.
"""
try:
if os.path.exists(CSV_CACHE_FILE):
print("Loading cached CSV data...")
return pd.read_csv(CSV_CACHE_FILE)
else:
print("No cached CSV data found.")
except Exception as e:
print(f"Failed to load cached CSV data: {e}")
return None
# Process data to extract genres and tags
def process_genres_tags(data):
if 'Genre' not in data.columns or 'Tags' not in data.columns:
raise KeyError("Required columns 'Genre' and 'Tags' not found in the data.")
genres = data['Genre'].unique()
genre_tags = {}
for genre in genres:
tags = data[data['Genre'] == genre]['Tags'].dropna().astype(str).unique().tolist()
genre_tags[genre] = tags
return genre_tags
# Populate genres and tags in a QListWidget
def populate_genres_tags(list_widget, genre_tags):
for genre, tags in genre_tags.items():
# Add genre as a parent item
genre_item = QListWidgetItem(f"Genre: {genre}")
genre_item.setFlags(genre_item.flags()) # Non-editable
list_widget.addItem(genre_item)
# Add tags as child items
for tag in tags:
tag_item = QListWidgetItem(f" - Tag: {tag}")
tag_item.setFlags(tag_item.flags()) # Non-editable
list_widget.addItem(tag_item)
# Map mods to their metadata (Genre, Tags, and Description)
def map_mods_to_metadata(data):
metadata = {}
for _, row in data.iterrows():
folder_name = row['Folder Name'] # Folder Name
genre = row.get('Genre', "Unknown") # Genre
tags = row.get('Tags', "") # Tags
description = row.get('Description', "No description available.") # Description
page_link = row.get('Page Link', "") # Page Link
discord_link = row.get('Discord Link', "") # Discord Link
# Add data to metadata dictionary
metadata[folder_name] = {
"Genre": genre if pd.notna(genre) else "Unknown",
"Tags": [tag.strip() for tag in tags.split(',')] if pd.notna(tags) else [],
"Description": description.strip() if pd.notna(description) else "No description available.",
"Page Link": page_link.strip() if pd.notna(page_link) else "",
"Discord Link": discord_link.strip() if pd.notna(discord_link) else ""
}
return metadata
class ModpackDownloadWorker(QThread):
finished = pyqtSignal(bool, str)
progress = pyqtSignal(int) # Signal to update progress (optional)
def __init__(self, clone_url, repo_name, branch_name, force_update=False):
super().__init__()
self.clone_url = clone_url
self.repo_name = os.path.join(os.getcwd(), "Modpacks", repo_name)
self.branch_name = branch_name
self.force_update = force_update
self.process = None # Store the QProcess instance
def run(self):
try:
# Ensure the Modpacks folder exists
os.makedirs(os.path.dirname(self.repo_name), exist_ok=True)
# Check if the repository folder already exists
if os.path.exists(self.repo_name):
if self.force_update:
# Delete the existing folder if force_update is True
try:
shutil.rmtree(self.repo_name, onerror=readonly_handler)
print(f"Deleted existing folder: {self.repo_name}")
except Exception as e:
self.finished.emit(False, f"Failed to delete existing folder: {str(e)}")
return
else:
# If not forcing update, emit failure message
self.finished.emit(False, f"Modpack folder '{self.repo_name}' already exists. Enable force update to overwrite.")
return
if self.clone_url.endswith('.git'):
# Clone the repository using the selected branch
git_command = ["git", "clone", "--branch", self.branch_name, "--recurse-submodules", "--remote-submodules", self.clone_url, self.repo_name]
self.process = QProcess()
self.process.setProcessChannelMode(QProcess.ProcessChannelMode.MergedChannels)
# Connect QProcess signals for dynamic output handling
self.process.finished.connect(self.git_finished)
self.process.readyReadStandardOutput.connect(self.read_git_output)
self.process.start(git_command[0], git_command[1:])
self.process.waitForFinished(-1)
else:
# Download the file (this part will still emit the success message)
response = requests.get(self.clone_url, stream=True)
if response.status_code != 200:
self.finished.emit(False, f"File download failed: HTTP status {response.status_code}.")
return
total_size = int(response.headers.get('content-length', 0))
downloaded_size = 0
local_file_path = os.path.join(os.getcwd(), self.repo_name + '.zip')
with open(local_file_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
# Emit progress signal if you have a connected GUI progress bar
if total_size > 0:
progress_percent = int((downloaded_size / total_size) * 100)
self.progress.emit(progress_percent)
# Verify the file size after download
if downloaded_size != total_size:
self.finished.emit(False, "File download failed: Incomplete file.")
return
# Unzip if necessary
if zipfile.is_zipfile(local_file_path):
try:
with zipfile.ZipFile(local_file_path, 'r') as zip_ref:
zip_ref.extractall(self.repo_name)
os.remove(local_file_path)
except zipfile.BadZipFile:
self.finished.emit(False, "File download failed: Corrupt ZIP file.")
return
# If file download succeeds, emit success
self.finished.emit(True, f"Successfully downloaded {self.repo_name}.")
except Exception as e:
self.finished.emit(False, f"An unexpected error occurred: {str(e)}")
def read_git_output(self):
"""Capture real-time output from the Git process."""
output = bytes(self.process.readAllStandardOutput()).decode('utf-8')
print(output) # Optionally, update your GUI log or console with this output
def git_finished(self):
"""Callback for handling the QProcess finish signal for Git operations."""
# Capture standard output and error messages
output = self.process.readAllStandardOutput().data().decode('utf-8').strip()
error_msg = self.process.readAllStandardError().data().decode('utf-8').strip()
# Check for actual error conditions
if self.process.exitCode() == 0 and self.process.error() == QProcess.ProcessError.UnknownError:
# Success case: Repository should exist
if os.path.exists(self.repo_name) and os.listdir(self.repo_name):
self.finished.emit(True, f"Successfully cloned {self.repo_name}.")
else:
# Handle unexpected case where the repo doesn't exist after a 'successful' clone
self.finished.emit(False, f"Git clone succeeded but the folder {self.repo_name} is empty.")
else:
# Error case: Provide more detailed output
error_detail = error_msg if error_msg else (output if output else "An unknown error occurred.")
self.finished.emit(False, f"Git clone failed: {error_detail}")
self.process.readyReadStandardOutput.connect(self.capture_stdout)
self.process.readyReadStandardError.connect(self.capture_stderr)
def capture_stdout(self):
output = self.process.readAllStandardOutput().data().decode('utf-8').strip()
print(f"Standard Output: {output}")
def capture_stderr(self):
error_msg = self.process.readAllStandardError().data().decode('utf-8').strip()
print(f"Standard Error: {error_msg}")
def update_submodules(repo):
"""
Update submodules of a given repository, handling additions and removals.
Args:
repo (Repo): The GitPython Repo object representing the repository.
"""
try:
print("Synchronizing submodules...")
repo.git.submodule('sync') # Sync submodule URLs
print("Initializing new submodules...")
repo.git.submodule('init') # Initialize new submodules
print("Updating submodules recursively...")
repo.git.submodule('update', '--recursive', '--remote') # Update submodules
submodules_path = os.path.join(repo.working_tree_dir, '.gitmodules')
if not os.path.exists(submodules_path):
print(".gitmodules file not found. Skipping stale submodule cleanup.")
return
print("Cleaning up stale submodules...")
# Deinit stale submodules
repo.git.submodule('deinit', '--all', '--force')
# Remove cached and stale submodules
repo.git.rm('--cached', '-r', '--ignore-unmatch', submodules_path)
stale_paths = [
os.path.join(repo.working_tree_dir, submodule.path) for submodule in repo.submodules
]
for path in stale_paths:
if os.path.exists(path):
shutil.rmtree(path, ignore_errors=True)
print("Re-initializing submodules...")
repo.git.submodule('init')
repo.git.submodule('update', '--recursive', '--remote')
print("Submodules updated successfully.")
except GitCommandError as e:
print(f"Git command error: {e}")
raise
except Exception as e:
print(f"Unexpected error during submodule update: {e}")
raise
class ModpackUpdateWorker(QThread):
finished = pyqtSignal(bool, str) # Signal to indicate task completion with success status and message
progress = pyqtSignal(str) # Signal to report progress to the GUI
def __init__(self, repo_url, repo_name, branch_name, parent_folder):
super().__init__()
self.repo_url = repo_url
self.repo_name = repo_name
self.branch_name = branch_name
self.repo_path = os.path.join(parent_folder, self.repo_name)
def run(self):
try:
if not os.path.exists(self.repo_path) or not os.path.isdir(self.repo_path):
self.finished.emit(False, f"Invalid repository path: {self.repo_path}")
return
repo = Repo(self.repo_path)
# Handle uncommitted changes
try:
if repo.is_dirty(untracked_files=True):
self.progress.emit("Uncommitted changes detected. Resetting and cleaning repository...")
repo.git.reset('--hard') # Discard local changes
repo.git.clean('-fd') # Remove untracked files and directories
except GitCommandError as e:
self.finished.emit(False, f"Error resetting repository: {str(e)}")
return
# Pull the latest changes
self.progress.emit("Pulling latest changes...")
try:
repo.remotes.origin.pull()
except GitCommandError as e:
self.finished.emit(False, f"Error pulling latest changes: {str(e)}")
return
# Update submodules
self.progress.emit("Updating submodules...")
try:
self.update_submodules(repo)
except GitCommandError as e:
self.finished.emit(False, f"Error updating submodules: {str(e)}")
return
self.finished.emit(True, "Modpack and submodules updated successfully.")
except GitCommandError as e:
self.finished.emit(False, f"Git error: {str(e)}")
except Exception as e:
self.finished.emit(False, f"Unexpected error: {str(e)}")
def update_submodules(self, repo):
"""Update all submodules recursively."""
repo.git.submodule('update', '--init', '--recursive')
self.progress.emit("Submodules updated.")
############################################################
# Tutorial class
############################################################
class TutorialPopup(QDialog):
"""Floating, titleless popup to display tutorial instructions."""
def __init__(self, step_text, related_widget, main_window, parent=None):
super().__init__(parent)
self.main_window = main_window # Store the main window for use in positioning
self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
self.setWindowModality(Qt.WindowModality.ApplicationModal) # Modal
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
layout = QVBoxLayout()
# QLabel to display the tutorial text
self.label = QLabel(step_text)
# Custom stylesheet for the tutorial text
self.label.setStyleSheet("""
QLabel {
background-color: lightyellow;
color: #333333;
font: 10pt 'Helvetica';
padding: 10px;
border: 2px solid #0087eb;
}
""")
layout.addWidget(self.label)
self.setLayout(layout)
# Adjust the popup's position near the related widget
self.adjust_popup_position(related_widget)
def adjust_popup_position(self, related_widget):
"""Position the popup near the related widget and ensure it stays within the main window's bounds."""
main_window_geometry = self.main_window.geometry() # Get the main window size and position
widget_pos = related_widget.mapToGlobal(QPoint(0, related_widget.height())) # Get widget position
self.adjustSize() # Adjust popup size before positioning
popup_x = widget_pos.x()
popup_y = widget_pos.y()
# Ensure the popup stays within the main window bounds
popup_width = self.width()
popup_height = self.height()
main_window_right = main_window_geometry.x() + main_window_geometry.width()
main_window_left = main_window_geometry.x()
main_window_top = main_window_geometry.y()
main_window_bottom = main_window_geometry.y() + main_window_geometry.height()
# Correct if the popup goes off the right side of the main window
if popup_x + popup_width > main_window_right:
popup_x = main_window_right - popup_width - 10 # Adjust to fit within the right side
# Correct if the popup goes off the left side of the main window
if popup_x < main_window_left:
popup_x = main_window_left + 10 # Add margin to the left
# Correct if the popup goes off the bottom of the main window
if popup_y + popup_height > main_window_bottom:
popup_y = widget_pos.y() - popup_height - related_widget.height()
# Correct if the popup goes off the top of the main window
if popup_y < main_window_top:
popup_y = main_window_top + 10 # Add margin to the top
# Finally, move the popup to the adjusted position
self.move(popup_x, popup_y)
############################################################
# Main Program
############################################################
class ModpackManagerApp(QWidget): # or QMainWindow
def __init__(self, *args, **kwargs):
super(ModpackManagerApp, self).__init__(*args, **kwargs)
self.setWindowTitle("Dimserene's Modpack Manager")
if not os.path.exists(LOGO_PATH):
download_logo(LOGO_URL, LOGO_PATH)
# Load the splash screen
splash_pixmap = QPixmap(LOGO_PATH).scaled(
400, 400, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation
)
self.splash = QSplashScreen(splash_pixmap, Qt.WindowType.WindowStaysOnTopHint)
self.splash.showMessage(
"Loading Modpack Manager...",
Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignCenter,
Qt.GlobalColor.black,