-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
1876 lines (1683 loc) · 84.3 KB
/
main.py
File metadata and controls
1876 lines (1683 loc) · 84.3 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
#Copyright (C) 2024 QWERTZexe
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License as published
#by the Free Software Foundation, either version 3 of the License, or
#any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Affero General Public License for more details.
#
#You should have received a copy of the GNU Affero General Public License
#along with this program. If not, see <https://www.gnu.org/licenses/>.
######################################################
### MAIN ###
import sys, os, json, subprocess, shutil, zipfile
import uuid as uuuid
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel, QComboBox, QMessageBox, QToolBar, QGridLayout, QFrame,QMainWindow,QStyle,QStyleOption,QStylePainter,QScrollArea,QVBoxLayout,QMenu,QFileDialog,QDialog,QLineEdit,QLineEdit, QToolButton,QHBoxLayout,QHBoxLayout,QSizePolicy,QListWidget,QProgressBar,QVBoxLayout,QCheckBox,QListWidgetItem
from PyQt6.QtCore import Qt, QSize,QUrl,pyqtSignal,QThread
import minecraft_launcher_lib as mc
import threading, requests
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtGui import QFont, QIcon, QPalette, QColor,QImage,QPixmap,QAction
cwd = os.path.dirname(os.path.abspath(sys.argv[0]))
os.chdir(cwd)
if not os.path.exists(f"{cwd}/profiles.json"):
with open(f"{cwd}/profiles.json","w") as f:
json.dump({"profiles":[]},f,indent=2)
if not os.path.exists(f"{cwd}/accounts.json"):
with open(f"{cwd}/accounts.json","w") as f:
json.dump({"accounts":[{"username":"USERNAME","uuid":"8be48703-76cc-4403-b631-fee288045323","token":"fake_token"}],"active":"USERNAME","refresh":{"start":"1","launch":"0"}},f,indent=2)
if not os.path.exists(f"{cwd}/.minecraft"):
os.makedirs(f"{cwd}/.minecraft",exist_ok=True)
try:
import pyi_splash # type: ignore
pyi_splash.update_text('REFRESHING TOKENS...')
except:
pass
mcdir = f"{cwd}/.minecraft"
CLIENT_ID = "3d006e3a-abc5-4c7f-af37-d4f2104128f5"
REDIRECT_URL = "https://login.microsoftonline.com/common/oauth2/nativeclient/"
HEADERS = {
'User-Agent': 'github.com/QWERTZexe/QWERTZ-Launcher | QWERTZ Launcher 2.1',
}
with open(f"{cwd}/accounts.json", "r", encoding="utf-8") as f:
accounts = json.load(f)
if accounts["refresh"]["start"] == "1":
for account in accounts["accounts"]:
index = accounts["accounts"].index(account)
try:
refresh_token = account["refresh_token"]
except:
refresh_token = None
if refresh_token:
try:
account_informaton = mc.microsoft_account.complete_refresh(CLIENT_ID, None, REDIRECT_URL, refresh_token)
username = account_informaton["name"]
uuid = account_informaton["id"]
token = account_informaton["access_token"]
accounts["accounts"][index]["username"] = username
accounts["accounts"][index]["uuid"] = uuid
accounts["accounts"][index]["token"] = token
with open(f"{cwd}/accounts.json","w") as f:
json.dump(accounts,f)
except:
pass
class ModManagerDialog(QDialog):
def __init__(self, parent=None, profile=None):
super().__init__(parent)
self.setWindowTitle("Mod Manager")
self.profile = profile
layout = QVBoxLayout()
self.setLayout(layout)
self.mod_list = QListWidget()
layout.addWidget(self.mod_list)
self.populate_mod_list()
remove_button = QPushButton("Remove Selected Mod")
remove_button.clicked.connect(self.remove_selected_mod)
layout.addWidget(remove_button)
def populate_mod_list(self):
mod_dir = f"{cwd}/profiles/{self.profile.name}/mods/"
if os.path.exists(mod_dir):
for mod_file in os.listdir(mod_dir):
mod_item = QListWidgetItem(mod_file)
self.mod_list.addItem(mod_item)
def remove_selected_mod(self):
selected_mod = self.mod_list.currentItem()
if selected_mod:
mod_name = selected_mod.text()
mod_path = f"{cwd}/profiles/{self.profile.name}/mods/{mod_name}"
reply = QMessageBox.question(self, 'Confirm', f'Are you sure you want to remove the mod "{mod_name}"?', QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
os.remove(mod_path)
self.mod_list.takeItem(self.mod_list.row(selected_mod))
else:
QMessageBox.warning(self, "No Mod Selected", "Please select a mod to remove.")
class DownloadModThread(QThread):
progress_updated = pyqtSignal(int)
finished = pyqtSignal(bool)
def __init__(self, download_url, download_path):
super().__init__()
self.download_url = download_url
self.download_path = download_path
def run(self):
try:
response = requests.get(self.download_url, stream=True,headers=HEADERS)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
block_size = 1024
progress = 0
with open(self.download_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=block_size):
if chunk:
file.write(chunk)
progress += len(chunk)
self.progress_updated.emit(int((progress / total_size) * 100))
self.finished.emit(True)
except Exception as e:
QMessageBox.critical(None, "Error", str(e))
self.finished.emit(False)
class CurseForgeModBrowserDialog(QDialog):
def __init__(self, parent=None, minecraft_version=None, loader=None, name=None):
super().__init__(parent)
self.setWindowTitle("CurseForge Mod Browser")
self.setGeometry(300, 300, 600, 500)
self.minecraft_version = minecraft_version
self.loader = loader
self.name = name
layout = QVBoxLayout()
self.setLayout(layout)
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Search for mods...")
layout.addWidget(self.search_input)
self.search_button = QPushButton("Search")
self.search_button.clicked.connect(self.search_mods)
layout.addWidget(self.search_button)
self.mod_list = QListWidget()
self.mod_list.itemSelectionChanged.connect(self.display_mod_versions)
layout.addWidget(self.mod_list)
self.version_list = QListWidget()
layout.addWidget(self.version_list)
self.show_incompatible_checkbox = QCheckBox("Show Incompatible Versions", self)
self.show_incompatible_checkbox.stateChanged.connect(self.display_mod_versions)
layout.addWidget(self.show_incompatible_checkbox)
self.add_button = QPushButton("Add Selected Version")
self.add_button.clicked.connect(self.add_selected_version)
layout.addWidget(self.add_button)
self.progress_bar = QProgressBar()
layout.addWidget(self.progress_bar)
def search_mods(self):
search_query = self.search_input.text()
mlt = "1" if self.loader == "forge" else "4" if self.loader == "fabric" else ""
response = requests.get(f"https://api.curse.tools/v1/cf/mods/search?gameId=432&searchFilter={search_query}&classId=6&modLoaderType={mlt}", headers=HEADERS)
if response.status_code == 200:
mods = response.json()["data"]
self.mod_list.clear()
for mod in mods:
item = QListWidgetItem(mod["name"])
try:
item.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(requests.get(mod["logo"]["url"], headers=HEADERS).content))))
except:
with open(f"{cwd}/icons/curseforge.png","rb") as f:
ico = f.read()
item.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(ico))))
item.setData(Qt.ItemDataRole.UserRole, mod["id"])
self.mod_list.addItem(item)
else:
QMessageBox.warning(self, "Error", "Failed to fetch mods.")
def display_mod_versions(self):
if self.mod_list.selectedItems():
item = self.mod_list.selectedItems()[0]
mod_id = item.data(Qt.ItemDataRole.UserRole)
response = requests.get(f"https://api.curse.tools/v1/cf/mods/{mod_id}/files?pageSize=1000&gameVersion={self.minecraft_version}", headers=HEADERS)
if response.status_code == 200:
files = response.json()["data"]
self.version_list.clear()
for file in files:
if self.minecraft_version in file["gameVersions"]:
version_item = QListWidgetItem(file["displayName"])
version_item.setData(Qt.ItemDataRole.UserRole, file["downloadUrl"])
self.version_list.addItem(version_item)
if self.show_incompatible_checkbox.isChecked():
response = requests.get(f"https://api.curse.tools/v1/cf/mods/{mod_id}/files?pageSize=1000", headers=HEADERS)
files = response.json()["data"]
if response.status_code == 200:
for file in files:
if not self.minecraft_version in file["gameVersions"]:
version_item = QListWidgetItem(file["displayName"])
version_item.setForeground(QColor(255,0,0))
version_item.setData(Qt.ItemDataRole.UserRole, file["downloadUrl"]) # Assuming the first file is the one to download
self.version_list.addItem(version_item)
else:
QMessageBox.warning(self, "Error", "Failed to fetch mod versions.")
def add_selected_version(self):
selected_version_item = self.version_list.currentItem()
if selected_version_item:
download_url = selected_version_item.data(Qt.ItemDataRole.UserRole)
mod_name = download_url.split("/")[-1]
download_path = f"{cwd}/profiles/{self.name}/mods/{mod_name}"
self.download_thread = DownloadModThread(download_url, download_path)
self.download_thread.progress_updated.connect(self.update_progress_bar)
self.download_thread.finished.connect(self.handle_download_finished)
self.download_thread.start()
else:
QMessageBox.warning(self, "No Version Selected", "Please select a version to add.")
def update_progress_bar(self, progress):
self.progress_bar.setValue(progress)
def handle_download_finished(self, success):
if success:
QMessageBox.information(self, "Success", "Mod downloaded successfully.")
else:
QMessageBox.critical(self, "Error", "Failed to download the mod.")
class ModBrowserDialog(QDialog):
def __init__(self, parent=None, minecraft_version=None, loader=None,name=None):
super().__init__(parent)
self.setWindowTitle("Modrinth Mod Browser")
self.setGeometry(300, 300, 600, 500)
self.minecraft_version = minecraft_version
self.loader = loader
self.name = name
layout = QVBoxLayout()
self.setLayout(layout)
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Search for mods...")
layout.addWidget(self.search_input)
self.search_button = QPushButton("Search")
self.search_button.clicked.connect(self.search_mods)
layout.addWidget(self.search_button)
self.mod_list = QListWidget()
self.mod_list.itemSelectionChanged.connect(self.display_mod_versions)
layout.addWidget(self.mod_list)
self.version_list = QListWidget()
layout.addWidget(self.version_list)
self.show_incompatible_checkbox = QCheckBox("Show Incompatible Versions", self)
self.show_incompatible_checkbox.stateChanged.connect(self.display_mod_versions)
layout.addWidget(self.show_incompatible_checkbox)
self.add_button = QPushButton("Add Selected Version")
self.add_button.clicked.connect(self.add_selected_version)
layout.addWidget(self.add_button)
self.progress_bar = QProgressBar()
layout.addWidget(self.progress_bar)
def search_mods(self):
search_query = self.search_input.text()
response = requests.get(f"https://api.modrinth.com/v2/search?query={search_query}",headers=HEADERS)
if response.status_code == 200:
mods = response.json()["hits"]
self.version_list.clear()
self.mod_list.clear()
for mod in mods:
item = QListWidgetItem(mod["title"])
try:
item.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(requests.get(mod["icon_url"],headers=HEADERS).content).scaled(100,100))))
except:
with open(f"{cwd}/icons/modrinth.png","rb") as f:
ico = f.read()
item.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(ico))))
item.setData(Qt.ItemDataRole.UserRole, mod["project_id"])
self.mod_list.addItem(item)
else:
QMessageBox.warning(self, "Error", "Failed to fetch mods.")
def display_mod_versions(self):
if self.mod_list.selectedItems():
mod_id = self.mod_list.selectedItems()[0].data(Qt.ItemDataRole.UserRole)
response = requests.get(f"https://api.modrinth.com/v2/project/{mod_id}/version",headers=HEADERS)
if response.status_code == 200:
versions = response.json()
self.version_list.clear()
for version in versions:
if self.minecraft_version in version["game_versions"] and self.loader in version["loaders"]:
version_item = QListWidgetItem(version["name"])
version_item.setData(Qt.ItemDataRole.UserRole, version["files"][0]["url"]) # Assuming the first file is the one to download
self.version_list.addItem(version_item)
if self.show_incompatible_checkbox.isChecked():
for version in versions:
if not self.minecraft_version in version["game_versions"] or not self.loader in version["loaders"]:
version_item = QListWidgetItem(version["name"])
version_item.setForeground(QColor(255,0,0))
version_item.setData(Qt.ItemDataRole.UserRole, version["files"][0]["url"]) # Assuming the first file is the one to download
self.version_list.addItem(version_item)
else:
QMessageBox.warning(self, "Error", "Failed to fetch mod versions.")
def add_selected_version(self):
selected_version_item = self.version_list.currentItem()
if selected_version_item:
name = self.name
download_url = selected_version_item.data(Qt.ItemDataRole.UserRole)
mod_name = download_url.split("/")[-1]
download_path = f"{cwd}/profiles/{name}/mods/{mod_name}"
self.download_thread = DownloadModThread(download_url, download_path)
self.download_thread.progress_updated.connect(self.update_progress_bar)
self.download_thread.finished.connect(self.handle_download_finished)
self.download_thread.start()
else:
QMessageBox.warning(self, "No Version Selected", "Please select a version to add.")
def update_progress_bar(self, progress):
self.progress_bar.setValue(progress)
def handle_download_finished(self, success):
if success:
QMessageBox.information(self, "Success", "Mod downloaded successfully.")
else:
QMessageBox.critical(self, "Error", "Failed to download the mod.")
class DownloadAndExtractThread(QThread):
progress_updated = pyqtSignal(int)
finished = pyqtSignal(bool)
def __init__(self, download_url, download_path, extract_path):
super().__init__()
self.download_url = download_url
self.download_path = download_path
self.extract_path = extract_path
def run(self):
try:
response = requests.get(self.download_url, stream=True)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
block_size = 1024
progress = 0
with open(self.download_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=block_size):
if chunk:
file.write(chunk)
progress += len(chunk)
self.progress_updated.emit(int((progress / total_size) * 100))
with zipfile.ZipFile(self.download_path, 'r') as zip_ref:
zip_ref.extractall(f"{cwd}/.minecraft")
os.remove(self.download_path)
self.finished.emit(True)
except Exception as e:
QMessageBox.critical(None, "Error", str(e))
self.finished.emit(False)
class DownloadAndExtractLegacyForge(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Download Legacy Forge Support")
self.layout = QVBoxLayout(self)
self.progress_bar = QProgressBar(self)
self.layout.addWidget(self.progress_bar)
self.download_url = 'https://qwertz.app/downloads/QWERTZLauncher/QWERTZ_Launcher-LEGACY-FORGE-SUPPORT.zip'
self.download_path = f"{cwd}/.minecraft/legacy-forge-support.zip"
self.extract_path = f"{cwd}/.minecraft"
self.download_thread = DownloadAndExtractThread(self.download_url, self.download_path, self.extract_path)
self.download_thread.progress_updated.connect(self.update_progress_bar)
self.download_thread.finished.connect(self.handle_finished)
self.download_thread.start()
def update_progress_bar(self, progress):
self.progress_bar.setValue(progress)
def handle_finished(self, success):
if success:
QMessageBox.information(self, "Success", "Legacy Forge support installed successfully.")
self.accept()
else:
QMessageBox.critical(self, "Error", "Failed to install Legacy Forge support.")
self.reject()
class LoginMainWindow(QDialog):
def __init__(self,parent=None):
super().__init__(parent)
self.setWindowTitle("Logging in to Microsoft")
self.loginWindow = LoginWindow(self,parent)
self.loginWindow.show()
self.loginWindow.closed.connect(self.close)
class LoginWindow(QWebEngineView):
closed = pyqtSignal()
def __init__(self, parent=None,ogparent=None):
super().__init__(parent)
self.parent = ogparent
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
self.setMinimumSize(QSize(800, 600))
self.setWindowTitle("Logging in to Microsoft")
login_url, self.state, self.code_verifier = mc.microsoft_account.get_secure_login_data(CLIENT_ID, REDIRECT_URL)
self.load(QUrl(login_url))
# Connects a function that is called when the url changed
self.urlChanged.connect(self.new_url)
self.show()
def closeEvent(self, event):
self.closed.emit() # Emit the closed signal when the window is closed
super().closeEvent(event)
def new_url(self, url: QUrl):
try:
auth_code = mc.microsoft_account.parse_auth_code_url(url.toString(), self.state)
account_information = mc.microsoft_account.complete_login(CLIENT_ID, None, REDIRECT_URL, auth_code, self.code_verifier)
self.handleLoginSuccess(account_information)
except AssertionError:
print("States do not match!")
except KeyError:
print("URL not valid")
def handleLoginSuccess(self, account_information):
self.token = account_information["access_token"]
self.username = account_information["name"]
self.uuid = account_information["id"]
# Save the refresh token in a file
with open(f"{cwd}/accounts.json", "r", encoding="utf-8") as f:
accounts = json.load(f)
a=0
for acc in accounts["accounts"]:
if acc["username"] == self.username:
a=1
if not a==1:
accounts["accounts"].append({
"username": self.username,
"uuid": self.uuid,
"token": self.token,
"refresh_token":account_information["refresh_token"]
})
with open(f"{cwd}/accounts.json","w") as f:
json.dump(accounts, f, ensure_ascii=False, indent=4)
# Update the account information in the parent AccountManagementDialog
self.parent.updateAccountInfo(self.username, self.uuid, self.token)
self.close()
else:
QMessageBox.warning(self, "Error", f"An account with the username '{self.username}' already exists.")
self.close()
class AccountManagementDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Account Management")
self.layout = QVBoxLayout(self)
with open(f"{cwd}/accounts.json","r") as f:
accounts = json.load(f)
microsoft_accounts = []
for account in accounts["accounts"]:
microsoft_accounts.append(account["username"])
# Add account list
self.account_list = QListWidget()
self.account_list.addItems(microsoft_accounts)
self.layout.addWidget(self.account_list)
# Add buttons for adding, deleting, and editing accounts
self.add_button = QPushButton("Add Account")
self.add_button.clicked.connect(self.add_account)
self.layout.addWidget(self.add_button)
self.add_fake_button = QPushButton("Add Offline Account")
self.add_fake_button.clicked.connect(self.add_fake_account)
self.layout.addWidget(self.add_fake_button)
self.delete_button = QPushButton("Delete Account")
self.delete_button.clicked.connect(self.delete_account)
self.layout.addWidget(self.delete_button)
self.refresh_on_start_checkbox = QCheckBox("Refresh sessions on launcher start")
self.layout.addWidget(self.refresh_on_start_checkbox)
# Checkbox for "Refresh on launch"
self.refresh_on_launch_checkbox = QCheckBox("Refresh on launch")
self.layout.addWidget(self.refresh_on_launch_checkbox)
# Load the initial states of the checkboxes from a configuration file or settings
self.load_checkbox_states()
# Connect signals if needed, for example, to save the state when changed
self.refresh_on_start_checkbox.stateChanged.connect(self.save_checkbox_states)
self.refresh_on_launch_checkbox.stateChanged.connect(self.save_checkbox_states)
def load_checkbox_states(self):
with open(f"{cwd}/accounts.json", "r", encoding="utf-8") as f:
accounts = json.load(f)
self.refresh_on_launch_checkbox.setChecked(True) if accounts["refresh"]["launch"] == "1" else self.refresh_on_launch_checkbox.setChecked(False)
self.refresh_on_start_checkbox.setChecked(True) if accounts["refresh"]["start"] == "1" else self.refresh_on_start_checkbox.setChecked(False)
def save_checkbox_states(self):
with open(f"{cwd}/accounts.json", "r", encoding="utf-8") as f:
accounts = json.load(f)
accounts["refresh"]["launch"] = "1" if self.refresh_on_launch_checkbox.isChecked() else "0"
accounts["refresh"]["start"] = "1" if self.refresh_on_start_checkbox.isChecked() else "0"
with open(f"{cwd}/accounts.json", "w", encoding="utf-8") as f:
json.dump(accounts,f,indent=2)
def add_account(self):
dialog = LoginMainWindow(self)
dialog.exec()
def updateAccountInfo(self, username, uuid,token):
self.activeUser = username
self.activeUUID = uuid
self.activeToken = token
self.updateAccountList()
def updateAccountList(self):
global restart
username = self.activeUser
uuid = self.activeUUID
token = self.activeToken
# Check if the account already exists
# Update the account list in the dialog
self.account_list.addItem(username)
try:
ico = requests.get(f"https://crafatar.com/avatars/{uuid}").content
except:
with open(f"{cwd}/icons/fallback.png","rb") as f:
ico = f.read()
action = QAction(QIcon(QPixmap.fromImage(QImage.fromData(ico))), f"{username}", self)
action.triggered.connect(lambda checked, t="fake_token", uu=uuid,u=username: ex.setActiveAccount(t,uu,u))
ex.microsoft_account_menu.addAction(action)
###RESTARTING BECAUSE IT IS NOT WORKING SMH
restart = 1
app.quit()
def add_fake_account(self):
dialog = QDialog(self)
dialog.setWindowTitle("Add Offline Account")
layout = QVBoxLayout(dialog)
# Username input
username_layout = QHBoxLayout()
username_label = QLabel("Username:")
self.username_input = QLineEdit()
username_layout.addWidget(username_label)
username_layout.addWidget(self.username_input)
layout.addLayout(username_layout)
# Save button
save_button = QPushButton("Save")
save_button.clicked.connect(lambda: self.save_fake_account(dialog))
layout.addWidget(save_button)
dialog.exec()
def save_fake_account(self, dialog):
username = self.username_input.text().strip().replace(" ", "_").replace("-", "_")
if username:
# Check if the account already exists
with open(f"{cwd}/accounts.json", "r") as f:
accounts = json.load(f)
for account in accounts["accounts"]:
if account["username"] == username:
# Account already exists, show an error message
QMessageBox.warning(self, "Error", f"An account with the username '{username}' already exists.")
return
# Generate a random UUID
uuid_str = str(uuuid.uuid4())
# Add the fake account to the accounts.json file
accounts["accounts"].append({
"username": username,
"uuid": uuid_str,
"token": "fake_token"
})
with open(f"{cwd}/accounts.json", "w") as f:
json.dump(accounts, f, indent=2)
# Update the account list in the dialog
self.account_list.addItem(username)
try:
ico = requests.get(f"https://crafatar.com/avatars/{uuid_str}").content
except:
with open(f"{cwd}/icons/fallback.png","rb") as f:
ico = f.read()
action = QAction(QIcon(QPixmap.fromImage(QImage.fromData(ico))), f"{username} (Offline)", self)
action.triggered.connect(lambda checked, t="fake_token", uu=uuid_str,u=username: ex.setActiveAccount(t,uu,u))
ex.microsoft_account_menu.addAction(action)
dialog.accept()
def delete_account(self):
# Get the selected account from the list
selected_account = self.account_list.currentItem()
if selected_account:
# Get the username of the selected account
username = selected_account.text()
u2 = username
# Ask for confirmation before deleting the account
reply = QMessageBox.question(self, 'Confirmation', f'Are you sure you want to delete the account "{username}"?', QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
with open(f"{cwd}/accounts.json", "r") as f:
accounts = json.load(f)
if len(accounts["accounts"]) > 1:
# Remove the account from the accounts.json file
# Find the index of the account to be deleted
for i, account in enumerate(accounts["accounts"]):
if account["username"] == username:
accounts["accounts"].pop(i)
with open(f"{cwd}/accounts.json", "w") as f:
json.dump(accounts, f, indent=2)
# Remove the account from the list widget
row = self.account_list.row(selected_account)
self.account_list.takeItem(row)
# If the deleted account was the active account, set the first account as active
if username == accounts["active"]:
if accounts["accounts"]:
accounts["active"] = accounts["accounts"][0]["username"]
uuid = accounts["accounts"][0]["uuid"]
activeuser = accounts["accounts"][0]["username"]
else:
accounts["active"] = ""
uuid = ""
activeuser = ""
with open(f"{cwd}/accounts.json", "w") as f:
json.dump(accounts, f, indent=2)
try:
ico = requests.get(f"https://crafatar.com/avatars/{uuid}").content
except:
with open(f"{cwd}/icons/fallback.png","rb") as f:
ico = f.read()
ex.active_account_icon.setPixmap(QPixmap.fromImage(QImage.fromData(ico)).scaled(40,40))
ex.microsoft_account_button.setText(f"{activeuser}")
for a in ex.microsoft_account_menu.actions():
if a.text().split(" ")[0] == u2:
ex.microsoft_account_menu.removeAction(a)
else:
QMessageBox.warning(self,"Error","You cannot delete your only account. Create a new one first.")
class VersionDialog(QDialog):
def __init__(self, version_list, current_version, parent=None):
super().__init__(parent)
self.setWindowTitle('Select Minecraft Version')
self.layout = QVBoxLayout(self)
# Create and populate the combo box with versions
self.comboBox = QComboBox(self)
self.comboBox.addItems(version_list)
self.comboBox.setCurrentText(current_version)
self.layout.addWidget(self.comboBox)
# Close button
self.closeButton = QPushButton('Save', self)
self.closeButton.clicked.connect(self.close)
self.layout.addWidget(self.closeButton)
def selected_version(self):
return self.comboBox.currentText()
class AddProfileDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Add Profile")
self.setGeometry(500, 500, 400, 300)
layout = QVBoxLayout()
self.setLayout(layout)
# Name input
name_layout = QVBoxLayout()
name_label = QLabel("Profile Name:")
self.name_input = QLineEdit()
name_layout.addWidget(name_label)
name_layout.addWidget(self.name_input)
layout.addLayout(name_layout)
# Icon selection
icon_layout = QVBoxLayout()
icon_label = QLabel("Profile Icon:")
self.icon_combobox = QComboBox()
self.icon_combobox.addItem("Default", "minecraft.png")
self.icon_combobox.addItem("Custom", "")
self.icon_combobox.currentIndexChanged.connect(self.icon_type_changed)
self.default_combobox = QComboBox()
self.default_combobox.addItem("Minecraft", "minecraft.png")
for x, y, files in os.walk(f"{cwd}/icons/profiles/"):
for file in files:
if not file == "minecraft.png":
self.default_combobox.addItem(file[0].upper() + file.split(".")[0][1:], file)
self.icon_path_input = QLineEdit()
self.icon_path_input.setPlaceholderText("Enter icon file path")
self.icon_path_input.setVisible(False)
self.icon_browse_button = QPushButton("Browse")
self.icon_browse_button.clicked.connect(self.browse_icon)
self.icon_browse_button.setVisible(False)
loader_layout = QVBoxLayout()
loader_label = QLabel("Loader:")
self.loader_combobox = QComboBox()
self.loader_combobox.addItem("Vanilla", "VANILLA")
self.loader_combobox.addItem("Forge", "FORGE")
self.loader_combobox.addItem("Fabric", "FABRIC")
jvm_layout = QVBoxLayout()
jvm_label = QLabel("JVM:")
self.jvm_combobox = QComboBox()
self.jvm_combobox.addItem("Built-in", "built-in")
self.jvm_combobox.addItem("Custom", "custom")
self.jvm_combobox.currentIndexChanged.connect(self.jvm_type_changed)
jvm_layout.addWidget(jvm_label)
jvm_layout.addWidget(self.jvm_combobox)
# Custom JVM path
self.jvm_path_input = QLineEdit()
self.jvm_path_input.setPlaceholderText("Enter JVM path")
self.jvm_path_input.setVisible(False)
self.jvm_browse_button = QPushButton("Browse")
self.jvm_browse_button.clicked.connect(self.browse_jvm)
self.jvm_browse_button.setVisible(False)
jvm_layout.addWidget(self.jvm_path_input)
jvm_layout.addWidget(self.jvm_browse_button)
icon_layout.addWidget(icon_label)
icon_layout.addWidget(self.icon_combobox)
icon_layout.addWidget(self.default_combobox)
icon_layout.addWidget(self.icon_path_input)
icon_layout.addWidget(self.icon_browse_button)
layout.addLayout(icon_layout)
loader_layout.addWidget(loader_label)
loader_layout.addWidget(self.loader_combobox)
layout.addLayout(loader_layout)
# Version selection
version_layout = QVBoxLayout()
version_label = QLabel("Version:")
self.version_combobox = QComboBox()
versions = mc.utils.get_available_versions(mcdir)
version_list = []
for i in versions:
if "." in i["id"] and not "fabric" in i["id"].lower() and not "forge" in i["id"].lower():
version_list.append(i["id"])
self.version_combobox.addItems(version_list)
version_layout.addWidget(version_label)
version_layout.addWidget(self.version_combobox)
layout.addLayout(version_layout)
layout.addLayout(jvm_layout)
# Save button
save_button = QPushButton("Save")
save_button.clicked.connect(self.save_profile)
layout.addWidget(save_button)
def icon_type_changed(self, index):
self.icon_path_input.setVisible(index == 1)
self.icon_browse_button.setVisible(index == 1)
self.default_combobox.setVisible(index == 0)
def browse_icon(self):
file_dialog = QFileDialog()
file_dialog.setNameFilter("Image files (*.png *.jpg *.jpeg)")
if file_dialog.exec():
selected_file = file_dialog.selectedFiles()[0]
self.icon_path_input.setText(selected_file)
def jvm_type_changed(self, index):
self.jvm_path_input.setVisible(index == 1)
self.jvm_browse_button.setVisible(index == 1)
def browse_jvm(self):
file_dialog = QFileDialog()
file_dialog.setNameFilter("Executable files (*.exe *.jar)")
if file_dialog.exec():
selected_file = file_dialog.selectedFiles()[0]
self.jvm_path_input.setText(selected_file)
def save_profile(self):
name = self.name_input.text().strip()
if not name:
return
icon_type = self.icon_combobox.currentData()
if icon_type == "":
icon_path = self.icon_path_input.text().strip()
if not os.path.exists(icon_path):
return
else:
icon_path = self.default_combobox.currentData()
version = self.version_combobox.currentText()
loader = self.loader_combobox.currentData()
new_profile = {
"name": name,
"icon": icon_path,
"icon_type": "default" if icon_type else "custom",
"loader": loader,
"version": version,
"jvm": "BI" if self.jvm_combobox.currentData() == "built-in" else self.jvm_path_input.text().strip()
}
with open(f"{cwd}/profiles.json", "r") as f:
profiles = json.load(f)
profiles["profiles"].append(new_profile)
with open(f"{cwd}/profiles.json", "w") as f:
json.dump(profiles, f, indent=2)
os.makedirs(f"{cwd}/profiles/{name}/mods/")
self.accept()
class ProfileButton(QPushButton):
def __init__(self, name, icon,profilegrid, parent=None):
super().__init__(parent)
self.setCheckable(True)
self.setMinimumSize(QSize(150, 150))
self.name = name
self.parentt = parent
self.profilegrid = profilegrid
# Create a vertical layout for the button
layout = QVBoxLayout()
self.setLayout(layout)
# Add the icon to the top of the button
self.icon = QLabel()
self.icon.setPixmap(QIcon(icon).pixmap(96, 96))
layout.addWidget(self.icon, alignment=Qt.AlignmentFlag.AlignCenter)
# Add the name label to the bottom of the button
self.nameLabel = QLabel(name)
self.nameLabel.setFont(QFont('Consolas', 10))
layout.addWidget(self.nameLabel, alignment=Qt.AlignmentFlag.AlignCenter)
# Set the stylesheet for the button
self.setStyleSheet("""
QPushButton {
background-color: transparent;
border: none;
}
QPushButton:checked {
background-color: #007bff;
color: white;
}
""")
def paintEvent(self, event):
opt = QStyleOption()
opt.initFrom(self)
painter = QStylePainter(self)
painter.drawPrimitive(QStyle.PrimitiveElement.PE_Widget, opt)
super(ProfileButton, self).paintEvent(event)
def contextMenuEvent(self, event):
menu = QMenu(self)
delete_icon = QIcon(f"{cwd}/icons/delete.png")
delete_action = menu.addAction(delete_icon, "Delete Profile")
rename_icon = QIcon(f"{cwd}/icons/rename.png")
rename_action = menu.addAction(rename_icon, "Rename Profile")
icon_icon = QIcon(f"{cwd}/icons/icon.png")
icon_action = menu.addAction(icon_icon, "Change Icon")
version_icon = QIcon(f"{cwd}/icons/version.png")
version_action = menu.addAction(version_icon, "Change Version")
jvm_icon = QIcon(f"{cwd}/icons/jvm.png")
jvm_action = menu.addAction(jvm_icon, "Change JVM")
loader_icon = QIcon(f"{cwd}/icons/loader.png")
loader_action = menu.addAction(loader_icon, "Change Loader")
folder_icon = QIcon(f"{cwd}/icons/folder.png")
folder_action = menu.addAction(folder_icon, "Open in Explorer")
self.parentt.selectProfile(self.name)
action = menu.exec(self.mapToGlobal(event.pos()))
if action == delete_action:
self.deleteProfile()
elif action == version_action:
self.changeVersion()
elif action == jvm_action:
self.changeJVM()
elif action == loader_action:
self.changeLoader()
elif action == rename_action:
self.renameProfile()
elif action == icon_action:
self.changeIcon()
elif action == folder_action:
self.openFolder()
def openFolder(self):
os.startfile(f"{cwd}/profiles/{self.name}")
def renameProfile(self):
profile_name = self.name
rename_dialog = QDialog(self)
rename_dialog.setWindowTitle("Rename Profile")
layout = QVBoxLayout()
rename_dialog.setLayout(layout)
label = QLabel("Enter new profile name:")
layout.addWidget(label)
name_input = QLineEdit()
name_input.setText(profile_name)
layout.addWidget(name_input)
button_layout = QHBoxLayout()
ok_button = QPushButton("Save")
button_layout.addWidget(ok_button)
layout.addLayout(button_layout)
def on_ok():
new_name = name_input.text().strip()
if new_name and new_name != profile_name:
with open(f"{cwd}/profiles.json", "r") as f:
profiles_data = json.load(f)
for profile in profiles_data["profiles"]:
if profile["name"] == new_name:
QMessageBox.warning(self, "Error", f"A profile with the name '{new_name}' already exists.")
return
for profile in profiles_data["profiles"]:
if profile["name"] == profile_name:
profile["name"] = new_name
break
with open(f"{cwd}/profiles.json", "w") as f:
json.dump(profiles_data, f, indent=2)
try:
shutil.move(f"{cwd}/profiles/{self.name}",f"{cwd}/profiles/{new_name}")
except:
pass
self.name = new_name
self.setText(new_name)
self.parentt.reinitLauncher()
rename_dialog.accept()
ok_button.clicked.connect(on_ok)
rename_dialog.exec()
def changeIcon(self):
# Assuming self.name is the profile name
profile_name = self.name
with open(f"{cwd}/profiles.json", "r") as f:
profiles_data = json.load(f)
# Find the current icon of the profile
current_icon = None
for profile in profiles_data["profiles"]:
if profile["name"] == self.name:
icon_type = profile["icon_type"]
current_icon = profile["icon"]
break
# Open a dialog to select the icon
icon_dialog = QDialog(self)
icon_dialog.setWindowTitle("Select icon")
layout = QVBoxLayout()
icon_dialog.setLayout(layout)
icon_label = QLabel("Icon:")
icon_combobox = QComboBox()
icon_combobox.addItem("Default", "default")
icon_combobox.addItem("Custom", "custom")
icon_combobox.setCurrentText("Default" if icon_type == "default" else "Custom")
icon_combobox.currentIndexChanged.connect(lambda index: icon_path_input.setVisible(index == 1))
icon_combobox.currentIndexChanged.connect(lambda index: icon_browse_button.setVisible(index == 1))
layout.addWidget(icon_label)
layout.addWidget(icon_combobox)
default_combobox = QComboBox()
default_combobox.addItem("Minecraft", "minecraft.png")
default_combobox.setVisible(icon_type != "custom")
for x, y, files in os.walk(f"{cwd}/icons/profiles/"):
for file in files:
if not file == "minecraft.png":
default_combobox.addItem(file[0].upper() + file.split(".")[0][1:], file)
icon_path_input = QLineEdit()
icon_path_input.setPlaceholderText("Enter icon path")
icon_path_input.setText(current_icon if icon_type == "custom" else "")
icon_path_input.setVisible(icon_type == "custom")
layout.addWidget(icon_path_input)
layout.addWidget(default_combobox)
icon_combobox.currentIndexChanged.connect(lambda index: default_combobox.setVisible(index != 1))
icon_browse_button = QPushButton("Browse")
icon_browse_button.clicked.connect(lambda: browse_icon(icon_path_input))
icon_browse_button.setVisible(current_icon == "custom")
layout.addWidget(icon_browse_button)
save_button = QPushButton("Save")
save_button.clicked.connect(icon_dialog.accept)