-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
3885 lines (3674 loc) · 220 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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 html.parser
import json
import os
import stat
import platform
import queue
import re
import shutil
import subprocess
import sys
import threading
import time
import traceback
import webbrowser
import zipfile
from urllib.parse import urlparse
from packaging import version
from datetime import datetime, timezone
import logging
import uuid
import appdirs
import requests
import tkinter as tk
from dotenv import load_dotenv
from PIL import Image, ImageTk
from tkinter import ttk, filedialog, messagebox, simpledialog
load_dotenv()
def get_resource_path(filename):
if getattr(sys, 'frozen', False):
return os.path.join(os.path.dirname(sys.executable), filename)
else:
return os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
class LoggerWriter:
def __init__(self, level):
self.level = level
def write(self, message):
if message != '\n':
self.level(message)
def flush(self):
pass
class MLStripper(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs = True
self.text = []
def handle_data(self, d):
self.text.append(d)
def get_data(self):
return ''.join(self.text)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
def get_version():
if getattr(sys, 'frozen', False):
app_dir = os.path.dirname(sys.executable)
else:
app_dir = os.path.dirname(os.path.abspath(__file__))
version_file = os.path.join(app_dir, 'version.json')
try:
with open(version_file, 'r') as f:
version_data = json.load(f)
return version_data.get('version', 'Unknown')
except Exception as e:
logging.info(f'Error reading version file: {e}')
return 'Unknown'
class BuoyUI:
def __init__(self, root):
self.root = root
self.app_data_dir = appdirs.user_data_dir('Hook_Line_Sinker_Reborn', 'PawsHLSR')
self.setup_logging()
self.gui_queue = queue.Queue()
self.gdweave_queue = queue.Queue()
self.load_settings()
self.dark_mode_colors = {
'bg': '#2b2b2b', 'fg': '#ffffff', 'select_bg': '#404040',
'select_fg': '#ffffff', 'button_bg': '#404040', 'button_fg': '#ffffff',
'entry_bg': '#333333', 'entry_fg': '#ffffff', 'frame_bg': '#1e1e1e',
'frame_fg': '#ffffff', 'menu_bg': '#2b2b2b', 'menu_fg': '#ffffff',
'tab_bg': '#333333', 'tab_fg': '#ffffff', 'tab_selected_bg': '#404040',
'tab_selected_fg': '#ffffff', 'scrollbar_bg': '#404040',
'scrollbar_fg': '#666666', 'highlight_bg': '#3d6a99',
'highlight_fg': '#ffffff', 'error_bg': '#992e2e', 'error_fg': '#ffffff',
'success_bg': '#2e9959', 'success_fg': '#ffffff'
}
self.dark_mode = tk.BooleanVar(value=self.settings.get('dark_mode', True))
version = get_version()
self.root.title(f'Buoy v{version}')
if not self.settings.get('windowed_mode', True):
self.root.state('zoomed')
else:
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
window_width = 800
window_height = 640
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
self.root.geometry(f'{window_width}x{window_height}+{x}+{y}')
self.root.minsize(800, 640)
icon_path = get_resource_path('images/icon.ico')
if os.path.exists(icon_path):
if platform.system() == 'Windows':
self.root.iconbitmap(icon_path)
elif platform.system() == 'Linux':
img = tk.PhotoImage(file=icon_path)
self.root.tk.call('wm', 'iconphoto', self.root._w, img)
else:
logging.info('Warning: icon.ico not found')
self.app_data_dir = appdirs.user_data_dir('Hook_Line_Sinker_Reborn', 'PawsHLSR')
self.mods_dir = os.path.join(self.app_data_dir, 'mods')
self.mod_cache_file = os.path.join(self.app_data_dir, 'mod_cache.json')
os.makedirs(self.mods_dir, exist_ok=True)
self.available_mods = []
self.installed_mods = []
TOOLS = 'Tools'
COSMETICS = 'Cosmetics'
LIBRARIES = 'Libraries'
MODS = 'Mods'
MISC = 'Misc'
self.filtered_installed_mods = []
self.mod_categories = {}
self.available_sort_by = tk.StringVar(value=self.settings.get('available_sort_by', 'Last Updated'))
self.installed_sort_by = tk.StringVar(value=self.settings.get('installed_sort_by', 'Recently Installed'))
self.last_available_category = self.settings.get('available_category', 'All')
self.last_installed_category = self.settings.get('installed_category', 'All')
self.load_mod_cache()
self.mod_downloading = False
self.windowed_mode = tk.BooleanVar(value=self.settings.get('windowed_mode', True))
self.auto_update = tk.BooleanVar(value=self.settings.get('auto_update', True))
self.notifications = tk.BooleanVar(value=self.settings.get('notifications', False))
self.theme = tk.StringVar(value=self.settings.get('theme', 'System'))
self.show_nsfw = tk.BooleanVar(value=self.settings.get('show_nsfw', False))
self.show_deprecated = tk.BooleanVar(value=self.settings.get('show_deprecated', False))
self.game_path_entry = tk.StringVar(value=self.settings.get('game_path', ''))
logging.info(f'Initial game path: {self.game_path_entry.get()}')
self.create_status_bar()
self.notebook = None
self.mod_limit_disabled = False
self.create_rotating_backup()
logging.info('Made rotating backup')
self.create_main_ui()
if self.dark_mode.get():
self.toggle_dark_mode(show_restart_prompt=False)
self.mod_limit_disabled = False
self.show_discord_prompt()
self.check_for_duplicate_mods()
self.multi_mod_warning_shown = False
def create_server_browser_tab(self):
"""Creates the Server Browser tab and populates it with content."""
server_browser_frame = ttk.Frame(self.notebook)
self.notebook.add(server_browser_frame, text="Server Browser") # Add tab
# Define the server list table
self.server_list = ttk.Treeview(server_browser_frame)
self.server_list['columns'] = ('lobby_name', 'current_players', 'max_players', 'lobby_code', '18plus')
self.server_list.column("#0", width=0, stretch=tk.NO)
self.server_list.column("lobby_name", anchor=tk.W, width=200)
self.server_list.column("18plus", anchor=tk.W, width=30)
self.server_list.column("current_players", anchor=tk.W, width=100)
self.server_list.column("max_players", anchor=tk.W, width=100)
self.server_list.column("lobby_code", anchor=tk.W, width=100)
self.server_list.heading("#0", text="", anchor=tk.W)
self.server_list.heading("lobby_name", text="Lobby Name", anchor=tk.W)
self.server_list.heading("18plus", text="18+", anchor=tk.W)
self.server_list.heading("current_players", text="Current Players", anchor=tk.W)
self.server_list.heading("max_players", text="Max Players", anchor=tk.W)
self.server_list.heading("lobby_code", text="Lobby Code", anchor=tk.W)
self.server_list.pack(fill=tk.BOTH, expand=True)
# Initial update
self.update_server_list()
def update_server_list(self):
try:
# Fetch server data from the endpoint
response = requests.get('http://127.0.0.1:5000/servers', timeout=5)
response.raise_for_status() # Raise an error for HTTP issues
# Get the list of servers from the response
self.server_data = response.json().get('servers', [])
print(self.server_data)
# Clear the existing entries in the server list
self.server_list.delete(*self.server_list.get_children())
# Add new server data to the list
for server in self.server_data:
self.server_list.insert('', 'end', values=(
server.get('lobby_name', 'Unknown'),
server.get('current_players', 0),
server.get('max_players', 0),
server.get('lobby_code', 'N/A'),
"Yes" if server.get('18plus', False) else "No" # Display 'Yes' or 'No' for 18plus
))
except requests.exceptions.RequestException as e:
print(f"Error updating server list: {e}")
finally:
# Schedule the next update
self.root.after(15000, self.update_server_list) # Update every 15 seconds
def save_sort_preferences(self):
self.settings.update({'available_sort_by': self.available_sort_by.get(), 'installed_sort_by': self.installed_sort_by.get()})
self.save_settings()
def toggle_mod_limit(self):
self.mod_limit_disabled = not self.mod_limit_disabled
if self.mod_limit_disabled:
messagebox.showinfo('Easter Egg', 'Mod selection limit warnings disabled. Please be careful when installing mods.')
else:
messagebox.showinfo('Easter Egg', 'Mod selection limit warnings re-enabled.')
def toggle_dark_mode(self, show_restart_prompt=True):
is_dark = True
style = ttk.Style()
style.theme_use('default')
style.configure('TRadiobutton', background=self.dark_mode_colors['bg'], foreground=self.dark_mode_colors['fg'])
style.map('TRadiobutton', foreground=[('active', 'black')], background=[('active', self.dark_mode_colors['highlight_bg'])])
style.configure('TFrame', background=self.dark_mode_colors['bg'])
style.configure('TLabel', background=self.dark_mode_colors['bg'], foreground=self.dark_mode_colors['fg'])
style.configure('TButton', background=self.dark_mode_colors['button_bg'], foreground=self.dark_mode_colors['button_fg'])
style.map('TButton', background=[('disabled', '#555555'), ('active', self.dark_mode_colors['highlight_bg'])], foreground=[('disabled', '#999999')])
style.configure('TEntry', fieldbackground=self.dark_mode_colors['entry_bg'], foreground=self.dark_mode_colors['entry_fg'])
style.configure('TLabelframe', background=self.dark_mode_colors['bg'])
style.configure('TLabelframe.Label', background=self.dark_mode_colors['bg'], foreground=self.dark_mode_colors['fg'])
style.configure('TNotebook', background=self.dark_mode_colors['bg'])
style.configure('TNotebook.Tab', background=self.dark_mode_colors['tab_bg'], foreground=self.dark_mode_colors['tab_fg'], padding=[10, 2])
style.map('TNotebook.Tab', background=[('selected', self.dark_mode_colors['tab_selected_bg'])], foreground=[('selected', self.dark_mode_colors['tab_selected_fg'])], expand=[('selected', [1, 1, 1, 0])])
style.configure('Treeview', background=self.dark_mode_colors['bg'], foreground=self.dark_mode_colors['fg'], fieldbackground=self.dark_mode_colors['bg'])
style.configure('Treeview.Heading', background=self.dark_mode_colors['button_bg'], foreground=self.dark_mode_colors['button_fg'])
style.map('Treeview', background=[('selected', self.dark_mode_colors['select_bg'])], foreground=[('selected', self.dark_mode_colors['select_fg'])])
style.map('TCheckbutton', background=[('active', 'darkgrey')])
style.configure('TCheckbutton', indicatorbackground=self.dark_mode_colors['bg'], indicatorforeground='white', background=self.dark_mode_colors['bg'], foreground='white')
listboxes = [self.available_listbox, self.installed_listbox, self.mod_details, self.modpacks_listbox, self.modpack_details]
listboxes = [lb for lb in listboxes if lb is not None]
for listbox in listboxes:
listbox.configure(bg=self.dark_mode_colors['bg'], fg=self.dark_mode_colors['fg'], selectbackground=self.dark_mode_colors['select_bg'], selectforeground=self.dark_mode_colors['select_fg'])
self.root.configure(bg=self.dark_mode_colors['bg'])
def setup_logging(self):
log_dir = os.path.dirname(os.path.join(self.app_data_dir, 'latestlog.txt'))
os.makedirs(log_dir, exist_ok=True)
error_log = os.path.join(self.app_data_dir, 'latestlog.txt')
with open(error_log, 'w') as f:
f.write('=' * 80 + '\n')
f.write('Buoy Error Log\n')
f.write('This log only contains errors and important messages\n')
f.write('=' * 80 + '\n\n')
error_handler = logging.FileHandler(error_log, mode='a')
error_handler.setLevel(logging.ERROR)
error_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S'))
full_log = os.path.join(self.app_data_dir, 'fulllatestlog.txt')
with open(full_log, 'w') as f:
f.write('=' * 80 + '\n')
f.write('Buoy Full Debug Log\n')
f.write('This log contains all debug messages and program activity\n')
f.write('=' * 80 + '\n\n')
full_handler = logging.FileHandler(full_log, mode='a')
full_handler.setLevel(logging.DEBUG)
full_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S'))
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
root_logger.addHandler(error_handler)
root_logger.addHandler(full_handler)
sys.stdout = LoggerWriter(logging.info)
sys.stderr = LoggerWriter(logging.error)
def open_latest_log(self):
log_path = os.path.join(self.app_data_dir, 'latestlog.txt')
if os.path.exists(log_path):
with open(log_path, 'r') as f:
log_content = f.read()
log_window = tk.Toplevel(self.root)
log_window.title('Buoy Log')
log_window.geometry('800x600')
log_window.configure(background=self.dark_mode_colors['bg'])
icon_path = get_resource_path('images/icon.ico')
if os.path.exists(icon_path):
log_window.iconbitmap(icon_path)
main_frame = ttk.Frame(log_window)
main_frame.pack(expand=True, fill='both', padx=5, pady=5)
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_rowconfigure(0, weight=1)
text_frame = ttk.Frame(main_frame)
text_frame.grid(row=0, column=0, sticky='nsew')
text_frame.grid_columnconfigure(0, weight=1)
text_frame.grid_rowconfigure(0, weight=1)
log_text = tk.Text(text_frame, wrap=tk.NONE, font=('Consolas', 10), bg=self.dark_mode_colors['bg'], fg=self.dark_mode_colors['fg'])
log_text.grid(row=0, column=0, sticky='nsew')
scrollbar = ttk.Scrollbar(text_frame, orient='vertical', command=log_text.yview)
scrollbar.grid(row=0, column=1, sticky='ns')
log_text.config(yscrollcommand=scrollbar.set)
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=1, column=0, sticky='ew', pady=(5, 0))
button_frame.grid_columnconfigure(0, weight=1)
ttk.Button(button_frame, text='Copy to Clipboard', command=lambda: self.root.clipboard_append(log_text.get('1.0', tk.END))).grid(row=0, column=0)
ttk.Button(button_frame, text='Close', command=log_window.destroy).grid(row=0, column=1)
log_text.insert(tk.END, log_content)
log_text.config(state='disabled')
else:
messagebox.showerror('Error', 'Latest log file not found.')
def open_full_log(self):
log_path = os.path.join(self.app_data_dir, 'fulllatestlog.txt')
if os.path.exists(log_path):
with open(log_path, 'r') as f:
log_content = f.read()
log_window = tk.Toplevel(self.root)
log_window.title('Full Buoy Log')
log_window.geometry('800x600')
log_window.configure(background=self.dark_mode_colors['bg'])
icon_path = get_resource_path('images/icon.ico')
if os.path.exists(icon_path):
log_window.iconbitmap(icon_path)
main_frame = ttk.Frame(log_window)
main_frame.pack(expand=True, fill='both', padx=5, pady=5)
main_frame.grid_columnconfigure(0, weight=1)
main_frame.grid_rowconfigure(0, weight=1)
text_frame = ttk.Frame(main_frame)
text_frame.grid(row=0, column=0, sticky='nsew')
text_frame.grid_columnconfigure(0, weight=1)
text_frame.grid_rowconfigure(0, weight=1)
log_text = tk.Text(text_frame, wrap=tk.NONE, font=('Consolas', 10), bg=self.dark_mode_colors['bg'], fg=self.dark_mode_colors['fg'])
log_text.grid(row=0, column=0, sticky='nsew')
scrollbar = ttk.Scrollbar(text_frame, orient='vertical', command=log_text.yview)
scrollbar.grid(row=0, column=1, sticky='ns')
log_text.config(yscrollcommand=scrollbar.set)
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=1, column=0, sticky='ew', pady=(5, 0))
button_frame.grid_columnconfigure(0, weight=1)
ttk.Button(button_frame, text='Copy to Clipboard', command=lambda: self.root.clipboard_append(log_text.get('1.0', tk.END))).grid(row=0, column=0)
ttk.Button(button_frame, text='Close', command=log_window.destroy).grid(row=0, column=1)
log_text.insert(tk.END, log_content)
log_text.config(state='disabled')
else:
messagebox.showerror('Error', 'Full log file not found.')
def check_for_fresh_update(self):
current_version = version.parse(get_version())
if (last_update_version := self.settings.get('last_update_version')):
last_update_version = version.parse(last_update_version)
if current_version > last_update_version:
messagebox.showinfo('Update Complete', f'Buoy has been updated to version {current_version}.')
self.settings['last_update_version'] = str(current_version)
self.save_settings()
else:
self.settings['last_update_version'] = str(current_version)
self.save_settings()
def uninstall_gdweave(self):
if not self.settings.get('game_path'):
messagebox.showerror('Error', 'Game path not set. Please set the game path first.')
return
gdweave_path = os.path.join(self.settings['game_path'], 'GDWeave')
winmm_path = os.path.join(self.settings['game_path'], 'winmm.dll')
if not os.path.exists(gdweave_path) and (not os.path.exists(winmm_path)):
messagebox.showinfo('Info', 'GDWeave is not installed.')
return
if messagebox.askyesno('Confirm Uninstall', 'Are you sure you want to uninstall GDWeave? This will remove the GDWeave folder, all mods within it, and the winmm.dll file from your game directory.'):
try:
shutil.rmtree(gdweave_path, ignore_errors=True)
if os.path.exists(winmm_path):
os.remove(winmm_path)
remaining_files = []
if os.path.exists(gdweave_path):
remaining_files.append('GDWeave folder')
if os.path.exists(winmm_path):
remaining_files.append('winmm.dll')
if remaining_files:
warning_message = f"Some files could not be deleted: {', '.join(remaining_files)}. This may be due to insufficient permissions or open programs. Please close all related programs and try again."
messagebox.showwarning('Partial Uninstall', warning_message)
self.set_status('GDWeave partially uninstalled')
else:
self.settings['gdweave_version'] = None
self.save_settings()
self.set_status('GDWeave uninstalled successfully')
messagebox.showinfo('Success', 'GDWeave has been uninstalled successfully.')
self.update_setup_status()
logging.info('GDWeave uninstallation process completed.')
except Exception as e:
error_message = f'Failed to uninstall GDWeave: {str(e)}'
self.set_status(error_message)
messagebox.showerror('Error', error_message)
def create_main_ui(self):
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(expand=True, fill='both')
self.create_mod_manager_tab()
self.create_modpacks_tab()
# self.create_server_browser_tab() # WIP
self.create_game_manager_tab()
self.create_buoy_setup_tab()
self.create_settings_tab()
self.copy_existing_gdweave_mods()
self.load_available_mods()
self.refresh_mod_lists()
def create_mod_manager_tab(self):
mod_manager_frame = ttk.Frame(self.notebook)
self.notebook.add(mod_manager_frame, text='Mod Manager')
mod_manager_frame.grid_columnconfigure(0, weight=1)
mod_manager_frame.grid_columnconfigure(1, weight=0)
mod_manager_frame.grid_columnconfigure(2, weight=1)
mod_manager_frame.grid_rowconfigure(0, weight=3)
mod_manager_frame.grid_rowconfigure(1, weight=1)
available_frame = ttk.LabelFrame(mod_manager_frame, text='Thunderstore Mods (0)')
self.available_frame = available_frame
available_frame.grid(row=0, column=0, padx=5, pady=5, sticky='nsew')
available_frame.grid_columnconfigure(0, weight=1)
available_frame.grid_rowconfigure(0, weight=0)
available_frame.grid_rowconfigure(1, weight=0)
available_frame.grid_rowconfigure(2, weight=1)
search_frame = ttk.Frame(available_frame)
search_frame.grid(row=0, column=0, sticky='ew', padx=2, pady=2)
search_frame.grid_columnconfigure(1, weight=1)
ttk.Label(search_frame, text='Search:').grid(row=0, column=0, padx=5)
self.search_var = tk.StringVar()
self.search_var.trace('w', lambda name, index, mode: self.filter_available_mods())
search_entry = ttk.Entry(search_frame, textvariable=self.search_var)
search_entry.grid(row=0, column=1, sticky='ew', padx=5)
self.advanced_filters_visible = tk.BooleanVar(value=False)
ttk.Button(search_frame, text='Advanced Filters', command=self.toggle_advanced_filters).grid(row=0, column=2, padx=5)
self.filter_frame = ttk.LabelFrame(available_frame, text='Advanced Filters')
category_frame = ttk.Frame(self.filter_frame)
category_frame.pack(fill='x', padx=5, pady=2)
ttk.Label(category_frame, text='Category:').pack(side='left', padx=5)
self.available_category = ttk.Combobox(category_frame, state='readonly')
self.available_category.pack(side='left', fill='x', expand=True, padx=5)
self.available_category.bind('<<ComboboxSelected>>', lambda e: self.filter_available_mods())
sort_frame = ttk.Frame(self.filter_frame)
sort_frame.pack(fill='x', padx=5, pady=2)
ttk.Label(sort_frame, text='Sort:').pack(side='left', padx=5)
self.sort_method = ttk.Combobox(sort_frame, state='readonly', values=['Last Updated', 'Most Downloads', 'Most Likes', 'Name (A-Z)', 'Name (Z-A)'], textvariable=self.available_sort_by)
self.sort_method.pack(side='left', fill='x', expand=True, padx=5)
self.sort_method.bind('<<ComboboxSelected>>', lambda e: (self.filter_available_mods(), self.save_sort_preferences()))
toggle_frame = ttk.Frame(self.filter_frame)
toggle_frame.pack(fill='x', padx=5, pady=2)
ttk.Checkbutton(toggle_frame, text='Show NSFW', variable=self.show_nsfw, command=lambda: self.handle_filter_toggle('nsfw')).pack(side='left', padx=5)
ttk.Checkbutton(toggle_frame, text='Show Deprecated', variable=self.show_deprecated, command=lambda: self.handle_filter_toggle('deprecated')).pack(side='left', padx=5)
self.available_listbox = tk.Listbox(available_frame, width=30, height=15, selectmode=tk.EXTENDED)
self.available_listbox.grid(row=2, column=0, pady=(2, 2), padx=2, sticky='nsew')
self.available_listbox.bind('<<ListboxSelect>>', self.on_available_listbox_select)
self.available_listbox.bind('<Button-3>', self.show_context_menu)
scrollbar = ttk.Scrollbar(available_frame, orient='vertical', command=self.available_listbox.yview)
scrollbar.grid(row=2, column=1, sticky='ns')
self.available_listbox.configure(yscrollcommand=scrollbar.set)
action_frame = ttk.Frame(mod_manager_frame)
action_frame.grid(row=0, column=1, padx=5, pady=5, sticky='ns')
action_frame.grid_columnconfigure(0, weight=1)
self.game_management_frame = ttk.LabelFrame(action_frame, text='Launch Game')
self.game_management_frame.grid(row=1, column=0, pady=5, padx=5, sticky='ew')
self.game_management_frame.grid_columnconfigure(0, weight=1)
self.game_management_frame.grid_columnconfigure(1, weight=1)
ttk.Button(self.game_management_frame, text='Modded', command=self.launch_modded).grid(row=0, column=0, pady=2, padx=2, sticky='ew')
ttk.Button(self.game_management_frame, text='Vanilla', command=self.launch_vanilla).grid(row=0, column=1, pady=2, padx=2, sticky='ew')
self.mod_management_frame = ttk.LabelFrame(action_frame, text='Mod Management')
self.mod_management_frame.grid(row=2, column=0, pady=5, padx=5, sticky='ew')
self.mod_management_frame.grid_columnconfigure(0, weight=1)
self.mod_management_frame.grid_columnconfigure(1, weight=1)
ttk.Button(self.mod_management_frame, text='Install', command=self.install_mod).grid(row=0, column=0, pady=2, padx=2, sticky='ew')
ttk.Button(self.mod_management_frame, text='Uninstall', command=self.uninstall_mod).grid(row=0, column=1, pady=2, padx=2, sticky='ew')
ttk.Button(self.mod_management_frame, text='Enable', command=self.enable_mod).grid(row=1, column=0, pady=2, padx=2, sticky='ew')
ttk.Button(self.mod_management_frame, text='Disable', command=self.disable_mod).grid(row=1, column=1, pady=2, padx=2, sticky='ew')
ttk.Button(self.mod_management_frame, text='Edit Config', command=self.edit_mod_config).grid(row=2, column=0, pady=2, padx=2, sticky='ew')
ttk.Button(self.mod_management_frame, text='Version', command=self.show_version_selection).grid(row=2, column=1, pady=2, padx=2, sticky='ew')
misc_frame = ttk.LabelFrame(action_frame, text='Misc')
misc_frame.grid(row=3, column=0, pady=5, padx=5, sticky='ew')
misc_frame.grid_columnconfigure(0, weight=1)
ttk.Button(misc_frame, text='Import .zip Mods', command=self.import_zip_mod).grid(row=0, column=0, padx=2, pady=2, sticky='ew')
ttk.Button(misc_frame, text='Refresh Mods', command=self.refresh_all_mods).grid(row=1, column=0, pady=2, padx=2, sticky='ew')
ttk.Button(misc_frame, text='Check for Mod Updates', command=self.check_for_updates).grid(row=2, column=0, pady=2, padx=2, sticky='ew')
ttk.Button(misc_frame, text='Join Discord', command=lambda: webbrowser.open('https://discord.gg/7HdZJZbkhw')).grid(row=3, column=0, padx=2, pady=2, sticky='ew')
installed_frame = ttk.LabelFrame(mod_manager_frame, text='Installed Mods (0)')
self.installed_frame = installed_frame
installed_frame.grid(row=0, column=2, padx=5, pady=5, sticky='nsew')
installed_search_frame = ttk.Frame(installed_frame)
installed_search_frame.grid(row=0, column=0, sticky='ew', padx=2, pady=2)
installed_search_frame.grid_columnconfigure(1, weight=1)
ttk.Label(installed_search_frame, text='Search:').grid(row=0, column=0, padx=5)
self.installed_search_var = tk.StringVar()
self.installed_search_var.trace('w', lambda name, index, mode: self.filter_installed_mods())
installed_search_entry = ttk.Entry(installed_search_frame, textvariable=self.installed_search_var)
installed_search_entry.grid(row=0, column=1, sticky='ew', padx=5)
self.installed_filters_visible = tk.BooleanVar(value=False)
ttk.Button(installed_search_frame, text='Advanced Filters', command=self.toggle_installed_filters).grid(row=0, column=2, padx=5)
self.installed_filter_frame = ttk.LabelFrame(installed_frame, text='Advanced Filters')
installed_filter_frame = ttk.Frame(self.installed_filter_frame)
installed_filter_frame.pack(fill='x', padx=5, pady=2)
ttk.Label(installed_filter_frame, text='Category:').pack(side='left', padx=5)
self.installed_category = ttk.Combobox(installed_filter_frame, state='readonly')
self.installed_category.pack(side='left', fill='x', expand=True, padx=5)
self.installed_category.bind('<<ComboboxSelected>>', self.filter_installed_mods)
installed_sort_frame = ttk.Frame(self.installed_filter_frame)
installed_sort_frame.pack(fill='x', padx=5, pady=2)
ttk.Label(installed_sort_frame, text='Sort:').pack(side='left', padx=5)
self.installed_sort_method = ttk.Combobox(installed_sort_frame, state='readonly', values=['Name (A-Z)', 'Name (Z-A)', 'Recently Updated', 'Recently Installed'], textvariable=self.installed_sort_by)
self.installed_sort_method.pack(side='left', fill='x', expand=True, padx=5)
self.installed_sort_method.bind('<<ComboboxSelected>>', lambda e: (self.filter_installed_mods(), self.save_sort_preferences()))
self.hide_third_party = tk.BooleanVar(value=False)
ttk.Checkbutton(self.installed_filter_frame, text='Hide 3rd Party', variable=self.hide_third_party, command=self.filter_installed_mods).pack(fill='x', padx=5, pady=2)
self.installed_listbox = tk.Listbox(installed_frame, width=30, height=15, selectmode=tk.EXTENDED)
installed_scrollbar = ttk.Scrollbar(installed_frame, orient='vertical', command=self.installed_listbox.yview)
self.installed_listbox.configure(yscrollcommand=installed_scrollbar.set)
self.installed_listbox.grid(row=2, column=0, pady=2, padx=2, sticky='nsew')
installed_scrollbar.grid(row=2, column=1, pady=2, sticky='ns')
self.installed_listbox.bind('<<ListboxSelect>>', lambda e: (self.update_mod_details(e), self.update_button_states()))
self.installed_listbox.bind('<Button-3>', self.show_context_menu)
installed_frame.grid_columnconfigure(0, weight=1)
installed_frame.grid_rowconfigure(2, weight=1)
self.mod_details_frame = ttk.LabelFrame(mod_manager_frame, text='Mod Details')
self.mod_details_frame.grid(row=1, column=0, columnspan=3, padx=5, pady=5, sticky='nsew')
self.mod_image = ttk.Label(self.mod_details_frame)
self.mod_image.grid(row=0, column=0, padx=5, pady=5, sticky='nw')
self.mod_details = tk.Text(self.mod_details_frame, wrap=tk.WORD, height=12, state='disabled')
self.mod_details.grid(row=0, column=1, pady=2, padx=2, sticky='nsew')
self.mod_details_frame.grid_columnconfigure(1, weight=1)
self.mod_details_frame.grid_rowconfigure(0, weight=1)
self.update_button_states()
def create_modpacks_tab(self):
modpacks_frame = ttk.Frame(self.notebook)
self.notebook.add(modpacks_frame, text='Mod Profiles')
modpacks_frame.grid_columnconfigure(0, weight=1)
modpacks_frame.grid_rowconfigure(2, weight=1)
title_label = ttk.Label(modpacks_frame, text='Mod Profiles', font=('Helvetica', 16, 'bold'))
title_label.grid(row=0, column=0, pady=(20, 5), padx=20, sticky='w')
subtitle_label = ttk.Label(modpacks_frame, text='Create, import, export, and manage mod profiles', font=('Helvetica', 10, 'italic'))
subtitle_label.grid(row=1, column=0, pady=(0, 10), padx=20, sticky='w')
panels_container = ttk.Frame(modpacks_frame)
panels_container.grid(row=2, column=0, sticky='nsew', pady=5)
panels_container.grid_columnconfigure(0, weight=1)
panels_container.grid_columnconfigure(1, weight=1)
panels_container.grid_rowconfigure(0, weight=1)
left_frame = ttk.LabelFrame(panels_container, text='Available Mod Profiles')
left_frame.grid(row=0, column=0, sticky='nsew', padx=(5, 2.5))
left_frame.grid_columnconfigure(0, weight=1)
left_frame.grid_rowconfigure(1, weight=1)
self.modpacks_listbox = tk.Listbox(left_frame, width=45)
modpacks_scrollbar = ttk.Scrollbar(left_frame, orient='vertical', command=self.modpacks_listbox.yview)
self.modpacks_listbox.configure(yscrollcommand=modpacks_scrollbar.set)
self.modpacks_listbox.grid(row=1, column=0, sticky='nsew', padx=(5, 0), pady=5)
modpacks_scrollbar.grid(row=1, column=1, sticky='ns', pady=5, padx=(0, 5))
self.modpacks_listbox.bind('<<ListboxSelect>>', self.on_modpack_select)
buttons_frame = ttk.Frame(left_frame)
buttons_frame.grid(row=2, column=0, columnspan=2, sticky='ew', padx=5, pady=5)
buttons_frame.grid_columnconfigure(0, weight=1)
buttons_frame.grid_columnconfigure(1, weight=1)
ttk.Button(buttons_frame, text='Create', command=self.create_modpack_window).grid(row=0, column=0, padx=2, pady=2, sticky='ew')
ttk.Button(buttons_frame, text='Import', command=self.import_modpack).grid(row=0, column=1, padx=2, pady=2, sticky='ew')
ttk.Button(buttons_frame, text='Import JSON', command=self.import_json_modpack).grid(row=1, column=0, padx=2, pady=2, sticky='ew')
ttk.Button(buttons_frame, text='Delete', command=self.remove_modpack).grid(row=1, column=1, padx=2, pady=2, sticky='ew')
ttk.Button(buttons_frame, text='Apply Mod Profile', command=self.apply_modpack).grid(row=2, column=0, columnspan=2, padx=2, pady=2, sticky='nsew')
buttons_frame.grid_rowconfigure(2, weight=1)
right_frame = ttk.LabelFrame(panels_container, text='Mod Profile Details')
right_frame.grid(row=0, column=1, sticky='nsew', padx=(2.5, 5))
right_frame.grid_columnconfigure(0, weight=1)
right_frame.grid_rowconfigure(0, weight=1)
self.modpack_details = tk.Text(right_frame, wrap=tk.WORD)
details_scrollbar = ttk.Scrollbar(right_frame, orient='vertical', command=self.modpack_details.yview)
self.modpack_details.configure(yscrollcommand=details_scrollbar.set)
self.modpack_details.grid(row=0, column=0, sticky='nsew', padx=(5, 0), pady=5)
details_scrollbar.grid(row=0, column=1, sticky='ns', pady=5, padx=(0, 5))
self.modpack_details.config(state='disabled')
self.modpacks_dir = os.path.join(self.app_data_dir, 'modpacks')
os.makedirs(self.modpacks_dir, exist_ok=True)
self.refresh_modpacks_list()
def import_json_modpack(self):
file_path = filedialog.askopenfilename(filetypes=[('JSON files', '*.json')])
if not file_path:
return
try:
with open(file_path, 'r') as f:
modpack_info = json.load(f)
required_fields = ['name', 'author', 'description', 'mods']
if not all(field in modpack_info for field in required_fields):
raise Exception('Invalid mod profile format')
modpack_path = os.path.join(self.modpacks_dir, f"{modpack_info['name']}.json")
if os.path.exists(modpack_path):
if not messagebox.askyesno('Mod Profile Exists', 'Overwrite existing mod profile?'):
return
with open(modpack_path, 'w') as outfile:
json.dump(modpack_info, outfile, indent=4)
self.refresh_modpacks_list()
self.modpacks_listbox.selection_set(self.modpacks_listbox.get(0, tk.END).index(modpack_info['name']))
self.on_modpack_select(None)
if messagebox.askyesno('Import Success', 'Apply mod profile now?'):
self.apply_imported_modpack(modpack_info)
except Exception as e:
messagebox.showerror('Error', f'Failed to import mod profile: {str(e)}')
self.set_status(f'Failed to import mod profile: {str(e)}')
def apply_imported_modpack(self, modpack_info):
try:
for mod in self.installed_mods:
mod['enabled'] = False
self.save_mod_info(mod)
for mod_entry in modpack_info['mods']:
mod_id = mod_entry['id']
existing_mod = next((mod for mod in self.installed_mods if mod['id'] == mod_id), None)
if existing_mod:
if existing_mod.get('version') != mod_entry.get('version'):
if mod_entry.get('thunderstore_id'):
available_mod = next((mod for mod in self.available_mods if mod['thunderstore_id'] == mod_entry['thunderstore_id']), None)
if available_mod:
self.uninstall_mod_files(existing_mod)
temp_mod = available_mod.copy()
temp_mod.update({'version': mod_entry['version'], 'id': mod_id, 'third_party': mod_entry.get('third_party', False)})
self.download_and_install_mod(temp_mod)
continue
existing_mod['enabled'] = True
self.save_mod_info(existing_mod)
elif mod_entry.get('thunderstore_id'):
available_mod = next((mod for mod in self.available_mods if mod['thunderstore_id'] == mod_entry['thunderstore_id']), None)
if available_mod:
temp_mod = available_mod.copy()
temp_mod.update({'version': mod_entry['version'], 'id': mod_id, 'third_party': mod_entry.get('third_party', False)})
self.download_and_install_mod(temp_mod)
self.refresh_mod_lists()
messagebox.showinfo('Success', f"Mod profile '{modpack_info['name']}' applied successfully!")
self.set_status(f"Applied mod profile: {modpack_info['name']}")
except Exception as e:
error_message = f"Failed to apply mod profile: {str(e)}"
messagebox.showerror('Error', error_message)
self.set_status(error_message)
def create_modpack_window(self):
modpack_window = tk.Toplevel(self.root)
modpack_window.title('Create Mod Profile')
modpack_window.geometry('800x600')
modpack_window.configure(bg='#2b2b2b')
icon_path = get_resource_path('images/icon.ico')
if os.path.exists(icon_path):
modpack_window.iconbitmap(icon_path)
modpack_window.grid_columnconfigure(0, weight=1)
modpack_window.grid_columnconfigure(1, weight=1)
modpack_window.grid_rowconfigure(1, weight=1)
info_frame = ttk.LabelFrame(modpack_window, text='Mod Profile Information')
info_frame.grid(row=0, column=0, columnspan=2, padx=5, pady=5, sticky='ew')
ttk.Label(info_frame, text='Name:').grid(row=0, column=0, padx=5, pady=5)
name_entry = ttk.Entry(info_frame)
name_entry.grid(row=0, column=1, padx=5, pady=5, sticky='ew')
ttk.Label(info_frame, text='Author:').grid(row=1, column=0, padx=5, pady=5)
author_entry = ttk.Entry(info_frame)
author_entry.grid(row=1, column=1, padx=5, pady=5, sticky='ew')
ttk.Label(info_frame, text='Description:').grid(row=2, column=0, padx=5, pady=5)
description_text = tk.Text(info_frame, height=3, bg='#2b2b2b', fg='white', insertbackground='white')
description_text.grid(row=2, column=1, padx=5, pady=5, sticky='ew')
ttk.Label(info_frame, text='Pastebin API Key:').grid(row=3, column=0, padx=5, pady=5)
pastebin_api_key_entry = ttk.Entry(info_frame, show='*')
pastebin_api_key_entry.grid(row=3, column=1, padx=5, pady=5, sticky='ew')
ttk.Button(info_frame, text='Get API Key', command=lambda: webbrowser.open('https://pastebin.com/doc_api')).grid(row=4, column=1, padx=5, pady=5)
installed_frame = ttk.LabelFrame(modpack_window, text='Installed Mods')
installed_frame.grid(row=1, column=0, padx=5, pady=5, sticky='nsew')
installed_listbox = tk.Listbox(installed_frame, selectmode=tk.EXTENDED, bg='#2b2b2b', fg='white', selectbackground='grey', selectforeground='#2b2b2b')
installed_listbox.pack(fill='both', expand=True, padx=5, pady=5)
modpack_frame = ttk.LabelFrame(modpack_window, text='Profile Mods')
modpack_frame.grid(row=1, column=1, padx=5, pady=5, sticky='nsew')
modpack_listbox = tk.Listbox(modpack_frame, selectmode=tk.EXTENDED, bg='#2b2b2b', fg='white', selectbackground='grey', selectforeground='#2b2b2b')
modpack_listbox.pack(fill='both', expand=True, padx=5, pady=5)
for mod in self.installed_mods:
if not mod.get('third_party', False):
installed_listbox.insert(tk.END, mod['title'])
def add_enabled_mods_to_modpack_list():
enabled_mods = [mod['title'] for mod in self.installed_mods if mod.get('enabled', False)]
for mod in enabled_mods:
if mod not in modpack_listbox.get(0, tk.END):
modpack_listbox.insert(tk.END, mod)
def add_to_modpack():
selections = installed_listbox.curselection()
for index in selections:
mod_name = installed_listbox.get(index)
if mod_name not in modpack_listbox.get(0, tk.END):
modpack_listbox.insert(tk.END, mod_name)
def remove_from_modpack():
selections = modpack_listbox.curselection()
for index in reversed(selections):
modpack_listbox.delete(index)
def export_modpack():
if not name_entry.get().strip() or not author_entry.get().strip():
messagebox.showerror('Error', 'Please enter a name and author for the modpack.')
return
modpack_info = {
'name': name_entry.get().strip(),
'author': author_entry.get().strip(),
'description': description_text.get('1.0', tk.END).strip(),
'mods': [{'id': mod['id'], 'title': mod['title'], 'version': mod.get('version', 'Unknown'), 'thunderstore_id': mod.get('thunderstore_id')} for mod in self.installed_mods if mod['title'] in modpack_listbox.get(0, tk.END) and (not mod.get('third_party', False))],
'created': datetime.now().isoformat()
}
json_data = json.dumps(modpack_info, indent=2)
file_path = filedialog.asksaveasfilename(title='Export Modpack as JSON', defaultextension='.json', filetypes=[('JSON files', '*.json')])
if file_path:
with open(file_path, 'w') as f:
f.write(json_data)
messagebox.showinfo('Success', 'Modpack exported successfully!')
def save_modpack():
name = name_entry.get().strip()
author = author_entry.get().strip()
api_dev_key = pastebin_api_key_entry.get()
description = description_text.get('1.0', tk.END).strip()
if not name:
messagebox.showerror('Error', 'Please enter a mod profile name')
return
modpack_mods = list(modpack_listbox.get(0, tk.END))
if not modpack_mods:
messagebox.showerror('Error', 'Please add at least one mod to the mod profile')
return
modpack_info = {'name': name, 'author': author, 'description': description, 'created': datetime.now().isoformat(), 'mods': [{'id': mod['id'], 'title': mod['title'], 'version': mod.get('version', 'Unknown'), 'thunderstore_id': mod.get('thunderstore_id')} for mod in self.installed_mods if mod['title'] in modpack_mods and (not mod.get('third_party', False))]}
try:
modpack_filename = f'{name}.json'
modpack_path = os.path.join(self.modpacks_dir, modpack_filename)
existing_paste_id = None
if os.path.exists(modpack_path):
if not messagebox.askyesno('Mod Profile Exists', 'A mod profile with this name already exists. Do you want to overwrite it?'):
return
try:
with open(modpack_path, 'r') as f:
existing_data = json.load(f)
existing_paste_id = existing_data.get('paste_id')
except:
pass
json_data = json.dumps(modpack_info, indent=2)
api_url = 'https://pastebin.com/api/api_post.php'
data = {'api_dev_key': api_dev_key, 'api_option': 'paste', 'api_paste_code': json_data, 'api_paste_name': f'Buoy Mod Profile - {name}', 'api_paste_format': 'json', 'api_paste_private': '0', 'api_paste_expire_date': 'N'}
response = requests.post(api_url, data=data)
if response.status_code == 200 and response.text.startswith('https://pastebin.com/'):
paste_id = response.text.split('/')[-1]
modpack_info['paste_id'] = paste_id
with open(modpack_path, 'w') as f:
json.dump(modpack_info, f, indent=2)
if existing_paste_id:
message = f'Mod profile updated successfully!\nPrevious share code: {existing_paste_id}\nNew share code: {paste_id}\nThe new code has been copied to your clipboard.'
else:
message = f'Mod profile created successfully!\nShare this code with others: {paste_id}\nIt has also been copied to your clipboard.'
messagebox.showinfo('Success', message)
self.root.clipboard_clear()
self.root.clipboard_append(paste_id)
self.root.update()
self.refresh_modpacks_list()
for i in range(self.modpacks_listbox.size()):
if self.modpacks_listbox.get(i) == name:
self.modpacks_listbox.selection_clear(0, tk.END)
self.modpacks_listbox.selection_set(i)
self.modpacks_listbox.see(i)
self.on_modpack_select(None)
break
modpack_window.destroy()
else:
raise Exception(f'Failed to create paste: {response.text}')
except Exception as e:
error_message = f'Failed to create mod profile: {str(e)}'
messagebox.showerror('Error', error_message)
buttons_frame = ttk.Frame(modpack_window)
buttons_frame.grid(row=2, column=0, columnspan=2, pady=5)
ttk.Button(buttons_frame, text='Add Selected', command=add_to_modpack).pack(side='left', padx=5)
ttk.Button(buttons_frame, text='Remove Selected', command=remove_from_modpack).pack(side='left', padx=5)
ttk.Button(buttons_frame, text='Add Enabled Mods', command=add_enabled_mods_to_modpack_list).pack(side='left', padx=5)
ttk.Button(buttons_frame, text='Export as JSON', command=export_modpack).pack(side='left', padx=5)
ttk.Button(buttons_frame, text='Save Profile', command=save_modpack).pack(side='left', padx=5)
ttk.Button(buttons_frame, text='Cancel', command=modpack_window.destroy).pack(side='left', padx=5)
def import_modpack(self):
paste_id = simpledialog.askstring('Import Mod Profile', 'Enter the mod profile code:')
if not paste_id:
return
try:
response = requests.get(f'https://pastebin.com/raw/{paste_id}')
if response.status_code != 200:
raise Exception('Failed to fetch mod profile data')
modpack_info = json.loads(response.text)
required_fields = ['name', 'author', 'description', 'mods']
if not all((field in modpack_info for field in required_fields)):
raise Exception('Invalid mod profile format')
modpack_info['paste_id'] = paste_id
modpack_filename = f"{modpack_info['name']}.json"
modpack_path = os.path.join(self.modpacks_dir, modpack_filename)
if os.path.exists(modpack_path):
if not messagebox.askyesno('Mod Profile Exists', 'A mod profile with this name already exists. Do you want to overwrite it?'):
return
with open(modpack_path, 'w') as f:
json.dump(modpack_info, f, indent=2)
self.refresh_modpacks_list()
for i in range(self.modpacks_listbox.size()):
if self.modpacks_listbox.get(i) == modpack_info['name']:
self.modpacks_listbox.selection_clear(0, tk.END)
self.modpacks_listbox.selection_set(i)
self.modpacks_listbox.see(i)
self.on_modpack_select(None)
break
if messagebox.askyesno('Import Success', 'Mod profile imported successfully! Would you like to apply it now?'):
self.apply_modpack()
except Exception as e:
error_message = f'Failed to import mod profile: {str(e)}'
messagebox.showerror('Error', error_message)
self.set_status(error_message)
def refresh_modpacks_list(self):
self.modpacks_listbox.delete(0, tk.END)
for file in os.listdir(self.modpacks_dir):
if file.endswith('.json'):
self.modpacks_listbox.insert(tk.END, file[:-5])
def on_modpack_select(self, event):
selected = self.modpacks_listbox.curselection()
if not selected:
return
modpack_name = self.modpacks_listbox.get(selected[0])
modpack_path = os.path.join(self.modpacks_dir, f'{modpack_name}.json')
try:
with open(modpack_path, 'r') as f:
modpack_info = json.load(f)
self.modpack_details.config(state='normal')
self.modpack_details.delete(1.0, tk.END)
self.modpack_details.insert(tk.END, f"Name: {modpack_info['name']}\n")
self.modpack_details.insert(tk.END, f"Author: {modpack_info['author']}\n")
created_date = datetime.fromisoformat(modpack_info['created'])
formatted_date = created_date.strftime('%I:%M%p %d/%m/%Y')
self.modpack_details.insert(tk.END, f'Created: {formatted_date}\n')
if 'paste_id' in modpack_info:
self.modpack_details.insert(tk.END, f"Share Code: {modpack_info['paste_id']}\n")
self.modpack_details.insert(tk.END, f"\nDescription:\n{modpack_info['description']}\n\n")
self.modpack_details.insert(tk.END, 'Included Mods:\n')
for mod in modpack_info['mods']:
self.modpack_details.insert(tk.END, f"• {mod['title']} v{mod['version']}\n")
self.modpack_details.config(state='disabled')
except Exception as e:
messagebox.showerror('Error', f'Failed to load mod profile details: {str(e)}')
def apply_modpack(self):
selected = self.modpacks_listbox.curselection()
if not selected:
messagebox.showerror('Error', 'Please select a mod profile to apply.')
return
modpack_name = self.modpacks_listbox.get(selected[0])
modpack_path = os.path.join(self.modpacks_dir, f'{modpack_name}.json')
if messagebox.askyesno('Confirm Apply', 'Applying this mod profile will disable all current mods and enable only the mods in the mod profile. Continue?'):
try:
with open(modpack_path) as f:
modpack_info = json.load(f)
for mod in self.installed_mods:
mod['enabled'] = False
self.save_mod_info(mod)
for mod_entry in modpack_info['mods']:
mod_id = mod_entry['id']
existing_mod = next((mod for mod in self.installed_mods if mod['id'] == mod_id), None)
if existing_mod:
if existing_mod.get('version') != mod_entry.get('version'):
if mod_entry.get('thunderstore_id'):
available_mod = next((mod for mod in self.available_mods if mod['thunderstore_id'] == mod_entry['thunderstore_id']), None)
if available_mod:
self.uninstall_mod_files(existing_mod)
temp_mod = available_mod.copy()
temp_mod.update({'version': mod_entry['version'], 'id': mod_id, 'third_party': mod_entry.get('third_party', False)})
self.download_and_install_mod(temp_mod)
continue
existing_mod['enabled'] = True
self.save_mod_info(existing_mod)
elif mod_entry.get('thunderstore_id'):
available_mod = next((mod for mod in self.available_mods if mod['thunderstore_id'] == mod_entry['thunderstore_id']), None)
if available_mod:
temp_mod = available_mod.copy()
temp_mod.update({'version': mod_entry['version'], 'id': mod_id, 'third_party': mod_entry.get('third_party', False)})
self.download_and_install_mod(temp_mod)
self.refresh_mod_lists()
messagebox.showinfo('Success', f"Mod profile '{modpack_name}' applied successfully!")
self.set_status(f'Applied mod profile: {modpack_name}')
except Exception as e:
error_message = f'Failed to apply mod profile: {str(e)}'
messagebox.showerror('Error', error_message)
self.set_status(error_message)
def save_mod_info(self, mod):
"""Saves the mod information to its mod_info.json file"""
try:
if mod.get('third_party', False):
mod_dir = os.path.join(self.mods_dir, '3rd_party', mod['id'])
else:
mod_dir = os.path.join(self.mods_dir, mod['id'])
mod_info_path = os.path.join(mod_dir, 'mod_info.json')
with open(mod_info_path, 'w') as f:
json.dump(mod, f, indent=2)
self.save_mod_status(mod)
except Exception as e:
error_message = f"Failed to save mod info for {mod.get('title', 'Unknown')}: {str(e)}"
self.set_status(error_message)
logging.error(error_message)
def remove_modpack(self):
selected = self.modpacks_listbox.curselection()
if not selected:
messagebox.showerror('Error', 'Please select a mod profile to remove.')
return
modpack_name = self.modpacks_listbox.get(selected[0])
modpack_path = os.path.join(self.modpacks_dir, f'{modpack_name}.json')
if messagebox.askyesno('Confirm Remove', 'Do you want to remove this mod profile?'):
try:
os.remove(modpack_path)
self.refresh_mod_lists()
self.refresh_modpacks_list()
self.set_status(f'Removed mod profile: {modpack_name}')
except Exception as e:
error_message = f'Failed to remove mod profile: {str(e)}'
messagebox.showerror('Error', error_message)
self.set_status(error_message)
def toggle_advanced_filters(self):
if self.advanced_filters_visible.get():
self.filter_frame.grid_remove()
self.advanced_filters_visible.set(False)
else:
self.filter_frame.grid(row=1, column=0, sticky='ew', padx=2, pady=2)
self.advanced_filters_visible.set(True)
def toggle_installed_filters(self):
if self.installed_filters_visible.get():
self.installed_filter_frame.grid_remove()
self.installed_filters_visible.set(False)
else:
self.installed_filter_frame.grid(row=1, column=0, sticky='ew', padx=2, pady=2)
self.installed_filters_visible.set(True)
def view_deprecated_mods_list(self):
messagebox.showinfo('Deprecated Mods List', "This will open a new tab with the deprecated mods list. Note that these mods may be outdated, broken, or no longer work. If you download one, you'll need to import it via the 'Import ZIP' option.")
webbrowser.open('https://notnite.github.io/webfishing-mods')
def on_available_listbox_select(self, event):
self.update_mod_details(event)
self.check_selection_limit(event)
self.update_button_states()
def update_button_states(self):
available_selected = bool(self.available_listbox.curselection())
installed_selected = bool(self.installed_listbox.curselection())
selected_mod = None
if installed_selected:
selected_indices = self.get_selected_installed_mod_indices()
if selected_indices:
selected_mod = self.filtered_installed_mods[selected_indices[0]]
for child in self.mod_management_frame.winfo_children():
if isinstance(child, ttk.Button):
text = child.cget('text')
if text == 'Install':
child.configure(state='normal' if available_selected else 'disabled')
elif text == 'Edit Config':
has_config = selected_mod and self.mod_has_config(selected_mod)
child.configure(state='normal' if installed_selected and has_config else 'disabled')
elif text in ['Uninstall', 'Enable', 'Disable']:
child.configure(state='normal' if installed_selected else 'disabled')
elif text == 'Version':
child.configure(state='normal' if installed_selected else 'disabled')
start_game_btn = self.game_management_frame.winfo_children()[0]
start_game_btn.configure(state='normal' if self.check_setup() else 'disabled')
def check_selection_limit(self, event):
listbox = event.widget
if listbox != self.available_listbox:
return
if self.mod_limit_disabled:
return
selected = listbox.curselection()
actual_mods = [i for i in selected if not listbox.get(i).startswith('--')]
if len(actual_mods) > 10:
listbox.selection_clear(0, tk.END)
for i in actual_mods[:10]: