Repository navigation
Expand file tree
/
Copy pathAddonsManager_GUI.py
More file actions
858 lines (698 loc) · 32.9 KB
/
Copy pathAddonsManager_GUI.py
File metadata and controls
858 lines (698 loc) · 32.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
#!/usr/bin/env python3
"""
ESO AddOn Manager - Xbox Game Pass
Dark mode · Single-file · Portable (run from anywhere, including your AddOns folder)
"""
import ctypes
import ctypes.wintypes
import json
import os
import re
import subprocess
import sys
import threading
import time
import uuid
import webbrowser
from pathlib import Path
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
# ── Environment ──────────────────────────────────────────────────────────────
LOCAL_APPDATA = Path(os.environ["LOCALAPPDATA"])
USER_PROFILE = Path(os.environ["USERPROFILE"])
ESO_LOCAL_BASE = LOCAL_APPDATA / "Elder Scrolls Online"
DEFAULT_CHANNEL = "xb1cert"
REROUTER_TAG = "__addon_rerouter__"
_UUID_NS = uuid.UUID("f4ad7000-e500-4000-9000-000000000001")
CREDITS_URL = "https://fairtech.app"
def _get_documents_folder() -> Path:
"""Return the user's real Documents folder via SHGetFolderPathW.
Handles the case where the user has moved Documents to a different drive."""
CSIDL_PERSONAL = 5
SHGFP_TYPE_CURRENT = 0
buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)
ctypes.windll.shell32.SHGetFolderPathW(
None, CSIDL_PERSONAL, None, SHGFP_TYPE_CURRENT, buf
)
return Path(buf.value)
DEFAULT_SOURCE = _get_documents_folder() / "Elder Scrolls Online" / DEFAULT_CHANNEL / "AddOns"
def _find_icon() -> str | None:
"""Locate FairTech.ico whether running as a script or a PyInstaller exe."""
if getattr(sys, "frozen", False):
base = Path(sys._MEIPASS) # PyInstaller temp extraction dir
else:
base = Path(__file__).parent
ico = base / "FairTech.ico"
return str(ico) if ico.exists() else None
# Config lives in AppData - persists regardless of where the exe is placed
CONFIG_DIR = LOCAL_APPDATA / "ESOAddonsManager"
CONFIG_FILE = CONFIG_DIR / "config.json"
# ── Dark palette ─────────────────────────────────────────────────────────────
BG = "#111118" # window background
PANEL = "#1a1a24" # panel / toolbar
PANEL2 = "#21212e" # slightly raised surface
ROW_ODD = "#1a1a24" # list row (odd)
ROW_EVEN = "#1e1e2c" # list row (even)
BORDER = "#2e2e42" # separators / outlines
TEXT = "#d0d0e0" # primary text
MUTED = "#60607a" # secondary / dim text
ACCENT = "#4d88ff" # blue - buttons, highlights
ACCENT_HV = "#2d66dd" # hover
DANGER = "#dd4455" # red - destructive action
DANGER_HV = "#bb2233"
SUCCESS = "#44bb77" # green - synced badge
UNSYNC = "#555570" # grey - not synced badge
FONT = ("Segoe UI", 9)
FONT_B = ("Segoe UI", 9, "bold")
FONT_TITLE= ("Segoe UI", 12, "bold")
FONT_SM = ("Segoe UI", 8)
FONT_HDR = ("Segoe UI", 8)
# ════════════════════════════════════════════════════════════════════════════
# Admin / elevation
# ════════════════════════════════════════════════════════════════════════════
def _is_admin() -> bool:
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except Exception:
return False
def _elevate():
if _is_admin():
return
args = " ".join(f'"{a}"' for a in sys.argv)
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, None, 1)
sys.exit(0)
# ════════════════════════════════════════════════════════════════════════════
# NTFS junction helpers
# ════════════════════════════════════════════════════════════════════════════
def _is_reparse_point(path: Path) -> bool:
INVALID = 0xFFFFFFFF
attrs = ctypes.windll.kernel32.GetFileAttributesW(str(path))
return attrs != INVALID and bool(attrs & 0x400)
def _create_junction(link: Path, target: Path) -> bool:
r = subprocess.run(
["cmd", "/c", "mklink", "/J", str(link), str(target)],
capture_output=True, text=True,
)
return r.returncode == 0
def _remove_junction_safe(path: Path) -> bool:
"""Remove a directory junction without touching its target.
Uses os.rmdir which never follows junctions."""
try:
os.rmdir(str(path))
return True
except OSError:
return False
# ════════════════════════════════════════════════════════════════════════════
# UUID / map helpers
# ════════════════════════════════════════════════════════════════════════════
def _addon_uuid(name: str) -> str:
return str(uuid.uuid5(_UUID_NS, name.lower()))
def _map_path(channel: str) -> Path:
return ESO_LOCAL_BASE / channel / "CachedData" / "AddonRouterMap.json"
def _load_map(channel: str) -> dict:
p = _map_path(channel)
if p.exists():
try:
return json.loads(p.read_text())
except Exception:
pass
return {"version": 1, "managed": {}}
def _save_map(channel: str, data: dict):
p = _map_path(channel)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(json.dumps(data, indent=2))
# ════════════════════════════════════════════════════════════════════════════
# Addon scanning
# ════════════════════════════════════════════════════════════════════════════
def _read_addon_version(addon_file: Path) -> str:
try:
for line in addon_file.read_text(encoding="utf-8", errors="ignore").splitlines():
m = re.match(r"##\s*AddOnVersion:\s*(.+)", line)
if m:
return m.group(1).strip()
m = re.match(r"##\s*Version:\s*(.+)", line)
if m:
return m.group(1).strip()
except Exception:
pass
return ""
def _scan_source(source: Path) -> dict:
"""
Return {addon_folder_name: {path, addon_file}} for every addon in source.
Uses rglob so nested .addon files (e.g. HarvestMap/Modules/X/X.addon) are found.
Skips directories that contain the rerouter executable itself.
"""
out = {}
if not source.is_dir():
return out
# Determine our own directory so we can skip it
if getattr(sys, "frozen", False):
self_dir = Path(sys.executable).parent.resolve()
else:
self_dir = Path(__file__).parent.resolve()
for entry in source.iterdir():
if not entry.is_dir():
continue
if entry.resolve() == self_dir:
continue # don't treat the rerouter folder as an addon
addon_files = list(entry.rglob("*.addon"))
if addon_files:
out[entry.name] = {"path": entry, "addon_file": addon_files[0]}
return out
def _available_drives() -> list[str]:
return [c for c in "CDEFGHIJKLMNOPQRSTUVWXYZ" if Path(f"{c}:\\").exists()]
def find_candidate_paths() -> list[Path]:
"""
Scan every drive for Elder Scrolls Online\\<channel>\\AddOns directories.
Also checks if the exe itself is sitting inside an AddOns folder.
"""
candidates: list[Path] = []
# Are we running from inside an AddOns folder?
here = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).parent
for parent in here.parents:
if parent.name.lower() == "addons" and parent.is_dir():
candidates.append(parent.resolve())
break
# Scan Documents-style roots - start with the real Documents folder
real_docs = _get_documents_folder()
doc_roots = [real_docs]
for drv in _available_drives():
p = Path(f"{drv}:\\Documents")
if p.is_dir() and p.resolve() not in {r.resolve() for r in doc_roots}:
doc_roots.append(p)
for doc in doc_roots:
eso_root = doc / "Elder Scrolls Online"
if not eso_root.is_dir():
continue
try:
for channel_dir in sorted(eso_root.iterdir()):
if channel_dir.is_dir():
addons_dir = channel_dir / "AddOns"
if addons_dir.is_dir():
resolved = addons_dir.resolve()
if resolved not in {c.resolve() for c in candidates}:
candidates.append(addons_dir)
except PermissionError:
pass
return candidates
# ════════════════════════════════════════════════════════════════════════════
# Core sync / clean logic
# ════════════════════════════════════════════════════════════════════════════
def _upsert_entry(addon_name: str, addon_info: dict, addon_uuid: str, managed_root: Path) -> str:
"""Create or refresh the junction for one addon. Returns action string."""
uuid_dir = managed_root / addon_uuid
junction_path = uuid_dir / addon_name
if junction_path.exists() or _is_reparse_point(junction_path):
if _is_reparse_point(junction_path):
action = "updated"
else:
return "skipped" # real directory we didn't make - leave it alone
else:
action = "added"
uuid_dir.mkdir(parents=True, exist_ok=True)
now = str(int(time.time()))
version = _read_addon_version(addon_info["addon_file"])
info = {
"contentInstallationInfoVersion": 1,
"contentId": addon_uuid,
"installationTime": now,
"releaseVersion": version or "custom",
"releaseCreationTime": now,
"ignoreUpdates": True,
REROUTER_TAG: True,
}
with open(uuid_dir / "content_installation_info.json", "w") as f:
json.dump(info, f)
if _is_reparse_point(junction_path):
_remove_junction_safe(junction_path)
ok = _create_junction(junction_path, addon_info["path"])
return action if ok else "failed"
def _safe_remove_uuid_dir(uuid_dir: Path, addon_name: str, managed_root: Path):
"""
Remove a rerouter-created UUID directory safely.
Never uses shutil.rmtree - it follows NTFS junctions and would delete
the source addon files. os.rmdir() (via _remove_junction_safe) removes
only the junction point itself, leaving the target untouched.
"""
# Refuse to operate on anything outside managed_root
try:
uuid_dir.resolve().relative_to(managed_root.resolve())
except ValueError:
return
junction = uuid_dir / addon_name
if _is_reparse_point(junction):
if not _remove_junction_safe(junction):
return # couldn't remove junction - abort rather than risk anything
elif junction.exists():
return # real directory we didn't create - leave it alone
# Remove only the specific file we wrote; then the (now-empty) dir
try:
(uuid_dir / "content_installation_info.json").unlink()
except OSError:
pass
try:
uuid_dir.rmdir()
except OSError:
pass
def do_sync(source: Path, channel: str) -> dict:
"""Sync all addons from source and remove stale junctions."""
managed_root = ESO_LOCAL_BASE / channel / "CachedData" / "AddOnsManaged"
managed_root.mkdir(parents=True, exist_ok=True)
map_data = _load_map(channel)
source_addons = _scan_source(source)
counts = {"added": 0, "updated": 0, "skipped": 0, "failed": 0, "removed": 0}
for name, info in source_addons.items():
a_uuid = map_data["managed"].get(name) or _addon_uuid(name)
map_data["managed"][name] = a_uuid
result = _upsert_entry(name, info, a_uuid, managed_root)
counts[result] += 1
# Remove stale - addons tracked in map but no longer in source.
# Guard: skip stale removal when the source scan returned nothing -
# an empty scan most likely means the source path is wrong, and treating
# everything as stale would remove all junctions unnecessarily.
if source_addons:
stale = set(map_data["managed"].keys()) - set(source_addons.keys())
for name in stale:
a_uuid = map_data["managed"][name]
uuid_dir = managed_root / a_uuid
info_file = uuid_dir / "content_installation_info.json"
try:
meta = json.loads(info_file.read_text())
if not meta.get(REROUTER_TAG):
continue # not ours - leave it alone
except Exception:
continue
_safe_remove_uuid_dir(uuid_dir, name, managed_root)
del map_data["managed"][name]
counts["removed"] += 1
_save_map(channel, map_data)
return counts
def do_clean(channel: str) -> int:
"""Remove every junction this tool created."""
managed_root = ESO_LOCAL_BASE / channel / "CachedData" / "AddOnsManaged"
map_data = _load_map(channel)
removed = 0
for name, a_uuid in list(map_data["managed"].items()):
uuid_dir = managed_root / a_uuid
info_file = uuid_dir / "content_installation_info.json"
try:
meta = json.loads(info_file.read_text())
if not meta.get(REROUTER_TAG):
continue
except Exception:
continue
_safe_remove_uuid_dir(uuid_dir, name, managed_root)
del map_data["managed"][name]
removed += 1
_save_map(channel, map_data)
return removed
def get_addon_statuses(source: Path, channel: str) -> "list[dict]":
managed_root = ESO_LOCAL_BASE / channel / "CachedData" / "AddOnsManaged"
map_data = _load_map(channel)
source_addons = _scan_source(source)
rows = []
for name, info in sorted(source_addons.items(), key=lambda x: x[0].lower()):
a_uuid = map_data["managed"].get(name) or _addon_uuid(name)
junction = managed_root / a_uuid / name
synced = _is_reparse_point(junction)
version = _read_addon_version(info["addon_file"])
rows.append({"name": name, "version": version, "synced": synced})
return rows
# ════════════════════════════════════════════════════════════════════════════
# Config
# ════════════════════════════════════════════════════════════════════════════
def load_config() -> dict:
if CONFIG_FILE.exists():
try:
return json.loads(CONFIG_FILE.read_text())
except Exception:
pass
return {"first_run": True, "source": "", "channel": DEFAULT_CHANNEL}
def save_config(data: dict):
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_FILE.write_text(json.dumps(data, indent=2))
# ════════════════════════════════════════════════════════════════════════════
# UI helpers
# ════════════════════════════════════════════════════════════════════════════
def _apply_dark_ttk():
"""Configure ttk scrollbar to match the dark theme."""
s = ttk.Style()
try:
s.theme_use("clam")
except Exception:
pass
s.configure(
"Vertical.TScrollbar",
background=PANEL2,
troughcolor=BG,
bordercolor=BG,
arrowcolor=MUTED,
relief="flat",
)
s.map("Vertical.TScrollbar", background=[("active", BORDER)])
def _flat_btn(parent, text, command, *, bg=PANEL2, fg=TEXT, hv=BORDER,
font=FONT, padx=14, pady=5, **kw) -> tk.Button:
b = tk.Button(
parent, text=text, command=command,
bg=bg, fg=fg, activebackground=hv, activeforeground=fg,
relief="flat", cursor="hand2", font=font,
padx=padx, pady=pady, **kw,
)
return b
def _sep(parent, **pack_kw):
tk.Frame(parent, height=1, bg=BORDER).pack(fill="x", **pack_kw)
# ════════════════════════════════════════════════════════════════════════════
# Setup dialog
# ════════════════════════════════════════════════════════════════════════════
class SetupDialog(tk.Toplevel):
def __init__(self, parent, on_done):
super().__init__(parent)
self.on_done = on_done
self._selected = tk.StringVar()
self._custom = tk.StringVar()
self.title("Setup - ESO AddOn Manager")
self.geometry("600x430")
self.resizable(False, False)
self.configure(bg=BG)
ico = _find_icon()
if ico:
self.iconbitmap(ico)
self.grab_set()
self.focus_set()
# Centre over parent
self.update_idletasks()
px = parent.winfo_x() + (parent.winfo_width() - self.winfo_width()) // 2
py = parent.winfo_y() + (parent.winfo_height() - self.winfo_height()) // 2
self.geometry(f"+{max(0,px)}+{max(0,py)}")
self._build()
def _build(self):
# Header strip
hdr = tk.Frame(self, bg=ACCENT, pady=16)
hdr.pack(fill="x")
tk.Label(hdr, text="Welcome to ESO AddOn Manager",
bg=ACCENT, fg="#ffffff", font=FONT_TITLE).pack()
tk.Label(hdr,
text="Select the folder where your addon manager keeps your ESO addons.",
bg=ACCENT, fg="#c8d8ff", font=FONT).pack(pady=(3, 0))
body = tk.Frame(self, bg=BG, padx=28)
body.pack(fill="both", expand=True, pady=16)
tk.Label(body, text="DETECTED LOCATIONS", bg=BG, fg=MUTED,
font=FONT_HDR).pack(anchor="w", pady=(0, 6))
# Radio list
radio_frame = tk.Frame(body, bg=PANEL, highlightbackground=BORDER,
highlightthickness=1)
radio_frame.pack(fill="x")
candidates = find_candidate_paths()
first_found = None
for path in candidates:
found = path.is_dir()
if found and first_found is None:
first_found = str(path)
row = tk.Frame(radio_frame, bg=PANEL)
row.pack(fill="x")
rb = tk.Radiobutton(
row, text=str(path),
variable=self._selected, value=str(path),
bg=PANEL, fg=TEXT if found else MUTED,
selectcolor=PANEL, activebackground=PANEL,
activeforeground=ACCENT, font=FONT, anchor="w",
)
rb.pack(side="left", padx=(8, 0), fill="x", expand=True, pady=3)
badge = "✓ Found" if found else "not found"
tk.Label(row, text=badge, bg=PANEL,
fg=SUCCESS if found else MUTED,
font=FONT_SM).pack(side="right", padx=10)
if first_found:
self._selected.set(first_found)
elif candidates:
self._selected.set(str(candidates[0]))
# Custom path row
tk.Label(body, text="OR BROWSE TO A CUSTOM FOLDER", bg=BG, fg=MUTED,
font=FONT_HDR).pack(anchor="w", pady=(14, 4))
row2 = tk.Frame(body, bg=BG)
row2.pack(fill="x")
ent = tk.Entry(row2, textvariable=self._custom, bg=PANEL2, fg=TEXT,
insertbackground=TEXT, relief="flat",
highlightbackground=BORDER, highlightthickness=1, font=FONT)
ent.pack(side="left", fill="x", expand=True, ipady=5)
_flat_btn(row2, "Browse…", self._browse, padx=10).pack(side="left", padx=(6, 0))
# Footer
_sep(self)
foot = tk.Frame(self, bg=PANEL, pady=10)
foot.pack(fill="x")
tk.Label(foot,
text="The folder will be created if it doesn't exist.",
bg=PANEL, fg=MUTED, font=FONT_SM).pack(side="left", padx=20)
_flat_btn(foot, "Get Started →", self._confirm,
bg=ACCENT, fg="#ffffff", hv=ACCENT_HV,
font=FONT_B, padx=18).pack(side="right", padx=16)
def _browse(self):
path = filedialog.askdirectory(
title="Select your ESO AddOns folder",
initialdir=str(USER_PROFILE),
)
if path:
self._custom.set(path)
self._selected.set(path)
def _confirm(self):
path = self._custom.get().strip() or self._selected.get()
if not path:
messagebox.showwarning("No folder selected",
"Please select or browse to your AddOns folder.",
parent=self)
return
p = Path(path)
if not p.is_dir():
if not messagebox.askyesno(
"Folder not found",
f"This folder doesn't exist:\n\n{p}\n\nCreate it and continue?",
parent=self,
):
return
p.mkdir(parents=True, exist_ok=True)
self.destroy()
self.on_done(str(p))
# ════════════════════════════════════════════════════════════════════════════
# Main window
# ════════════════════════════════════════════════════════════════════════════
class MainWindow(tk.Tk):
def __init__(self, config: dict):
super().__init__()
self._cfg = config
self._busy = False
self.title("ESO AddOn Manager - Xbox Game Pass")
self.geometry("760x560")
self.minsize(620, 420)
self.configure(bg=BG)
ico = _find_icon()
if ico:
self.iconbitmap(ico)
_apply_dark_ttk()
self._build_ui()
self.after(120, self._refresh)
# ── Layout ───────────────────────────────────────────────────────────────
def _build_ui(self):
self._build_header()
_sep(self)
self._build_source_bar()
_sep(self)
self._build_list()
_sep(self)
self._build_toolbar()
_sep(self)
self._build_statusbar()
def _build_header(self):
bar = tk.Frame(self, bg=PANEL, pady=11)
bar.pack(fill="x")
tk.Label(bar, text=" ESO AddOn Manager",
bg=PANEL, fg=TEXT, font=FONT_TITLE).pack(side="left")
tk.Label(bar, text="Xbox Game Pass",
bg=PANEL, fg=MUTED, font=FONT).pack(side="left", padx=10)
credit = tk.Label(bar, text="by FairTech ", bg=PANEL, fg=ACCENT,
font=FONT_SM, cursor="hand2")
credit.pack(side="right")
credit.bind("<Button-1>", lambda _: webbrowser.open(CREDITS_URL))
def _build_source_bar(self):
bar = tk.Frame(self, bg=PANEL, pady=7)
bar.pack(fill="x")
tk.Label(bar, text=" Source:", bg=PANEL, fg=MUTED, font=FONT_SM
).pack(side="left")
self._lbl_source = tk.Label(bar, text="", bg=PANEL, fg=TEXT, font=FONT)
self._lbl_source.pack(side="left", padx=6)
_flat_btn(bar, "Change Folder", self._open_setup, padx=10
).pack(side="right", padx=12)
def _build_list(self):
outer = tk.Frame(self, bg=BG)
outer.pack(fill="both", expand=True)
# Column headers
hdr = tk.Frame(outer, bg=PANEL2)
hdr.pack(fill="x")
for label, width in [(" Addon Name", 42), ("Version", 14), ("Status", 14)]:
tk.Label(hdr, text=label, bg=PANEL2, fg=MUTED,
font=FONT_HDR, width=width, anchor="w",
pady=4).pack(side="left")
# Scrollable canvas
container = tk.Frame(outer, bg=BG)
container.pack(fill="both", expand=True)
vscroll = ttk.Scrollbar(container, orient="vertical",
style="Vertical.TScrollbar")
vscroll.pack(side="right", fill="y")
self._canvas = tk.Canvas(container, bg=BG, highlightthickness=0,
yscrollcommand=vscroll.set)
self._canvas.pack(side="left", fill="both", expand=True)
vscroll.config(command=self._canvas.yview)
self._list_frame = tk.Frame(self._canvas, bg=BG)
self._cwin = self._canvas.create_window(
(0, 0), window=self._list_frame, anchor="nw",
)
self._list_frame.bind(
"<Configure>",
lambda e: self._canvas.configure(scrollregion=self._canvas.bbox("all")),
)
self._canvas.bind(
"<Configure>",
lambda e: self._canvas.itemconfig(self._cwin, width=e.width),
)
self.bind_all("<MouseWheel>",
lambda e: self._canvas.yview_scroll(-1 if e.delta > 0 else 1, "units"))
def _build_toolbar(self):
bar = tk.Frame(self, bg=PANEL, pady=9)
bar.pack(fill="x")
self._btn_sync = _flat_btn(
bar, "▶ Sync All", self._do_sync,
bg=ACCENT, fg="#ffffff", hv=ACCENT_HV, font=FONT_B,
)
self._btn_sync.pack(side="left", padx=(12, 6))
_flat_btn(bar, "⟳ Refresh", self._refresh).pack(side="left", padx=(0, 6))
_flat_btn(bar, "✕ Remove All Junctions", self._do_clean,
bg=PANEL2, fg=DANGER, hv=BORDER
).pack(side="left", padx=(0, 6))
def _build_statusbar(self):
self._status_var = tk.StringVar(value="Ready.")
tk.Label(
self, textvariable=self._status_var,
bg=BG, fg=MUTED, font=FONT_SM, anchor="w", pady=4, padx=12,
).pack(fill="x", side="bottom")
# ── Helpers ──────────────────────────────────────────────────────────────
def _source(self) -> Path:
return Path(self._cfg.get("source", "") or "")
def _channel(self) -> str:
return self._cfg.get("channel", DEFAULT_CHANNEL)
def _set_busy(self, busy: bool):
self._busy = busy
self._btn_sync.config(state="disabled" if busy else "normal")
def _status(self, msg: str):
self._status_var.set(msg)
# ── List refresh ─────────────────────────────────────────────────────────
def _refresh(self):
source = self._source()
self._lbl_source.config(
text=str(source) if source.parts else "(not configured - click Change Folder)"
)
for w in self._list_frame.winfo_children():
w.destroy()
if not source.is_dir():
tk.Label(
self._list_frame,
text="No source folder configured.\nClick 'Change Folder' to set one.",
bg=BG, fg=MUTED, font=FONT, pady=30, justify="center",
).pack()
self._status("No source folder configured.")
return
rows = get_addon_statuses(source, self._channel())
total = len(rows)
synced = sum(1 for r in rows if r["synced"])
if total == 0:
tk.Label(
self._list_frame,
text=f"No addons found in:\n{source}\n\n"
"Make sure your addon manager has installed addons to this folder.",
bg=BG, fg=MUTED, font=FONT, pady=30, justify="center",
).pack()
self._status("No addons found in source folder.")
return
for i, row in enumerate(rows):
bg = ROW_ODD if i % 2 == 0 else ROW_EVEN
r = tk.Frame(self._list_frame, bg=bg)
r.pack(fill="x")
tk.Label(r, text=f" {row['name']}", bg=bg, fg=TEXT,
font=FONT, width=42, anchor="w", pady=6).pack(side="left")
tk.Label(r, text=(row["version"] or "-")[:16], bg=bg, fg=MUTED,
font=FONT, width=14, anchor="w").pack(side="left")
if row["synced"]:
badge, badge_fg = "● Synced", SUCCESS
else:
badge, badge_fg = "○ Not Synced", UNSYNC
tk.Label(r, text=badge, bg=bg, fg=badge_fg,
font=FONT, width=14, anchor="w").pack(side="left")
self._status(
f"{total} addon(s) found · {synced} synced · {total - synced} not yet synced"
)
# ── Actions ──────────────────────────────────────────────────────────────
def _run_bg(self, fn, *args, done_msg="Done."):
if self._busy:
return
self._set_busy(True)
self._status("Working…")
def worker():
try:
result = fn(*args)
self.after(0, lambda r=result: self._on_done(r, done_msg))
except Exception as exc:
self.after(0, lambda e=exc: self._on_error(e))
threading.Thread(target=worker, daemon=True).start()
def _on_done(self, result, done_msg):
self._set_busy(False)
if isinstance(result, dict):
parts = [f"{v} {k}" for k, v in result.items() if v]
self._status(done_msg + (" (" + ", ".join(parts) + ")" if parts else ""))
elif isinstance(result, int):
self._status(f"{done_msg} ({result} removed)")
else:
self._status(done_msg)
self._refresh()
def _on_error(self, exc):
self._set_busy(False)
self._status(f"Error: {exc}")
messagebox.showerror("Error", str(exc))
self._refresh()
def _do_sync(self):
if not self._source().is_dir():
messagebox.showwarning("No source folder",
"Please set your AddOns source folder first.")
return
self._run_bg(do_sync, self._source(), self._channel(), done_msg="Sync complete.")
def _do_clean(self):
if not messagebox.askyesno(
"Remove All Junctions",
"This will remove all junctions this tool created in the Game Pass system.\n\n"
"Your actual addon files will NOT be deleted.\n\n"
"Continue?",
):
return
self._run_bg(do_clean, self._channel(), done_msg="All rerouter junctions removed.")
def _open_setup(self):
def on_done(path):
self._cfg["source"] = path
self._cfg["first_run"] = False
save_config(self._cfg)
self._refresh()
SetupDialog(self, on_done)
# ════════════════════════════════════════════════════════════════════════════
# Entry point
# ════════════════════════════════════════════════════════════════════════════
def main():
_elevate()
config = load_config()
app = MainWindow(config)
if config.get("first_run", True) or not config.get("source"):
def _on_setup_done(path):
config["source"] = path
config["first_run"] = False
save_config(config)
app._cfg = config
app._refresh()
app.after(150, lambda: SetupDialog(app, _on_setup_done))
app.mainloop()
if __name__ == "__main__":
main()