-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMCE.OLED.GALLERY.py
More file actions
2344 lines (2021 loc) · 100 KB
/
Copy pathMCE.OLED.GALLERY.py
File metadata and controls
2344 lines (2021 loc) · 100 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
#!/usr/bin/env python3
"""
# MCE OLED Toolset [Gallery]
"""
import os, sys, glob, threading, math, shutil, re, json, subprocess, platform
import datetime
import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import numpy as np
from PIL import Image, ImageTk
# ── Format constants ─────────────────────────────────────────────────────────
OUT_W, OUT_H = 128, 64
COLOR_TABLE_LEN = 8
BITMAP_BYTES = OUT_W * OUT_H // 8
BIN_SIZE = COLOR_TABLE_LEN + BITMAP_BYTES
THUMB_SCALE = 2
THUMB_W = OUT_W * THUMB_SCALE
THUMB_H = OUT_H * THUMB_SCALE
CARD_PAD = 12
CARD_W = THUMB_W + CARD_PAD * 2
ITEMS_PER_PAGE = 60
SCAN_GLOB = "**/*.bin"
PREVIEW_SCALE = 5
PW = OUT_W * PREVIEW_SCALE
PH = OUT_H * PREVIEW_SCALE
_HW_FRAME_CANDIDATES = ["gcmcepr.png", "gcmepr.png"]
SPLASH_Y_OFFSET = 182
SDBUILDER_NAME = "SDBuilder" # local fallback folder name
def resource_path(relative):
base = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base, relative)
def _find_hw_frame_png():
for name in _HW_FRAME_CANDIDATES:
rp = resource_path(name)
if os.path.exists(rp):
return rp
return None
# ── File/path constants ───────────────────────────────────────────────────────
CACHE_DIR = os.path.join(os.getcwd(), ".gallery_cache")
REPORT_FILE = os.path.join(os.getcwd(), "missing_raw_report.json")
CONFIG_FILE = os.path.join(os.getcwd(), "gallery_config.json")
os.makedirs(CACHE_DIR, exist_ok=True)
# ── Colour palette ────────────────────────────────────────────────────────────
BG = "#1e1e2e"
BG2 = "#252537"
CARD_BG = "#2a2a40"
ACCENT = "#7c5bc8"
ACCENT2 = "#9d7de8"
FG = "#dde0f0"
FG_DIM = "#8888aa"
FG_ID = "#e8c07d"
BORDER = "#35354a"
GREEN_REG = "#4CAF50"
RAW_GREEN = "#3ecf6e"
MISSING_RED = "#e07070"
UNMATCHED_CLR = "#e0a840"
BUILDER_CLR = "#5bc8c0" # teal — SDBuilder
PREVIEW_COLOR = (225, 240, 255)
PREVIEW_COLOR_HEX = "#{:02x}{:02x}{:02x}".format(*PREVIEW_COLOR)
FONT = "Arial"
F_TITLE = (FONT, 13, "bold")
F_HEAD = (FONT, 10, "bold")
F_BODY = (FONT, 9, "bold")
F_SMALL = (FONT, 8)
F_TINY = (FONT, 7)
# ── SD path resolution ────────────────────────────────────────────────────────
def resolve_sd_gc(selected_path: str) -> str:
"""
Normalise *any* path the user picks to the MemoryCards/GC subfolder.
Accepted inputs (case-insensitive suffix match):
.../MemoryCards/GC/ → used as-is
.../MemoryCards/ → appends GC/
anything else → appends MemoryCards/GC/
"""
p = os.path.normpath(selected_path)
parts = p.replace("\\", "/").split("/")
lo = [x.lower() for x in parts]
if len(lo) >= 2 and lo[-2] == "memorycards" and lo[-1] == "gc":
return p
if lo[-1] == "memorycards":
return os.path.join(p, "GC")
return os.path.join(p, "MemoryCards", "GC")
def sdbuilder_gc() -> str:
"""Return the local SDBuilder MemoryCards/GC path (always in cwd)."""
return os.path.join(os.getcwd(), SDBUILDER_NAME, "MemoryCards", "GC")
def _next_serial_filename(dest_dir: str, serial: str) -> str:
"""serial.bin → serial-1.bin → serial-2.bin … (first free name)."""
candidate = f"{serial}.bin"
if not os.path.exists(os.path.join(dest_dir, candidate)):
return candidate
n = 1
while True:
candidate = f"{serial}-{n}.bin"
if not os.path.exists(os.path.join(dest_dir, candidate)):
return candidate
n += 1
# ── Pixel / image helpers ─────────────────────────────────────────────────────
def _data_to_rgba(raw_bytes) -> np.ndarray:
raw = np.frombuffer(raw_bytes, dtype=np.uint8)
bits = np.unpackbits(raw, bitorder='big')
vals = np.where(bits == 1, 255, 0).astype(np.uint8).reshape((OUT_H, OUT_W))
rgba = np.zeros((OUT_H, OUT_W, 4), dtype=np.uint8)
rgba[..., 3] = 255
on_mask = vals == 255
rgba[on_mask] = (*PREVIEW_COLOR, 255)
rgba[~on_mask] = (0, 0, 0, 255)
return rgba
def get_base_image(path: str):
base_name = os.path.basename(path)
cache_path = os.path.join(CACHE_DIR, base_name + ".png")
if os.path.exists(cache_path) and \
os.path.getmtime(cache_path) >= os.path.getmtime(path):
try:
return Image.open(cache_path).convert("RGBA")
except Exception:
pass
try:
with open(path, "rb") as f:
data = f.read()
if len(data) != BIN_SIZE:
return None
rgba = _data_to_rgba(data[COLOR_TABLE_LEN:])
img = Image.fromarray(rgba, "RGBA")
img.save(cache_path)
return img
except Exception:
return None
def make_thumb(path: str):
img = get_base_image(path)
if img is None:
return None
return ImageTk.PhotoImage(img.resize((THUMB_W, THUMB_H), Image.NEAREST))
# ── Raw channel helpers ───────────────────────────────────────────────────────
def _find_raw_files(bin_path: str):
folder = os.path.dirname(bin_path)
raws = sorted(glob.glob(os.path.join(folder, "*.raw")))
if not raws:
return []
groups = {}
for r in raws:
name = os.path.basename(r)
stem = os.path.splitext(name)[0]
m = re.search(r'^(.*)-(\d+)$', stem)
if m:
base, num = m.group(1), int(m.group(2))
else:
base, num = stem, None
groups.setdefault(base, []).append((num, name))
result = []
for base, entries in groups.items():
entries.sort(key=lambda x: (-1 if x[0] is None else x[0]))
has_base = any(n is None for n, _ in entries)
for i, (num, name) in enumerate(entries):
channel = (1 if num is None else num + 1) if has_base else (i + 1)
result.append((channel, name))
result.sort(key=lambda x: x[0])
return result
# ── Misc helpers ──────────────────────────────────────────────────────────────
def open_file_location(path: str) -> None:
folder = os.path.dirname(os.path.abspath(path))
try:
system = platform.system()
if system == "Windows":
subprocess.Popen(["explorer", "/select,", os.path.abspath(path)])
elif system == "Darwin":
subprocess.Popen(["open", folder])
else:
subprocess.Popen(["xdg-open", folder])
except OSError as e:
messagebox.showerror("Open Location", f"Could not open folder:\n{e}")
# ── Main Application ──────────────────────────────────────────────────────────
class BinGallery(tk.Tk):
def __init__(self):
super().__init__()
self.title("MCE Splash Gallery")
self.geometry("1200x900")
self.minsize(900, 600)
self.configure(bg=BG)
self._cfg = {}
self._load_config()
self._scan_root = tk.StringVar(value=self._cfg.get(
"scan_root", os.path.join(os.getcwd(), "MemoryCards", "GC")))
self._sd_root_last = self._cfg.get("sd_card_root", "")
self._filter_var = tk.StringVar()
self._filter_var.trace_add("write", lambda *_: self._apply_filter())
self._hide_alts = tk.BooleanVar(value=True)
self._filter_has_raw = tk.BooleanVar(value=False)
self._filter_has_raw.trace_add("write", lambda *_: self._apply_filter())
self._current_region = "ALL"
self._current_letter = "ALL"
self.game_db = {}
# (path, rel, core_serial, db, raw_name, is_alt, has_raw, is_unmatched)
self._all_items = []
self._shown = []
self._thumbs = {}
self._thumb_lock = threading.Lock()
self.current_page = 0
self.total_pages = 1
self._loading = False
self._cols = 4
# Build list: path → {serial, db, raw_name, is_unmatched}
self._build_list: dict = {}
self._load_json_db()
self._build_ui()
self.protocol("WM_DELETE_WINDOW", self._on_close)
# ── Config ────────────────────────────────────────────────────────────────
def _load_config(self):
try:
with open(CONFIG_FILE, encoding="utf-8") as f:
self._cfg = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
self._cfg = {}
raw_col = self._cfg.get("preview_color")
if isinstance(raw_col, list) and len(raw_col) == 3:
global PREVIEW_COLOR, PREVIEW_COLOR_HEX
PREVIEW_COLOR = tuple(int(c) for c in raw_col)
PREVIEW_COLOR_HEX = "#{:02x}{:02x}{:02x}".format(*PREVIEW_COLOR)
def _save_config(self):
self._cfg["scan_root"] = self._scan_root.get()
self._cfg["sd_card_root"] = self._sd_root_last
self._cfg["preview_color"] = list(PREVIEW_COLOR)
try:
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(self._cfg, f, indent=2)
except Exception as ex:
print(f"Config save failed: {ex}")
def _on_close(self):
self._save_config()
self.destroy()
# ── Database ──────────────────────────────────────────────────────────────
def _load_json_db(self):
json_path = self._cfg.get("db_path",
resource_path("database.json"))
if not os.path.exists(json_path):
json_path = resource_path("database.json")
if not os.path.exists(json_path):
print("Notice: database.json not found. Running without titles.")
return
try:
with open(json_path, "r", encoding="utf-8") as f:
try:
data = json.load(f)
except json.JSONDecodeError:
f.seek(0)
data = [json.loads(line) for line in f if line.strip()]
for item in data:
serial = str(item.get("serial", "")).strip()
if serial and serial != "-":
self.game_db[serial] = {
"title": str(item.get("title", "")).strip(),
"id": str(item.get("id", "")).strip(),
"region": str(item.get("region", "")).strip(),
}
print(f"Loaded {len(self.game_db)} entries from database.json")
except Exception as e:
print(f"Error parsing JSON: {e}")
# ── Treeview style helper ─────────────────────────────────────────────────
def _configure_dark_treeview(self, style_name: str = "Dark.Treeview"):
s = ttk.Style()
s.configure(style_name,
background=BG2, foreground=FG, fieldbackground=BG2,
rowheight=24, font=(FONT, 8), borderwidth=0, relief="flat")
s.configure(f"{style_name}.Heading",
background=BG, foreground=FG_DIM, relief="flat",
font=(FONT, 8, "bold"))
s.map(style_name,
background=[("selected", ACCENT)],
foreground=[("selected", "white")])
# ── UI Build ──────────────────────────────────────────────────────────────
def _build_ui(self):
style = ttk.Style()
style.theme_use("clam")
style.configure("TEntry", fieldbackground=BG2, foreground=FG,
insertcolor=FG, bordercolor=BORDER)
style.configure("TScrollbar", background=BG2, troughcolor=BG,
arrowcolor=FG_DIM, bordercolor=BG)
self._configure_dark_treeview()
# ── Top bar ───────────────────────────────────────────────────────────
top = tk.Frame(self, bg=BG, pady=8, padx=12)
top.pack(fill="x")
tk.Label(top, text="MCE Splash Gallery", font=F_TITLE,
fg=ACCENT2, bg=BG).pack(side="left")
btn_frame = tk.Frame(top, bg=BG)
btn_frame.pack(side="right")
self.btn_alt_toggle = self._btn(btn_frame, "Hide Alternatives", self._toggle_alts)
self.btn_alt_toggle.pack(side="left", padx=4)
self._update_alt_btn_ui()
self._btn(btn_frame, "Missing Splash Files", self._show_missing_bins,
color=BG2, fg=MISSING_RED).pack(side="left", padx=4)
self._btn(btn_frame, "Missing RAW Files", self._show_missing_raw,
color=BG2, fg=MISSING_RED).pack(side="left", padx=4)
self._btn(btn_frame, "Compare to SD", self._compare_to_sd,
color=BG2, fg=ACCENT2).pack(side="left", padx=4)
self._btn(btn_frame, "Auto Fill SD", self._auto_fill_sd).pack(side="left", padx=4)
self.btn_build_list = self._btn(btn_frame, "📋 Build List (0)",
self._open_build_list,
color=BG2, fg=BUILDER_CLR)
self.btn_build_list.pack(side="left", padx=4)
self._btn(btn_frame, "Choose Folder", self._pick_folder).pack(side="left", padx=4)
self._btn(btn_frame, "Rescan", self._start_scan).pack(side="left", padx=4)
self._btn(btn_frame, "⚙ Settings", self._open_settings,
color=BG2, fg=FG_DIM).pack(side="left", padx=4)
# ── Filter bar ────────────────────────────────────────────────────────
bar = tk.Frame(self, bg=BG2, padx=12, pady=6)
bar.pack(fill="x")
tk.Label(bar, text="DIR:", fg=FG_DIM, bg=BG2, font=F_SMALL).pack(side="left")
tk.Label(bar, textvariable=self._scan_root, fg=FG, bg=BG2,
font=F_SMALL, anchor="w").pack(side="left", padx=(4, 10))
tk.Label(bar, text="Search:", fg=FG_DIM, bg=BG2, font=F_SMALL).pack(side="left")
self._filter_entry = tk.Entry(
bar, textvariable=self._filter_var, bg=BG, fg=FG,
relief="flat", font=F_SMALL,
highlightthickness=1, highlightcolor=ACCENT,
highlightbackground=BORDER, width=20)
self._filter_entry.pack(side="left", padx=6)
reg_frame = tk.Frame(bar, bg=BG2)
reg_frame.pack(side="left", padx=10)
for r in ["ALL", "USA", "EUR", "JAP"]:
b = tk.Button(reg_frame, text=r, font=(FONT, 8, "bold"), bg=BG, fg=FG_DIM,
relief="flat", padx=6, command=lambda x=r: self._set_region(x))
b.pack(side="left", padx=2)
setattr(self, f"reg_btn_{r}", b)
self._update_region_ui()
self.btn_has_raw = tk.Button(
bar, text="Has RAW file", font=(FONT, 8, "bold"),
bg=BG, fg=FG_DIM, relief="flat", padx=8,
cursor="hand2", command=self._toggle_has_raw)
self.btn_has_raw.pack(side="left", padx=(6, 2))
self._update_has_raw_ui()
self._status_var = tk.StringVar(value="No scan yet")
tk.Label(bar, textvariable=self._status_var, fg=FG_ID, bg=BG2,
font=F_SMALL).pack(side="right")
# ── Alpha bar ─────────────────────────────────────────────────────────
alpha_bar = tk.Frame(self, bg=BG, padx=12, pady=2)
alpha_bar.pack(fill="x")
chars = ["ALL", "#"] + [chr(i) for i in range(ord('A'), ord('Z') + 1)] + ["?"]
for c in chars:
fg_col = UNMATCHED_CLR if c == "?" else FG_DIM
display = "Unmatched" if c == "?" else c
b = tk.Button(alpha_bar, text=display, font=(FONT, 7, "bold"),
bg=BG, fg=fg_col, relief="flat", padx=2,
command=lambda x=c: self._set_letter(x))
b.pack(side="left", expand=True)
setattr(self, f"let_btn_{c}", b)
self._update_letter_ui()
# ── Pagination bar (bottom) ───────────────────────────────────────────
page_bar = tk.Frame(self, bg=BG2, pady=8)
page_bar.pack(fill="x", side="bottom")
self.btn_prev = self._btn(page_bar, "< Previous", self._prev_page)
self.btn_prev.pack(side="left", padx=20)
self.lbl_page = tk.Label(page_bar, text="Page 1 / 1", fg=FG, bg=BG2,
font=(FONT, 10, "bold"))
self.lbl_page.pack(side="left", expand=True)
self.btn_next = self._btn(page_bar, "Next >", self._next_page)
self.btn_next.pack(side="right", padx=20)
# ── Scrollable grid ───────────────────────────────────────────────────
container = tk.Frame(self, bg=BG)
container.pack(fill="both", expand=True, padx=8, pady=6)
self._vscroll = ttk.Scrollbar(container, orient="vertical")
self._vscroll.pack(side="right", fill="y")
self._canvas = tk.Canvas(container, bg=BG, highlightthickness=0,
yscrollcommand=self._vscroll.set)
self._canvas.pack(side="left", fill="both", expand=True)
self._vscroll.config(command=self._canvas.yview)
self._grid_frame = tk.Frame(self._canvas, bg=BG)
self._canvas_window = self._canvas.create_window(
(0, 0), window=self._grid_frame, anchor="nw")
self._grid_frame.bind("<Configure>",
lambda e: self._canvas.configure(scrollregion=self._canvas.bbox("all")))
self._canvas.bind("<Configure>", self._on_canvas_resize)
self._canvas.bind("<MouseWheel>",
lambda e: self._canvas.yview_scroll(-1 * (e.delta // 120), "units"))
self._canvas.bind("<Button-4>",
lambda e: self._canvas.yview_scroll(-1, "units"))
self._canvas.bind("<Button-5>",
lambda e: self._canvas.yview_scroll(1, "units"))
def _btn(self, parent, text, cmd, color=BG2, fg=FG):
return tk.Button(parent, text=text, command=cmd,
bg=color, fg=fg,
activebackground=ACCENT, activeforeground="white",
relief="flat", font=F_BODY, padx=12, pady=4,
cursor="hand2")
def _pick_folder(self):
d = filedialog.askdirectory(initialdir=self._scan_root.get())
if d:
self._scan_root.set(d)
self._save_config()
# ── Filter toggles ────────────────────────────────────────────────────────
def _toggle_alts(self):
self._hide_alts.set(not self._hide_alts.get())
self._update_alt_btn_ui()
self._apply_filter()
def _update_alt_btn_ui(self):
self.btn_alt_toggle.config(
text="Hidden Alts" if self._hide_alts.get() else "Showing Alts",
fg=FG_DIM if self._hide_alts.get() else ACCENT2)
def _toggle_has_raw(self):
self._filter_has_raw.set(not self._filter_has_raw.get())
self._update_has_raw_ui()
self._apply_filter()
def _update_has_raw_ui(self):
if self._filter_has_raw.get():
self.btn_has_raw.config(fg=RAW_GREEN, bg=CARD_BG)
else:
self.btn_has_raw.config(fg=FG_DIM, bg=BG)
def _set_region(self, r):
self._current_region = r
self._update_region_ui()
self._apply_filter()
def _update_region_ui(self):
for r in ["ALL", "USA", "EUR", "JAP"]:
btn = getattr(self, f"reg_btn_{r}")
btn.config(fg=ACCENT2 if r == self._current_region else FG_DIM,
bg=CARD_BG if r == self._current_region else BG)
def _set_letter(self, c):
self._current_letter = c
self._update_letter_ui()
self._apply_filter()
def _update_letter_ui(self):
chars = ["ALL", "#"] + [chr(i) for i in range(ord('A'), ord('Z') + 1)] + ["?"]
for c in chars:
btn = getattr(self, f"let_btn_{c}", None)
if btn is None:
continue
active = (c == self._current_letter)
if c == "?":
btn.config(fg=UNMATCHED_CLR, bg=CARD_BG if active else BG)
else:
btn.config(fg=ACCENT2 if active else FG_DIM,
bg=CARD_BG if active else BG)
# ── Build List management ─────────────────────────────────────────────────
def _add_to_build_list(self, path, serial, db, raw_name, is_unmatched):
self._build_list[path] = {
"serial": serial, "db": db,
"raw_name": raw_name, "is_unmatched": is_unmatched,
}
count = len(self._build_list)
self.btn_build_list.config(text=f"📋 Build List ({count})")
def _remove_from_build_list(self, path):
self._build_list.pop(path, None)
count = len(self._build_list)
self.btn_build_list.config(text=f"📋 Build List ({count})")
def _in_build_list(self, path) -> bool:
return path in self._build_list
# ── SD destination picker ─────────────────────────────────────────────────
def _pick_destination(self, parent=None) -> tuple:
"""
Show a small dialog asking whether to target an SD card or the local
SDBuilder folder. Returns (gc_path, label) or (None, None) if cancelled.
"""
result = [None, None]
dlg = tk.Toplevel(parent or self)
dlg.title("Choose Destination")
dlg.geometry("520x240")
dlg.configure(bg=BG)
dlg.resizable(False, False)
dlg.transient(parent or self)
tk.Label(dlg, text="WHERE TO COPY?", font=F_HEAD,
fg=ACCENT2, bg=BG, padx=20, pady=14).pack(anchor="w")
info = tk.Frame(dlg, bg=BG2, padx=20, pady=10)
info.pack(fill="x")
dest_var = tk.StringVar(value="")
tk.Label(info, textvariable=dest_var, fg=ACCENT2, bg=BG2,
font=F_SMALL, wraplength=460, justify="left").pack(anchor="w")
def _set_sd():
d = filedialog.askdirectory(
title="Select SD Card (or MemoryCards or MemoryCards/GC folder)",
initialdir=self._sd_root_last or os.getcwd(),
parent=dlg)
if not d:
return
gc = resolve_sd_gc(d)
dest_var.set(f"SD Card → {gc}")
result[0] = gc
result[1] = "SD"
def _set_builder():
gc = sdbuilder_gc()
dest_var.set(f"SDBuilder → {gc}")
result[0] = gc
result[1] = "SDBuilder"
btns = tk.Frame(dlg, bg=BG, pady=10, padx=20)
btns.pack(fill="x")
self._btn(btns, "💾 Select SD Card",
_set_sd, color=ACCENT, fg="white").pack(side="left", padx=(0, 8))
self._btn(btns, f"🗂 Use {SDBUILDER_NAME}/ folder",
_set_builder, color=BG2, fg=BUILDER_CLR).pack(side="left")
confirm_row = tk.Frame(dlg, bg=BG, pady=6, padx=20)
confirm_row.pack(fill="x")
tk.Label(confirm_row,
text="Select a destination above, then click Confirm.",
fg=FG_DIM, bg=BG, font=F_TINY).pack(side="left")
def _confirm():
if result[0] is None:
messagebox.showwarning("No Destination",
"Please select a destination first.", parent=dlg)
return
if result[1] == "SD":
self._sd_root_last = result[0]
self._save_config()
dlg.destroy()
self._btn(confirm_row, "Confirm", _confirm,
color=ACCENT, fg="white").pack(side="right")
self._btn(confirm_row, "Cancel",
lambda: (result.__setitem__(0, None), dlg.destroy()),
color=BG2).pack(side="right", padx=(0, 6))
dlg.grab_set()
dlg.wait_window()
return result[0], result[1]
# ── Unified file-copy helper ──────────────────────────────────────────────
def _collect_copy_pairs(self, src_path: str, serial: str, raw_name: str,
gc_root: str,
include_alts: bool,
include_raw: bool,
include_ini: bool) -> list:
"""
Build a list of (src, dst) pairs for one game entry.
Always copies the main .bin.
Optionally copies -1/-2/… .bin alts, .raw, and .ini files.
Destination is gc_root/<serial>/<filename>.
"""
dest_dir = os.path.join(gc_root, serial)
src_dir = os.path.dirname(src_path)
pairs = []
def _add(src, dst_name):
pairs.append((src, os.path.join(dest_dir, dst_name)))
# Main .bin
_add(src_path, raw_name)
if include_alts:
# Every other .bin in the same folder whose stem starts with the serial
for f in sorted(os.listdir(src_dir)):
if f == raw_name:
continue
if f.upper().startswith(serial.upper()) and \
f.lower().endswith(".bin"):
_add(os.path.join(src_dir, f), f)
if include_ini:
# serial.ini or raw_name.ini companion
for ini_name in [raw_name.replace(".bin", ".ini"),
serial + ".ini"]:
ini_path = os.path.join(src_dir, ini_name)
if os.path.exists(ini_path):
_add(ini_path, ini_name)
break
if include_raw:
for f in sorted(os.listdir(src_dir)):
if f.lower().endswith(".raw"):
_add(os.path.join(src_dir, f), f)
return pairs
# ── Scanning ──────────────────────────────────────────────────────────────
def _start_scan(self):
if self._loading:
return
self._loading = True
self._status_var.set("Scanning...")
self._all_items.clear()
threading.Thread(target=self._scan_thread, daemon=True).start()
def _scan_thread(self):
root = self._scan_root.get()
pattern = os.path.join(root, SCAN_GLOB)
found = []
try:
for p in glob.glob(pattern, recursive=True):
if os.path.isfile(p) and os.path.getsize(p) == BIN_SIZE:
rel = os.path.relpath(p, root)
base_name = os.path.basename(p)
raw_serial = base_name.replace(".bin", "").upper()
match = re.search(r'-(\d+)$', raw_serial)
core_serial = re.sub(r'-\d+$', '', raw_serial)
is_alt = bool(match)
has_raw = bool(_find_raw_files(p))
is_unmatched = core_serial not in self.game_db
db_info = dict(self.game_db.get(core_serial, {}))
alt_tag = f" (Alt {match.group(1)})" if match else ""
if "title" in db_info:
db_info["title"] += alt_tag
else:
db_info["title"] = base_name
found.append((p, rel, core_serial, db_info,
base_name, is_alt, has_raw, is_unmatched))
except Exception as e:
self.after(0, lambda: self._status_var.set(f"Error: {e}"))
self._loading = False
return
found.sort(key=lambda x: x[3].get("title", x[1]).lower())
self._all_items = found
self.after(0, self._apply_filter)
self.after(0, lambda: self._prune_cache(found))
self._loading = False
def _apply_filter(self):
q = self._filter_var.get().lower()
reg = self._current_region
let = self._current_letter
hide = self._hide_alts.get()
need_raw = self._filter_has_raw.get()
self._shown = []
hidden_count = 0
for item in self._all_items:
path, rel, serial, db, raw_name, is_alt, has_raw, is_unmatched = item
title = db.get("title", "").lower()
game_id = db.get("id", "").lower()
region = db.get("region", "Unknown").upper()
if hide and is_alt:
hidden_count += 1
continue
if need_raw and not has_raw:
continue
if reg != "ALL" and reg not in region:
continue
if let == "?":
if not is_unmatched:
continue
elif let != "ALL":
first_char = title[0].upper() if title else ""
if let == "#":
if not first_char.isdigit():
continue
elif first_char != let:
continue
if q and not (q in rel.lower() or q in serial.lower()
or q in raw_name.lower() or q in title or q in game_id):
continue
self._shown.append(item)
self.total_pages = max(1, math.ceil(len(self._shown) / ITEMS_PER_PAGE))
self.current_page = 0
unmatched_count = sum(1 for i in self._all_items if i[7])
raw_suffix = " [Has RAW]" if need_raw else ""
self._status_var.set(
f"{len(self._shown)} files (hidden: {hidden_count})"
f" | unmatched: {unmatched_count}{raw_suffix}")
self._rebuild_grid()
# ── Build List window ─────────────────────────────────────────────────────
def _open_build_list(self):
win = tk.Toplevel(self)
win.title(f"Build List — {len(self._build_list)} items")
win.geometry("1060x700")
win.configure(bg=BG)
hdr = tk.Frame(win, bg=BG, padx=16, pady=10)
hdr.pack(fill="x")
tk.Label(hdr, text="BUILD LIST", font=F_HEAD, fg=BUILDER_CLR, bg=BG).pack(side="left")
self._btn(hdr, "Close", win.destroy).pack(side="right")
tk.Label(hdr,
text=" Select items then copy to SD card or local SDBuilder folder.",
fg=FG_DIM, bg=BG, font=F_SMALL).pack(side="left")
# ── Options bar ───────────────────────────────────────────────────────
opts = tk.Frame(win, bg=BG2, padx=16, pady=8)
opts.pack(fill="x")
inc_alts = tk.BooleanVar(value=False)
inc_raw = tk.BooleanVar(value=True)
inc_ini = tk.BooleanVar(value=True)
for var, label in [(inc_alts, "Include Alt .bin (-1/-2…)"),
(inc_raw, "Include .raw channels"),
(inc_ini, "Include .ini companion")]:
tk.Checkbutton(opts, text=label, variable=var,
bg=BG2, fg=FG, selectcolor=BG,
activebackground=BG2, activeforeground=FG,
font=F_SMALL).pack(side="left", padx=(0, 12))
# ── Treeview ──────────────────────────────────────────────────────────
self._configure_dark_treeview("BL.Treeview")
cols = ("sel", "title", "serial", "region", "path")
tv_frame = tk.Frame(win, bg=BG)
tv_frame.pack(fill="both", expand=True, padx=8, pady=4)
vsb = ttk.Scrollbar(tv_frame, orient="vertical")
vsb.pack(side="right", fill="y")
tree = ttk.Treeview(tv_frame, columns=cols, show="headings",
style="BL.Treeview", selectmode="extended",
yscrollcommand=vsb.set)
tree.pack(side="left", fill="both", expand=True)
vsb.config(command=tree.yview)
tree.heading("sel", text="✓")
tree.heading("title", text="Title")
tree.heading("serial", text="Serial")
tree.heading("region", text="Region")
tree.heading("path", text="Source Path")
tree.column("sel", width=30, anchor="c", stretch=False)
tree.column("title", width=300, anchor="w")
tree.column("serial", width=180, anchor="w")
tree.column("region", width=120, anchor="w")
tree.column("path", width=0, anchor="w", stretch=True)
tree.tag_configure("odd", background=BG)
tree.tag_configure("even", background=BG2)
tree.tag_configure("checked", foreground=RAW_GREEN)
tree.tag_configure("unchecked", foreground=FG)
checked = set() # iids that are checked
def _refresh_tree():
for iid in tree.get_children():
tree.delete(iid)
checked.clear()
for i, (path, info) in enumerate(self._build_list.items()):
serial = info["serial"]
db = info["db"]
tag = "odd" if i % 2 == 0 else "even"
iid = str(i)
tree.insert("", "end", iid=iid, tags=(tag,), values=(
"☑", db.get("title", info["raw_name"]),
serial, db.get("region", "-"), path))
checked.add(iid)
win.title(f"Build List — {len(self._build_list)} items")
def _toggle_check(event):
iid = tree.identify_row(event.y)
if not iid:
return
if iid in checked:
checked.discard(iid)
tree.set(iid, "sel", "☐")
else:
checked.add(iid)
tree.set(iid, "sel", "☑")
tree.bind("<Button-1>", _toggle_check)
tree.bind("<MouseWheel>",
lambda e: tree.yview_scroll(-1 * (e.delta // 120), "units"))
tree.bind("<Button-4>", lambda e: tree.yview_scroll(-1, "units"))
tree.bind("<Button-5>", lambda e: tree.yview_scroll(1, "units"))
# Double-click → open preview
def _on_double(event):
iid = tree.identify_row(event.y)
if not iid:
return
vals = tree.item(iid, "values")
if not vals:
return
src_path = vals[4]
info = self._build_list.get(src_path)
if info:
self._open_preview(src_path, info["serial"],
info["db"], info["raw_name"],
info["is_unmatched"])
tree.bind("<Double-Button-1>", _on_double)
# ── Bottom controls ───────────────────────────────────────────────────
ctrl = tk.Frame(win, bg=BG2, padx=16, pady=8)
ctrl.pack(fill="x")
def _get_checked_items():
items = []
for iid in list(tree.get_children()):
if iid in checked:
vals = tree.item(iid, "values")
if vals:
src_path = vals[4]
info = self._build_list.get(src_path)
if info:
items.append((src_path, info))
return items
def _remove_selected():
iids = sorted(checked, key=lambda x: int(x), reverse=True)
paths_to_remove = []
for iid in iids:
vals = tree.item(iid, "values")
if vals:
paths_to_remove.append(vals[4])
for p in paths_to_remove:
self._remove_from_build_list(p)
_refresh_tree()
def _copy_checked(gc_root, label):
items = _get_checked_items()
if not items:
messagebox.showwarning("Nothing Selected",
"Check at least one item first.", parent=win)
return
pairs = []
for src_path, info in items:
pairs += self._collect_copy_pairs(
src_path, info["serial"], info["raw_name"],
gc_root,
include_alts=inc_alts.get(),
include_raw=inc_raw.get(),
include_ini=inc_ini.get())
def _done(n, errors):
msg = f"Copied {n} file(s) to {label}."
if errors:
msg += "\n\nErrors:\n" + "\n".join(errors[:10])
messagebox.showinfo("Copy Complete", msg, parent=win)
self._run_copy_async(pairs, win, _done)
def _copy_to_dest():
gc_root, label = self._pick_destination(win)
if gc_root is None:
return
_copy_checked(gc_root, label)
def _select_all():
for iid in tree.get_children():
checked.add(iid)
tree.set(iid, "sel", "☑")
def _select_none():
checked.clear()
for iid in tree.get_children():
tree.set(iid, "sel", "☐")
def _clear_list():
if not self._build_list:
return
if messagebox.askyesno("Clear List",
"Remove all items from the build list?", parent=win):
self._build_list.clear()
self.btn_build_list.config(text="📋 Build List (0)")
_refresh_tree()
self._btn(ctrl, "✔ Copy Checked to SD / Builder",
_copy_to_dest, color=ACCENT, fg="white").pack(side="left", padx=(0, 8))
self._btn(ctrl, "🗑 Remove Selected", _remove_selected,
color=BG2, fg=MISSING_RED).pack(side="left", padx=(0, 8))
self._btn(ctrl, "Clear All", _clear_list,
color=BG2, fg=FG_DIM).pack(side="left")
self._btn(ctrl, "None", _select_none, color=BG2).pack(side="right", padx=2)
self._btn(ctrl, "All", _select_all, color=BG2).pack(side="right", padx=2)
tk.Label(ctrl, text="Select:", fg=FG_DIM, bg=BG2,
font=F_SMALL).pack(side="right", padx=(8, 0))
_refresh_tree()
win.grab_set()
# ── Missing BINs window ───────────────────────────────────────────────────
def _show_missing_bins(self):
win = tk.Toplevel(self)
win.title("Missing Splash Files")
win.geometry("1060x720")
win.configure(bg=BG)
hdr = tk.Frame(win, bg=BG, padx=16, pady=10)
hdr.pack(fill="x")
tk.Label(hdr, text="MISSING SPLASH FILES", font=F_HEAD,
fg=MISSING_RED, bg=BG).pack(side="left")
self._btn(hdr, "Close", win.destroy).pack(side="right")
# SD cross-reference bar
sd_bar = tk.Frame(win, bg=BG2, padx=16, pady=6)
sd_bar.pack(fill="x")
sd_gc_var = tk.StringVar(value="")
tk.Label(sd_bar, text="SD card (optional cross-check):",
fg=FG_DIM, bg=BG2, font=F_SMALL).pack(side="left")
sd_lbl = tk.Label(sd_bar, textvariable=sd_gc_var, fg=ACCENT2, bg=BG2,
font=F_SMALL, anchor="w")
sd_lbl.pack(side="left", padx=(6, 12))
def _pick_sd():
d = filedialog.askdirectory(
title="Select SD Card for cross-check",
initialdir=self._sd_root_last or os.getcwd(),
parent=win)
if d:
sd_gc_var.set(resolve_sd_gc(d))
_populate()
self._btn(sd_bar, "Pick SD…", _pick_sd, color=BG2, fg=ACCENT2).pack(side="left")
sub = tk.Frame(win, bg=BG, padx=16, pady=4)
sub.pack(fill="x")
count_var = tk.StringVar(value="")
tk.Label(sub, textvariable=count_var, fg=FG_DIM, bg=BG,
font=F_SMALL).pack(side="left")
self._btn(sub, "⟳ Refresh", lambda: _populate(),
color=BG2, fg=ACCENT2).pack(side="right")
# Treeview
self._configure_dark_treeview("MBin.Treeview")
columns = ("title", "serial", "id", "region", "on_sd", "expected")
tv_frame = tk.Frame(win, bg=BG)
tv_frame.pack(fill="both", expand=True, padx=8, pady=(4, 8))
vsb = ttk.Scrollbar(tv_frame, orient="vertical")
vsb.pack(side="right", fill="y")
hsb = ttk.Scrollbar(tv_frame, orient="horizontal")
hsb.pack(side="bottom", fill="x")
tree = ttk.Treeview(tv_frame, columns=columns, show="headings",
style="MBin.Treeview", selectmode="browse",
yscrollcommand=vsb.set, xscrollcommand=hsb.set)
tree.pack(side="left", fill="both", expand=True)
vsb.config(command=tree.yview)
hsb.config(command=tree.xview)
tree.tag_configure("odd", background=BG)
tree.tag_configure("even", background=BG2)
tree.tag_configure("on_sd", foreground=RAW_GREEN)
_sort_state = {"col": None, "rev": False}
COL_LABELS = {"title": "Title", "serial": "Serial", "id": "Game ID",
"region": "Region", "on_sd": "On SD?", "expected": "Expected Folder"}
COL_WIDTHS = {"title": 280, "serial": 160, "id": 70,
"region": 120, "on_sd": 60, "expected": 0}