This repository was archived by the owner on Apr 12, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
677 lines (569 loc) · 25.6 KB
/
gui.py
File metadata and controls
677 lines (569 loc) · 25.6 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
import logging
import sys
import os
import requests
from typing import Optional
from PyQt6.QtCore import QObject, QThread, pyqtSignal, Qt, QSize
from PyQt6.QtWidgets import (
QApplication,
QMainWindow,
QWidget,
QVBoxLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QPushButton,
QRadioButton,
QCheckBox,
QProgressBar,
QTextEdit,
QFileDialog,
QGroupBox,
QStatusBar,
QMessageBox,
QDialog,
QListWidget,
QListWidgetItem,
QComboBox,
)
from PyQt6.QtGui import QFont, QIcon, QPalette, QColor, QImage, QPixmap
import server_pack_builder
# --- Logging Integration ---
class GUILogHandler(logging.Handler):
"""Captures logs and emits them via a signal."""
def __init__(self, signal):
super().__init__()
self.signal = signal
def emit(self, record):
msg = self.format(record)
self.signal.emit(msg)
# --- Worker Thread ---
class SearchWorker(QThread):
results_found = pyqtSignal(list)
error_occurred = pyqtSignal(str)
def __init__(self, query: str):
super().__init__()
self.query = query
def run(self):
try:
results = server_pack_builder.search_modrinth_modpacks(self.query)
self.results_found.emit(results)
except Exception as e:
self.error_occurred.emit(str(e))
class VersionsWorker(QThread):
versions_found = pyqtSignal(list)
def __init__(self, slug: str):
super().__init__()
self.slug = slug
def run(self):
try:
versions = server_pack_builder.get_modrinth_versions(self.slug)
self.versions_found.emit(versions)
except Exception:
self.versions_found.emit([])
class ImageLoader(QThread):
image_loaded = pyqtSignal(str, QImage) # url, image
def __init__(self, url: str):
super().__init__()
self.url = url
def run(self):
try:
# Use a session or simple get
response = requests.get(self.url, timeout=5)
if response.status_code == 200:
image = QImage()
image.loadFromData(response.content)
self.image_loaded.emit(self.url, image)
except Exception:
pass # Fail silently for icons
class ModrinthSearchDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Search Modrinth Modpacks")
self.resize(700, 500)
self.selected_slug = None
self.image_threads = {} # Keep references to prevent GC
# UI Setup
layout = QVBoxLayout(self)
# Search Bar
search_layout = QHBoxLayout()
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Search for modpacks (e.g., 'Better MC')...")
self.search_input.returnPressed.connect(self.do_search)
self.btn_search = QPushButton("Search")
self.btn_search.clicked.connect(self.do_search)
search_layout.addWidget(self.search_input)
search_layout.addWidget(self.btn_search)
layout.addLayout(search_layout)
# Results List
self.list_widget = QListWidget()
self.list_widget.setIconSize(QSize(64, 64))
self.list_widget.itemDoubleClicked.connect(self.accept_selection)
layout.addWidget(self.list_widget)
# Buttons
btn_layout = QHBoxLayout()
self.btn_select = QPushButton("Select")
self.btn_select.clicked.connect(self.accept_selection)
self.btn_cancel = QPushButton("Cancel")
self.btn_cancel.clicked.connect(self.reject)
btn_layout.addStretch()
btn_layout.addWidget(self.btn_select)
btn_layout.addWidget(self.btn_cancel)
layout.addLayout(btn_layout)
self.worker = None
def do_search(self):
query = self.search_input.text().strip()
if not query:
return
self.list_widget.clear()
self.btn_search.setEnabled(False)
self.list_widget.addItem("Searching...")
# Cancel previous worker if any
if self.worker and self.worker.isRunning():
self.worker.terminate()
self.worker.wait()
self.worker = SearchWorker(query)
self.worker.results_found.connect(self.populate_results)
self.worker.error_occurred.connect(self.handle_error)
self.worker.finished.connect(lambda: self.btn_search.setEnabled(True))
self.worker.start()
def handle_error(self, error_msg):
self.list_widget.clear()
self.list_widget.addItem(f"Error: {error_msg}")
def populate_results(self, hits):
self.list_widget.clear()
if not hits:
self.list_widget.addItem("No results found.")
return
for hit in hits:
title = hit.get("title", "Unknown")
author = hit.get("author", "Unknown")
slug = hit.get("slug", "")
desc = hit.get("description", "")
icon_url = hit.get("icon_url", "")
# Format text
item_text = f"{title} ({author})\n{desc}"
item = QListWidgetItem(item_text)
item.setData(Qt.ItemDataRole.UserRole, slug)
item.setToolTip(f"Slug: {slug}\n{desc}")
# Placeholder icon
placeholder = QPixmap(64, 64)
placeholder.fill(QColor("gray"))
item.setIcon(QIcon(placeholder))
self.list_widget.addItem(item)
# Load icon if available
if icon_url:
loader = ImageLoader(icon_url)
# Use a closure or default arg to capture 'item' correctly?
# Actually, ImageLoader emits url, we can map url back to item,
# OR we can pass item to ImageLoader (but QThread shouldn't touch UI directly).
# Safer: connect signal to a slot that updates the item.
# Since we loop, we need to know WHICH item to update.
# I'll just store the item in a map keyed by URL? No, multiple packs might share icon? Unlikely.
# Better: Make a custom slot or lambda.
# We need to be careful with lambdas in loops.
loader.image_loaded.connect(lambda u, i, it=item: self.update_icon(it, i))
# Keep reference
self.image_threads[icon_url] = loader
loader.finished.connect(lambda u=icon_url: self.cleanup_thread(u))
loader.start()
def update_icon(self, item, image):
if not image.isNull():
item.setIcon(QIcon(QPixmap.fromImage(image)))
def cleanup_thread(self, url):
if url in self.image_threads:
del self.image_threads[url]
def accept_selection(self):
item = self.list_widget.currentItem()
if item:
slug = item.data(Qt.ItemDataRole.UserRole)
if slug:
self.selected_slug = slug
self.accept()
class WorkerThread(QThread):
"""Runs the long-running CLI tasks in a background thread."""
log_signal = pyqtSignal(str)
progress_signal = pyqtSignal(int, int, str) # current, total, message
download_signal = pyqtSignal(int, int) # current_bytes, total_bytes
finished_signal = pyqtSignal(bool, str) # success, message
def __init__(self, mode: str, kwargs: dict):
super().__init__()
self.mode = mode
self.kwargs = kwargs
def update_progress(self, current: int, total: int, message: str = ""):
self.progress_signal.emit(current, total, message)
def update_download(self, current: int, total: int):
self.download_signal.emit(current, total)
def run(self):
# Configure logging to emit to our signal
handler = GUILogHandler(self.log_signal)
handler.setFormatter(logging.Formatter("%(message)s"))
# Default to non-verbose (INFO) to avoid "Checking..." spam
server_pack_builder.setup_logging(verbose=False, handler=handler)
try:
if self.mode == "local":
server_pack_builder.process_local_modpack(
source=self.kwargs["source"],
dest=self.kwargs["dest"],
dry_run=self.kwargs["dry_run"],
progress_callback=self.update_progress
)
elif self.mode == "modrinth":
server_pack_builder.process_modrinth_pack(
modrinth_url=self.kwargs["url"],
output_file=self.kwargs["output"],
dry_run=self.kwargs["dry_run"],
pack_version_id=self.kwargs.get("version_id"),
progress_callback=self.update_progress,
download_callback=self.update_download
)
self.finished_signal.emit(True, "Process completed successfully.")
except Exception as e:
self.finished_signal.emit(False, str(e))
finally:
# Reset logging to avoid side effects if run again (though handler instance changes)
pass
# --- Main Window ---
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Minecraft Server Pack Builder")
self.setMinimumSize(600, 500)
self.worker: Optional[WorkerThread] = None
# Setup UI
self.init_ui()
self.apply_theme()
def init_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setSpacing(10)
# Mode Selection
mode_group = QGroupBox("Mode Selection")
mode_layout = QHBoxLayout()
self.radio_local = QRadioButton("Local Modpack")
self.radio_modrinth = QRadioButton("Modrinth Modpack")
self.radio_local.setChecked(True)
self.radio_local.toggled.connect(self.update_ui_state)
mode_layout.addWidget(self.radio_local)
mode_layout.addWidget(self.radio_modrinth)
mode_group.setLayout(mode_layout)
main_layout.addWidget(mode_group)
# Inputs Group
self.input_group = QGroupBox("Configuration")
self.input_layout = QVBoxLayout()
self.input_group.setLayout(self.input_layout)
main_layout.addWidget(self.input_group)
# Local Inputs (Source/Dest)
self.local_widget = QWidget()
local_layout = QVBoxLayout(self.local_widget)
local_layout.setContentsMargins(0, 0, 0, 0)
# Source
src_layout = QHBoxLayout()
self.edit_source = QLineEdit()
self.edit_source.setPlaceholderText("Path to 'mods' directory...")
btn_browse_src = QPushButton("Browse...")
btn_browse_src.clicked.connect(lambda: self.browse_dir(self.edit_source))
src_layout.addWidget(QLabel("Source:"))
src_layout.addWidget(self.edit_source)
src_layout.addWidget(btn_browse_src)
local_layout.addLayout(src_layout)
# Destination
dest_layout = QHBoxLayout()
self.edit_dest = QLineEdit()
self.edit_dest.setPlaceholderText("Destination directory...")
btn_browse_dest = QPushButton("Browse...")
btn_browse_dest.clicked.connect(lambda: self.browse_dir(self.edit_dest))
dest_layout.addWidget(QLabel("Dest:"))
dest_layout.addWidget(self.edit_dest)
dest_layout.addWidget(btn_browse_dest)
local_layout.addLayout(dest_layout)
self.input_layout.addWidget(self.local_widget)
# Modrinth Inputs (URL/Output)
self.modrinth_widget = QWidget()
mod_layout = QVBoxLayout(self.modrinth_widget)
mod_layout.setContentsMargins(0, 0, 0, 0)
# URL
url_layout = QHBoxLayout()
self.edit_url = QLineEdit()
self.edit_url.setPlaceholderText("Modrinth URL or Slug (e.g., 'my-pack')")
self.edit_url.editingFinished.connect(self.fetch_versions)
self.btn_search_modrinth = QPushButton("Search...")
self.btn_search_modrinth.clicked.connect(self.open_search_dialog)
url_layout.addWidget(QLabel("URL/Slug:"))
url_layout.addWidget(self.edit_url)
url_layout.addWidget(self.btn_search_modrinth)
mod_layout.addLayout(url_layout)
# Version Selection
version_layout = QHBoxLayout()
self.combo_version = QComboBox()
self.combo_version.addItem("Latest", None)
self.combo_version.setEnabled(False)
version_layout.addWidget(QLabel("Version:"))
version_layout.addWidget(self.combo_version)
mod_layout.addLayout(version_layout)
# Output File
out_layout = QHBoxLayout()
self.edit_output = QLineEdit()
self.edit_output.setPlaceholderText("Output .mrpack file (optional)")
btn_browse_out = QPushButton("Save As...")
btn_browse_out.clicked.connect(self.browse_save_file)
out_layout.addWidget(QLabel("Output:"))
out_layout.addWidget(self.edit_output)
out_layout.addWidget(btn_browse_out)
mod_layout.addLayout(out_layout)
self.input_layout.addWidget(self.modrinth_widget)
self.modrinth_widget.hide() # Initial state
# Options
opts_layout = QHBoxLayout()
self.check_dry_run = QCheckBox("Dry Run (Simulate only)")
# Verbose is implied/handled by capturing all logs for now, or we can toggle detail
opts_layout.addWidget(self.check_dry_run)
opts_layout.addStretch()
main_layout.addLayout(opts_layout)
# Action Buttons
btn_layout = QHBoxLayout()
self.btn_run = QPushButton("Run Process")
self.btn_run.setFixedHeight(40)
self.btn_run.clicked.connect(self.start_process)
self.btn_cancel = QPushButton("Cancel")
self.btn_cancel.setFixedHeight(40)
self.btn_cancel.setEnabled(False)
self.btn_cancel.clicked.connect(self.cancel_process)
btn_layout.addWidget(self.btn_run)
btn_layout.addWidget(self.btn_cancel)
main_layout.addLayout(btn_layout)
# Logs
main_layout.addWidget(QLabel("Logs:"))
self.text_logs = QTextEdit()
self.text_logs.setReadOnly(True)
self.text_logs.setFont(QFont("Consolas", 9))
main_layout.addWidget(self.text_logs)
# Progress Section
progress_layout = QVBoxLayout()
self.lbl_progress = QLabel("")
self.progress_bar = QProgressBar()
self.progress_bar.setTextVisible(True)
self.progress_bar.setFormat("%p%") # Show percentage
progress_layout.addWidget(self.lbl_progress)
progress_layout.addWidget(self.progress_bar)
main_layout.addLayout(progress_layout)
# Status Bar
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.status_bar.showMessage("Ready")
def apply_theme(self):
# Fusion Theme with Dark Palette
app = QApplication.instance()
# In PyQt6, instance() returns QCoreApplication, which doesn't have setStyle/setPalette type hints
# matching what we expect from QApplication. However, since we created a QApplication in run_gui(),
# the instance IS a QApplication at runtime.
# If we want to be safe and satisfy linters (and logic), we check/cast.
if isinstance(app, QApplication):
app.setStyle("Fusion")
palette = QPalette()
# ... (colors setup) ...
palette.setColor(QPalette.ColorRole.Window, QColor(53, 53, 53))
palette.setColor(QPalette.ColorRole.WindowText, Qt.GlobalColor.white)
palette.setColor(QPalette.ColorRole.Base, QColor(25, 25, 25))
palette.setColor(QPalette.ColorRole.AlternateBase, QColor(53, 53, 53))
palette.setColor(QPalette.ColorRole.ToolTipBase, Qt.GlobalColor.white)
palette.setColor(QPalette.ColorRole.ToolTipText, Qt.GlobalColor.white)
palette.setColor(QPalette.ColorRole.Text, Qt.GlobalColor.white)
palette.setColor(QPalette.ColorRole.Button, QColor(53, 53, 53))
palette.setColor(QPalette.ColorRole.ButtonText, Qt.GlobalColor.white)
palette.setColor(QPalette.ColorRole.BrightText, Qt.GlobalColor.red)
palette.setColor(QPalette.ColorRole.Link, QColor(42, 130, 218))
palette.setColor(QPalette.ColorRole.Highlight, QColor(42, 130, 218))
palette.setColor(QPalette.ColorRole.HighlightedText, Qt.GlobalColor.black)
app.setPalette(palette)
# Additional Stylesheet for polish
app.setStyleSheet("""
QGroupBox {
border: 1px solid gray;
border-radius: 5px;
margin-top: 0.5em;
font-weight: bold;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 10px;
padding: 0 3px 0 3px;
}
QPushButton {
background-color: #2b5b84;
border-radius: 3px;
padding: 5px;
}
QPushButton:hover {
background-color: #3a7ca5;
}
QPushButton:disabled {
background-color: #555;
color: #888;
}
""")
def update_ui_state(self):
is_local = self.radio_local.isChecked()
self.local_widget.setVisible(is_local)
self.modrinth_widget.setVisible(not is_local)
def browse_dir(self, line_edit):
path = QFileDialog.getExistingDirectory(self, "Select Directory")
if path:
line_edit.setText(path)
def browse_save_file(self):
path, _ = QFileDialog.getSaveFileName(self, "Save Output File", "", "Modrinth Pack (*.mrpack)")
if path:
self.edit_output.setText(path)
def append_log(self, message):
self.text_logs.append(message)
# Auto scroll
cursor = self.text_logs.textCursor()
cursor.movePosition(cursor.MoveOperation.End)
self.text_logs.setTextCursor(cursor)
def update_progress_bar(self, current, total, message):
if total > 0:
self.progress_bar.setRange(0, total)
self.progress_bar.setValue(current)
self.progress_bar.setFormat(f"{int(current/total*100)}% ({current}/{total})")
else:
self.progress_bar.setRange(0, 0)
if message:
self.lbl_progress.setText(message)
def update_download_progress(self, current_bytes, total_bytes):
if total_bytes > 0:
self.progress_bar.setRange(0, total_bytes)
self.progress_bar.setValue(current_bytes)
# Convert to MB for display
curr_mb = current_bytes / (1024 * 1024)
total_mb = total_bytes / (1024 * 1024)
self.progress_bar.setFormat(f"{int(current_bytes/total_bytes*100)}% ({curr_mb:.2f}/{total_mb:.2f} MB)")
self.lbl_progress.setText(f"Downloading... {curr_mb:.2f} MB / {total_mb:.2f} MB")
else:
self.progress_bar.setRange(0, 0)
self.progress_bar.setFormat("%p%")
self.lbl_progress.setText("Downloading... (Unknown size)")
def process_finished(self, success, message):
self.progress_bar.setRange(0, 100) # Reset from indeterminate
self.progress_bar.setValue(100 if success else 0)
self.progress_bar.setFormat("%p%")
self.lbl_progress.setText("Process Completed" if success else "Process Failed")
self.btn_run.setEnabled(True)
self.btn_cancel.setEnabled(False)
self.input_group.setEnabled(True)
if success:
self.status_bar.showMessage("Done!")
QMessageBox.information(self, "Success", message)
self.append_log(f"\n[SUCCESS] {message}")
else:
self.status_bar.showMessage("Failed")
QMessageBox.critical(self, "Error", message)
self.append_log(f"\n[ERROR] {message}")
def start_process(self):
# Validate inputs
dry_run = self.check_dry_run.isChecked()
if self.radio_local.isChecked():
source = self.edit_source.text().strip()
dest = self.edit_dest.text().strip()
if not source or not os.path.isdir(source):
QMessageBox.warning(self, "Invalid Input", "Please select a valid source directory.")
return
if not dest:
QMessageBox.warning(self, "Invalid Input", "Please select a destination directory.")
return
mode = "local"
kwargs = {"source": source, "dest": dest, "dry_run": dry_run}
else:
url = self.edit_url.text().strip()
output = self.edit_output.text().strip() or None
if not url:
QMessageBox.warning(self, "Invalid Input", "Please enter a Modrinth URL or Slug.")
return
version_id = self.combo_version.currentData()
mode = "modrinth"
kwargs = {"url": url, "output": output, "dry_run": dry_run, "version_id": version_id}
# Start Thread
self.text_logs.clear()
self.append_log("Starting process...")
self.status_bar.showMessage("Running...")
self.progress_bar.setRange(0, 0) # Indeterminate
self.btn_run.setEnabled(False)
self.btn_cancel.setEnabled(True)
self.input_group.setEnabled(False)
self.worker = WorkerThread(mode, kwargs)
self.worker.log_signal.connect(self.append_log)
self.worker.progress_signal.connect(self.update_progress_bar)
self.worker.download_signal.connect(self.update_download_progress)
self.worker.finished_signal.connect(self.process_finished)
self.worker.start()
def cancel_process(self):
if self.worker and self.worker.isRunning():
# Terminating threads is harsh, but Python threads are hard to kill gracefully
# without logic changes in the loop.
# For now, we will warn user or just try terminate if supported,
# but ideally we'd set a flag in the worker logic.
# Since the CLI functions don't check a "stop" flag, we might have to just let it finish or use terminate().
# process_local_modpack uses ThreadPoolExecutor, so main thread is just waiting.
reply = QMessageBox.question(self, "Cancel",
"Stopping the process abruptly might leave partial files. Are you sure?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
self.worker.terminate() # Unsafe but effective for immediate stop
self.worker.wait()
self.append_log("\n[CANCELLED] Process cancelled by user.")
# Reset UI on cancel
self.progress_bar.setValue(0)
self.progress_bar.setRange(0, 100)
self.progress_bar.setFormat("%p%")
self.lbl_progress.setText("")
self.process_finished(False, "Process cancelled.")
def open_search_dialog(self):
dialog = ModrinthSearchDialog(self)
if dialog.exec() == QDialog.DialogCode.Accepted:
if dialog.selected_slug:
self.edit_url.setText(dialog.selected_slug)
self.fetch_versions()
def fetch_versions(self):
slug_or_url = self.edit_url.text().strip()
if not slug_or_url:
return
# Simple check if it looks like a slug/url
if "modrinth.com" in slug_or_url:
# Extract slug from URL if possible, otherwise let backend handle it?
# get_modrinth_project_version is in backend.
# We can't easily call it here without importing or duplicating.
# We can just try to search versions for the slug/ID extracted.
# For now, let's just pass the text. If it's a URL, the backend might fail to find versions
# unless we extract the slug first.
pass
# Use backend helper to extract slug if needed?
slug, _ = server_pack_builder.get_modrinth_project_version(slug_or_url)
self.combo_version.clear()
self.combo_version.addItem("Loading...", None)
self.combo_version.setEnabled(False)
# We need a worker for this so GUI doesn't freeze
self.version_worker = VersionsWorker(slug)
self.version_worker.versions_found.connect(self.populate_versions)
self.version_worker.start()
def populate_versions(self, versions):
self.combo_version.clear()
self.combo_version.addItem("Latest", None)
if versions:
for v in versions:
name = v.get("name", "Unknown")
vid = v.get("id")
game_versions = v.get("game_versions", [])
loaders = v.get("loaders", [])
display = f"{name} ({', '.join(game_versions)}) - {', '.join(loaders)}"
self.combo_version.addItem(display, vid)
self.combo_version.setEnabled(True)
else:
self.combo_version.addItem("No versions found or invalid slug", None)
self.combo_version.setEnabled(True) # Allow user to still try "Latest" if they think it's right
def run_gui():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
run_gui()