-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSteamRoulette.py
More file actions
1916 lines (1641 loc) · 79.9 KB
/
Copy pathSteamRoulette.py
File metadata and controls
1916 lines (1641 loc) · 79.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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import io
import queue
import random
import platform
import webbrowser
import requests
import tkinter as tk
from tkinter import messagebox, ttk
from PIL import Image, ImageDraw, ImageFont, ImageTk
from io import BytesIO
import json
import vdf
import sys
from concurrent.futures import ThreadPoolExecutor
import time
import winreg
import threading
from functools import lru_cache
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
PLACEHOLDER_IMAGE_DIMENSIONS = (600, 300)
ANIMATION_DURATION_MS = 7600 # total desired spin duration
FRAME_DELAY_MS = 16 # ~60 FPS
SLOWDOWN_FACTOR = 0.95 # speed multiplier each frame during deceleration
MIN_SPEED = 5 # pixels/frame floor during slowdown
PRELOAD_WORKERS = 10 # threads used for parallel image pre-load
IMAGE_CACHE_SUBDIR = "image_cache"
# Steam tool/redistributable app IDs that should never appear as spinnable games
NON_GAME_APP_IDS = {
"228980", # Steamworks Common Redistributables
"250820", # SteamVR
"1070560", # Steam Linux Runtime
"1391110", # Steam Linux Runtime - Soldier
"1628350", # Steam Linux Runtime - Sniper
"1493710", # Proton Experimental
"1887720", # Proton 7.0
"2348590", # Proton 8.0
"1245040", # Proton 5.0
"1420170", # Proton 5.13
"1580130", # Proton 6.3
"223850", # 3DMark
"365670", # Blender
"431960", # Wallpaper Engine
"3419430", # Bongo Cat
}
# ---------------------------------------------------------------------------
# Path helpers
# ---------------------------------------------------------------------------
def _exe_dir() -> str:
"""Directory that contains the running executable (or script in dev mode)."""
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
def _data_path(filename: str) -> str:
"""Resolve a user-data file (api key, user id, exclusions) next to the exe."""
return os.path.join(_exe_dir(), filename)
def resource_path(relative_path: str) -> str:
"""Resolve a bundled resource (icons, logos) – works in dev and PyInstaller."""
try:
base = sys._MEIPASS # PyInstaller temp dir
except AttributeError:
base = os.path.dirname(os.path.abspath(__file__))
return os.path.join(base, relative_path)
# ---------------------------------------------------------------------------
# Steam installation discovery
# ---------------------------------------------------------------------------
def get_steam_install_path() -> str | None:
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Valve\Steam")
path, _ = winreg.QueryValueEx(key, "SteamPath")
return path
except FileNotFoundError:
return None
def find_steam_path_fallback() -> str | None:
candidates = [
r"C:\Program Files (x86)\Steam",
r"C:\Program Files\Steam",
os.path.expanduser(r"~\AppData\Local\Steam"),
]
for p in candidates:
if os.path.exists(os.path.join(p, "steam.exe")):
return p
return None
STEAM_PATH = get_steam_install_path() or find_steam_path_fallback()
ICON_PATH = resource_path("SteamRouletteIcon.ico")
# ---------------------------------------------------------------------------
# Cache directory
# ---------------------------------------------------------------------------
def create_cache_directory() -> str:
cache_dir = os.path.join(_exe_dir(), IMAGE_CACHE_SUBDIR)
os.makedirs(cache_dir, exist_ok=True)
return cache_dir
# ---------------------------------------------------------------------------
# VDF / ACF parsing
# ---------------------------------------------------------------------------
def parse_vdf(file_path: str) -> dict:
try:
with open(file_path, "r", encoding="utf-8") as fh:
content = vdf.parse(fh)
libraries = content.get("libraryfolders", {})
return {
key: value.get("path")
for key, value in libraries.items()
if isinstance(value, dict) and "path" in value
}
except Exception as e:
print(f"Error parsing VDF file: {e}")
return {}
@lru_cache(maxsize=None)
def fetch_game_data(acf_path: str, library_path: str) -> dict:
try:
with open(acf_path, "r", encoding="utf-8") as fh:
content = vdf.parse(fh).get("AppState", {})
return {
"app_id": content.get("appid"),
"name": content.get("name"),
"path": library_path,
}
except Exception as e:
print(f"Error reading ACF file {acf_path}: {e}")
return {}
def get_installed_games(steam_path: str) -> list:
library_folders = parse_vdf(os.path.join(steam_path, "steamapps", "libraryfolders.vdf"))
installed_games = []
seen_ids: set = set()
for library_path in library_folders.values():
if not (library_path and isinstance(library_path, str)):
continue
steamapps_path = os.path.join(library_path, "steamapps")
if not os.path.exists(steamapps_path):
continue
for acf_file in filter(lambda f: f.endswith(".acf"), os.listdir(steamapps_path)):
game = fetch_game_data(os.path.join(steamapps_path, acf_file), library_path)
if not game or not game.get("app_id"):
print(f"Excluded invalid game entry: {game}")
continue
app_id = str(game["app_id"])
if app_id in NON_GAME_APP_IDS:
print(f"Skipping non-game tool: {game.get('name')} ({app_id})")
continue
if app_id in seen_ids:
print(f"Skipping duplicate: {game.get('name')} ({app_id})")
continue
seen_ids.add(app_id)
installed_games.append(game)
return installed_games
# ---------------------------------------------------------------------------
# Image helpers
# ---------------------------------------------------------------------------
# Thread lock for preloaded_images dict mutations coming from background threads
_image_lock = threading.Lock()
def create_placeholder_image(text: str) -> Image.Image:
img = Image.new("RGB", PLACEHOLDER_IMAGE_DIMENSIONS, color=(40, 40, 40))
draw = ImageDraw.Draw(img)
font = ImageFont.load_default()
bbox = draw.textbbox((0, 0), text, font=font)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
draw.text(
((img.width - tw) / 2, (img.height - th) / 2),
text, font=font, fill="white",
)
return img
def create_placeholder_icon(size: int = 20) -> Image.Image:
"""Generate a small square placeholder icon for games with no icon available.
Draws a dark rounded square with a faint '?' centred inside."""
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
margin = 1
draw.rounded_rectangle(
[margin, margin, size - margin - 1, size - margin - 1],
radius=3,
fill=(60, 60, 65, 220),
outline=(120, 120, 128, 180),
)
font = ImageFont.load_default()
text = "?"
bbox = draw.textbbox((0, 0), text, font=font)
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
draw.text(
((size - tw) / 2, (size - th) / 2 - 1),
text, font=font, fill=(180, 180, 185, 255),
)
return img
def fetch_header_image(app_id: str, cache_dir: str, timeout: int = 10,
game_name: str = "") -> Image.Image:
"""Fetch game header image from disk cache or Steam CDN."""
label = f"{game_name} ({app_id})" if game_name else app_id
cache_file = os.path.join(cache_dir, f"{app_id}.jpg")
if os.path.exists(cache_file):
try:
img = Image.open(cache_file)
img.load()
return img
except Exception as e:
print(f"[Image] Corrupt cache for {label} — deleting and re-fetching. ({e})")
try:
os.remove(cache_file)
except OSError:
pass
urls = [
f"https://cdn.cloudflare.steamstatic.com/steam/apps/{app_id}/header.jpg",
f"https://cdn.akamai.steamstatic.com/steam/apps/{app_id}/header.jpg",
f"https://cdn.cloudflare.steamstatic.com/steam/apps/{app_id}/capsule_616x353.jpg",
f"https://cdn.cloudflare.steamstatic.com/steam/apps/{app_id}/page_bg.jpg",
]
for url in urls:
try:
resp = _session.get(url, timeout=timeout)
if resp.status_code == 200 and len(resp.content) > 1024:
img = Image.open(BytesIO(resp.content))
img.load()
img.save(cache_file, "JPEG")
print(f"[Image] Downloaded: {label}")
return img
elif resp.status_code != 200:
print(f"[Image] HTTP {resp.status_code} for {label} — {url}")
except Exception as e:
print(f"[Image] Error fetching {label} from {url}: {e}")
print(f"[Image] All URLs failed for {label} — using placeholder.")
return create_placeholder_image("Image Unavailable")
def fetch_game_icon(app_id: str, icon_hash: str, cache_dir: str,
size: int = 20, timeout: int = 6,
game_name: str = "") -> "Image.Image | None":
"""Fetch a small icon for a game as a PIL Image, scaled to size px.
Returns a PIL Image (not PhotoImage) so it can be used from background threads.
Caller must convert to PhotoImage on the main thread.
Always cached as PNG to support RGBA icons."""
if not app_id:
return None
label = f"{game_name} ({app_id})" if game_name else app_id
cache_file = os.path.join(cache_dir, f"icon_{app_id}.png")
# Migrate legacy .jpg cache
legacy_cache = os.path.join(cache_dir, f"icon_{app_id}.jpg")
if os.path.exists(legacy_cache) and not os.path.exists(cache_file):
try:
img = Image.open(legacy_cache).convert("RGBA")
img.load()
img.save(cache_file, "PNG")
os.remove(legacy_cache)
print(f"[Icon] Migrated legacy .jpg cache for {label}")
except Exception as e:
print(f"[Icon] Failed to migrate legacy cache for {label}: {e}")
if os.path.exists(cache_file):
try:
img = Image.open(cache_file).convert("RGBA")
img.load()
return img.resize((size, size), Image.Resampling.LANCZOS)
except Exception as e:
print(f"[Icon] Corrupt cache for {label} — deleting and re-fetching. ({e})")
try:
os.remove(cache_file)
except OSError:
pass
urls = [
f"https://cdn.cloudflare.steamstatic.com/steam/apps/{app_id}/capsule_sm_120.jpg",
f"https://cdn.akamai.steamstatic.com/steam/apps/{app_id}/capsule_sm_120.jpg",
]
if icon_hash:
base = (f"https://media.steampowered.com/steamcommunity/public"
f"/images/apps/{app_id}/{icon_hash}")
urls += [base, f"{base}.jpg", f"{base}.png"]
tried = []
for url in urls:
try:
resp = _session.get(url, timeout=timeout)
if resp.status_code == 200 and len(resp.content) > 64:
img = Image.open(BytesIO(resp.content)).convert("RGBA")
img.load()
img.save(cache_file, "PNG")
print(f"[Icon] Downloaded: {label}")
return img.resize((size, size), Image.Resampling.LANCZOS)
elif resp.status_code == 404:
tried.append(os.path.basename(url.split("?")[0]))
else:
print(f"[Icon] HTTP {resp.status_code} for {label} — {url}")
except Exception as e:
print(f"[Icon] Error fetching {label} from {url}: {e}")
if tried:
print(f"[Icon] No icon found for {label} "
f"(404 on: {', '.join(tried)}) — using placeholder.")
else:
print(f"[Icon] All URLs failed for {label} — using placeholder.")
return create_placeholder_icon(size)
# ---------------------------------------------------------------------------
# Steam Web API helpers
# ---------------------------------------------------------------------------
def get_all_games(api_key: str, steam_id: str) -> list:
"""Fetch all games owned by the user via the Steam API."""
url = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v1/"
params = {
"key": api_key,
"steamid": steam_id,
"include_appinfo": True,
"include_played_free_games": True,
}
try:
resp = _session.get(url, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
if "response" in data and "games" in data["response"]:
games = data["response"]["games"]
print(f"Fetched {len(games)} games from Steam API.")
return games
print("No games found in Steam API response.")
return []
except Exception as e:
print(f"Error fetching games from Steam API: {e}")
return []
def get_uninstalled_games_from_api(api_key: str, steam_id: str, installed_games: list) -> list:
all_games = get_all_games(api_key, steam_id)
if not all_games:
return []
installed_ids = {str(g["app_id"]) for g in installed_games}
return [
{"app_id": str(g["appid"]), "name": g["name"]}
for g in all_games
if str(g["appid"]) not in installed_ids
]
# ---------------------------------------------------------------------------
# Drive enumeration
# ---------------------------------------------------------------------------
def get_drives() -> list:
if platform.system() == "Windows":
return [f"{chr(i)}:\\" for i in range(65, 91) if os.path.exists(f"{chr(i)}:\\")]
elif platform.system() == "Linux":
import subprocess
result = subprocess.run(["df", "-h", "--output=source"], capture_output=True, text=True)
return result.stdout.splitlines()[1:]
elif platform.system() == "Darwin":
import subprocess
result = subprocess.run(["mount"], capture_output=True, text=True)
return [line.split()[2] for line in result.stdout.splitlines()]
return []
# ---------------------------------------------------------------------------
# Shared requests session (reuses TCP connections across all API/image calls)
# ---------------------------------------------------------------------------
_session = requests.Session()
_session.headers.update({"User-Agent": "SteamRoulette/1.0"})
# ---------------------------------------------------------------------------
# Progress window
# ---------------------------------------------------------------------------
class ProgressWindow:
"""Modal progress window with a determinate or indeterminate bar and a status label."""
def __init__(self, parent: tk.Tk, title: str, total: int,
bg: str = "#ffffff", fg: str = "#000000"):
self.total = total
self._closed = False
self._indeterminate = (total == 0)
self.win = tk.Toplevel(parent)
self.win.title(title)
self.win.resizable(False, False)
self.win.grab_set()
self.win.protocol("WM_DELETE_WINDOW", lambda: None)
# Window icon
try:
if os.path.exists(ICON_PATH):
self.win.iconbitmap(ICON_PATH)
except Exception as e:
print(f"Error setting window icon: {e}")
self.win.configure(bg=bg)
ws = parent.winfo_screenwidth()
hs = parent.winfo_screenheight()
w, h = 380, 110
self.win.geometry(f"{w}x{h}+{ws//2 - w//2}+{hs//2 - h//2}")
self.label = tk.Label(self.win, text="", wraplength=360, justify="center",
font=("Arial", 9), bg=bg, fg=fg)
self.label.pack(pady=(14, 4), padx=10)
# Style the progressbar to match theme
style = ttk.Style(self.win)
style_name = f"pw{id(self)}.Horizontal.TProgressbar"
style.configure(style_name, troughcolor=bg, background="#4a90d9")
mode = "indeterminate" if self._indeterminate else "determinate"
self.bar = ttk.Progressbar(self.win, orient="horizontal",
length=340, mode=mode,
maximum=max(total, 1),
style=style_name)
self.bar.pack(pady=(0, 14), padx=20)
if self._indeterminate:
self.bar.start(12)
self.win.update_idletasks()
def set_text(self, text: str):
"""Update the status label (safe to call from any thread via root.after)."""
if not self._closed:
self.label.config(text=text)
self.win.update_idletasks()
def switch_to_determinate(self, total: int, text: str = ""):
"""Switch from indeterminate to determinate mode once total is known."""
if self._closed:
return
self.bar.stop()
self.total = max(total, 1)
self._indeterminate = False
self.bar.config(mode="determinate", maximum=self.total, value=0)
if text:
self.label.config(text=text)
self.win.update_idletasks()
def update(self, value: int, text: str = ""):
if self._closed:
return
self.bar["value"] = value
if text:
self.label.config(text=text)
self.win.update_idletasks()
def close(self):
if not self._closed:
self._closed = True
try:
self.bar.stop()
self.win.grab_release()
self.win.destroy()
except tk.TclError:
pass
# ---------------------------------------------------------------------------
# GUI
# ---------------------------------------------------------------------------
class LogWindow:
"""A scrolling log window that captures all stdout/stderr output.
Instantiated once and kept alive for the session. Calling open() shows it;
closing the window hides it rather than destroying it so the log is preserved.
sys.stdout and sys.stderr are redirected to this window as soon as it is created.
"""
def __init__(self, root: tk.Tk):
self.root = root
self._win = None
self._text = None
self._queue: queue.Queue = queue.Queue()
# Redirect stdout and stderr immediately
self._orig_stdout = sys.stdout
self._orig_stderr = sys.stderr
sys.stdout = self
sys.stderr = self
# Poll the queue every 100 ms from the main thread
self.root.after(100, self._flush)
# ------------------------------------------------------------------
# Stream interface (write / flush) so this object can act as stdout
# ------------------------------------------------------------------
def write(self, text: str):
self._orig_stdout.write(text) # keep VS Code / terminal output working
self._queue.put(text)
def flush(self):
self._orig_stdout.flush()
# ------------------------------------------------------------------
# Queue drainer — runs on main thread so Text widget is safe to touch
# ------------------------------------------------------------------
def _flush(self):
try:
while True:
text = self._queue.get_nowait()
if self._text:
self._text.configure(state="normal")
self._text.insert("end", text)
self._text.see("end")
self._text.configure(state="disabled")
except queue.Empty:
pass
self.root.after(100, self._flush)
# ------------------------------------------------------------------
# Window management
# ------------------------------------------------------------------
def open(self, bg: str = "#ffffff", fg: str = "#000000"):
if self._win and self._win.winfo_exists():
self._win.lift()
return
self._win = tk.Toplevel(self.root)
self._win.title("Log")
self._win.protocol("WM_DELETE_WINDOW", self._win.withdraw)
try:
if os.path.exists(ICON_PATH):
self._win.iconbitmap(ICON_PATH)
except Exception:
pass
ws = self.root.winfo_screenwidth()
hs = self.root.winfo_screenheight()
w, h = 700, 400
self._win.geometry(f"{w}x{h}+{ws//2 - w//2}+{hs//2 - h//2}")
self._win.configure(bg=bg)
# Toolbar
toolbar = tk.Frame(self._win, bg=bg)
toolbar.pack(fill="x", padx=6, pady=(6, 2))
tk.Button(toolbar, text="Clear", font=("Arial", 9), bg=bg, fg=fg,
command=self._clear).pack(side="left", padx=(0, 4))
tk.Button(toolbar, text="Copy All", font=("Arial", 9), bg=bg, fg=fg,
command=self._copy_all).pack(side="left")
# Scrolling text area
frame = tk.Frame(self._win, bg=bg)
frame.pack(fill="both", expand=True, padx=6, pady=(2, 6))
vsb = tk.Scrollbar(frame)
vsb.pack(side="right", fill="y")
self._text = tk.Text(
frame,
wrap="word",
state="disabled",
font=("Courier", 9),
bg="#1e1e1e" if bg == "#2e2e2e" else "#f5f5f5",
fg="#d4d4d4" if bg == "#2e2e2e" else "#1e1e1e",
insertbackground=fg,
yscrollcommand=vsb.set,
relief="flat",
)
self._text.pack(fill="both", expand=True)
vsb.configure(command=self._text.yview)
def apply_theme(self, bg: str, fg: str):
"""Call when the main window theme changes."""
if self._win and self._win.winfo_exists():
self._win.configure(bg=bg)
if self._text:
self._text.configure(
bg="#1e1e1e" if bg == "#2e2e2e" else "#f5f5f5",
fg="#d4d4d4" if bg == "#2e2e2e" else "#1e1e1e",
)
for w in self._win.winfo_children():
try:
w.configure(bg=bg, fg=fg)
except tk.TclError:
pass
def _clear(self):
if self._text:
self._text.configure(state="normal")
self._text.delete("1.0", "end")
self._text.configure(state="disabled")
def _copy_all(self):
if self._text:
self.root.clipboard_clear()
self.root.clipboard_append(self._text.get("1.0", "end"))
def restore(self):
"""Restore original stdout/stderr — call on app exit."""
sys.stdout = self._orig_stdout
sys.stderr = self._orig_stderr
class SteamRouletteGUI:
def __init__(self, root: tk.Tk, installed_games: list, drives: list):
self.root = root
self.installed_games = installed_games
self.excluded_games: list = []
self.uninstalled_games: list = []
self.selected_game: dict | None = None
self.drives = drives
self.cache_dir = create_cache_directory()
self.api_key: str = self._load_text_file("apikey.txt")
self.is_dark_mode: bool = False
self.selected_num_games: int | None = None
self.is_images_preloaded: bool = False
self.active_images: list = []
self.selected_game_image: Image.Image | None = None
self.selected_game_item = None
self.animation_id = None
self.preloaded_images: dict = {}
# Log window — created early so all subsequent print() calls are captured
self.log_window = LogWindow(self.root)
# Color schemes
self.light_mode_bg = "#ffffff"
self.dark_mode_bg = "#2e2e2e"
self.light_mode_fg = "#000000"
self.dark_mode_fg = "#ffffff"
# Animation state
self.initial_animation_speed = 50
self.animation_speed = 200
self.frame_delay = FRAME_DELAY_MS
self._build_ui()
self.load_exclusions()
# Pre-load installed-game images in the background; UI stays responsive
threading.Thread(target=self._preload_installed_images, daemon=True).start()
# Fetch icon hashes for installed games from the Steam API in the background
threading.Thread(target=self._fetch_icon_hashes, daemon=True).start()
# ------------------------------------------------------------------
# File I/O helpers
# ------------------------------------------------------------------
def _load_text_file(self, filename: str) -> str:
path = _data_path(filename)
if os.path.exists(path):
with open(path, "r") as fh:
return fh.read().strip()
return ""
def _save_text_file(self, filename: str, content: str) -> None:
with open(_data_path(filename), "w") as fh:
fh.write(content)
# ------------------------------------------------------------------
# UI construction
# ------------------------------------------------------------------
def _build_ui(self):
self.root.title("Steam Roulette")
width, height = 600, 750
ws = self.root.winfo_screenwidth()
hs = self.root.winfo_screenheight()
self.root.geometry(f"{width}x{height}+{int(ws/2 - width/2)}+{int(hs/2 - height/2)}")
self.root.resizable(False, False)
# Window icon
try:
if os.path.exists(ICON_PATH):
self.root.iconbitmap(ICON_PATH)
except Exception as e:
print(f"Error setting window icon: {e}")
bg = self.light_mode_bg
fg = self.light_mode_fg
# ── Top info bar ─────────────────────────────────────────────
self.copyright_notice = tk.Label(
self.root, text="© Streetbackguy 2024", font=("Arial", 8), bg=bg, fg=fg)
self.copyright_notice.place(x=2, y=58)
# ── Logo / title frame ───────────────────────────────────────
top_frame = tk.Frame(self.root, bg=bg)
# Push main content downward slightly
top_frame.pack(side="top", pady=(90, 0))
# Small logo positioned manually in top-left
try:
logo_path = resource_path("SteamRouletteLogo.png")
if not os.path.exists(logo_path):
raise FileNotFoundError(f"Logo not found: {logo_path}")
logo_img = Image.open(logo_path)
# Resize logo smaller
logo_img = logo_img.resize((120, 50), Image.LANCZOS)
logo_tk = ImageTk.PhotoImage(logo_img)
self.label_logoimage = tk.Label(
self.root,
image=logo_tk,
bg=bg
)
self.label_logoimage.image = logo_tk
except Exception as e:
print(e)
self.label_logoimage = tk.Label(
self.root,
text="Steam Roulette",
font=("Arial", 12),
bg=bg,
fg=fg
)
# Place logo in top-left
self.label_logoimage.place(x=5, y=5)
# Main title labels remain centered
self.label_welcome = tk.Label(
top_frame,
text="Welcome to Steam Roulette!",
font=("Arial", 16),
bg=bg,
fg=fg,
)
self.label_welcome.grid(row=0, pady=5)
self.label_game_name = tk.Label(
top_frame,
text="",
wraplength=420,
font=("Arial", 16),
bg=bg,
fg=fg,
padx=130, # pushes text right, clear of the logo in the top-left
)
self.label_game_name.grid(row=1, pady=(2, 0))
# ── Canvas (game art strip) ──────────────────────────────────
self.canvas = tk.Canvas(self.root, width=600, height=300, bg="black")
self.canvas.pack(pady=0)
self.root.update_idletasks()
self.display_random_header_image()
# ── Spin / launch / store buttons ────────────────────────────
utility_frame = tk.Frame(self.root, bg=bg)
utility_frame.pack(pady=5)
self.button_spin = tk.Button(utility_frame, text="Spin the Wheel",
command=self.spin_wheel, font=("Arial", 14), bg=bg, fg=fg)
self.button_spin.grid(row=0, column=0, pady=10, padx=10, columnspan=2)
self.button_launch = tk.Button(utility_frame, text="Launch/Install Game",
command=self.launch_game, state=tk.DISABLED,
font=("Arial", 10), bg=bg, fg=fg)
self.button_launch.grid(row=1, column=0, pady=5, padx=4)
self.button_store = tk.Button(utility_frame, text="Steam Storepage",
command=self.open_store, state=tk.DISABLED,
font=("Arial", 10), bg=bg, fg=fg)
self.button_store.grid(row=1, column=1, pady=5, padx=4)
# ── Controls: number of games / exclusions ───────────────────
self.frame_controls = tk.Frame(self.root, bg=bg)
self.frame_controls.place(anchor="w", x=4, y=610)
for col in range(3):
self.frame_controls.grid_columnconfigure(col, weight=1)
self.button_set_number_of_games = tk.Button(
self.frame_controls, text="Set Number of Games",
command=self.set_number_of_games, bg=bg, fg=fg)
self.button_set_number_of_games.grid(row=0, column=1, pady=2)
self.label_number_of_games = tk.Label(
self.frame_controls, text="Number of games to spin:\nAll Games",
font=("Arial", 8), bg=bg, fg=fg)
self.label_number_of_games.grid(row=1, column=1, pady=2)
self.button_exclude = tk.Button(
self.frame_controls, text="Exclude Games",
command=self.exclude_games, font=("Arial", 10), bg=bg, fg=fg)
self.button_exclude.grid(row=2, column=1, pady=2)
self.excluded_label = tk.Label(
self.frame_controls, text=f"Excluded Games:\n{len(self.excluded_games)}",
font=("Arial", 8), bg=bg, fg=fg)
self.excluded_label.grid(row=3, column=1, pady=2)
# ── Bottom-left: API key / user ID / theme ───────────────────
self.button_frame = tk.Frame(self.root, bg=bg)
self.button_frame.place(relx=0.0, rely=1.0, anchor="sw", x=2, y=-2)
tk.Button(self.button_frame, text="Set API Key",
command=self.set_api_key, font=("Arial", 10), bg=bg, fg=fg
).grid(row=0, column=0, pady=2, padx=2)
tk.Button(self.button_frame, text="Set Steam User ID",
command=self.set_user_id_key, font=("Arial", 10), bg=bg, fg=fg
).grid(row=0, column=1, pady=2, padx=2)
tk.Button(self.button_frame, text="Toggle Dark Mode",
command=self.toggle_theme, font=("Arial", 10), bg=bg, fg=fg
).grid(row=0, column=2, pady=2, padx=2)
tk.Button(self.button_frame, text="Clear Image Cache",
command=self.clear_image_cache, font=("Arial", 10), bg=bg, fg=fg
).grid(row=1, column=0, columnspan=2, pady=2, padx=2, sticky="ew")
tk.Button(self.button_frame, text="Log Window",
command=self.open_log_window, font=("Arial", 10), bg=bg, fg=fg
).grid(row=1, column=2, pady=2, padx=2, sticky="ew")
# ── Bottom-right: checkboxes + status ────────────────────────
self.yes_no_frame = tk.Frame(self.root, bg=bg)
self.yes_no_frame.place(relx=1.0, rely=1.0, anchor="se", x=-2, y=-2)
self.please_wait_label = tk.Label(self.yes_no_frame, text="", font=("Arial", 8),
bg=bg, fg=fg, wraplength=180, justify="right")
self.please_wait_label.grid(row=0)
self.label_game_count = tk.Label(
self.yes_no_frame, text=self._games_found_text(),
font=("Arial", 8), bg=bg, fg=fg, justify="right")
self.label_game_count.grid(row=1, sticky="e", pady=(0, 4))
self.include_uninstalled_var = tk.BooleanVar(value=False)
self.include_uninstalled_checkbox = tk.Checkbutton(
self.yes_no_frame, text="Include Uninstalled Games",
variable=self.include_uninstalled_var, command=self.toggle_uninstalled_games,
bg=bg, fg=fg, selectcolor=bg)
self.include_uninstalled_checkbox.grid(sticky="w", row=2)
self.filter_achievements_var = tk.BooleanVar(value=False)
self.filter_achievements_checkbox = tk.Checkbutton(
self.yes_no_frame, text="Exclude 100% Achieved Games",
variable=self.filter_achievements_var, command=self.toggle_achievement_filter,
bg=bg, fg=fg, selectcolor=bg)
self.filter_achievements_checkbox.grid(sticky="w", row=3)
self.set_light_mode()
# ------------------------------------------------------------------
# Image pre-loading
# ------------------------------------------------------------------
def _fetch_icon_hashes(self):
"""Silently fetch img_icon_url for installed games from the Steam API
and merge them into self.installed_games so the Exclude popup can show icons
even when uninstalled games haven't been loaded."""
api_key = self.api_key
user_id = self._load_text_file("steamuserid.txt")
if not api_key or not user_id:
return # not configured yet — skip silently
try:
all_games = get_all_games(api_key, user_id)
except Exception as e:
print(f"Could not fetch icon hashes: {e}")
return
if not all_games:
return
# Build a lookup: appid (str) → img_icon_url
hash_map = {
str(g["appid"]): g.get("img_icon_url", "")
for g in all_games
if "appid" in g and g.get("img_icon_url")
}
# Merge into installed_games in-place (thread-safe: only writing new keys)
for game in self.installed_games:
app_id = str(game["app_id"])
if app_id in hash_map and not game.get("img_icon_url"):
game["img_icon_url"] = hash_map[app_id]
print(f"Icon hashes merged for {len(hash_map)} games.")
def _preload_installed_images(self):
"""Background worker: fetch header images for all installed games."""
def _load(game):
app_id = game.get("app_id")
if not app_id:
return
with _image_lock:
already = app_id in self.preloaded_images
if already:
return
img = fetch_header_image(app_id, self.cache_dir,
game_name=game.get("name", ""))
with _image_lock:
self.preloaded_images[app_id] = img
with ThreadPoolExecutor(max_workers=PRELOAD_WORKERS) as ex:
ex.map(_load, self.installed_games)
self.root.after(0, self._on_installed_images_ready)
def _on_installed_images_ready(self):
self.is_images_preloaded = True
print("Installed-game images pre-loaded.")
def load_images_in_parallel(self, pw: "ProgressWindow | None" = None):
"""Download header images for uninstalled games, skipping any already cached."""
all_games = list(self.uninstalled_games)
# Filter to only games whose image isn't already on disk
def _is_cached(game) -> bool:
cache_file = os.path.join(self.cache_dir, f"{game['app_id']}.jpg")
return os.path.exists(cache_file)
games_to_fetch = [g for g in all_games if not _is_cached(g)]
already_cached = len(all_games) - len(games_to_fetch)
total = len(games_to_fetch)
print(f"Image download: {already_cached} already cached, "
f"{total} to fetch.")
# If no window was passed in, create a fresh one
if pw is None:
pw_holder = [None]
def _open_pw():
pw_holder[0] = ProgressWindow(
self.root, "Downloading Images", max(total, 1))
self.root.after(0, _open_pw)
import time as _time; _time.sleep(0.05)
else:
if total > 0:
self.root.after(0, lambda: pw.switch_to_determinate(
total, f"Downloading images… 0 of {total}"))
pw_holder = [pw]
if total == 0:
# Nothing to download — close the progress window and finish
def _nothing_to_do():
if pw_holder[0]:
pw_holder[0].close()
self.on_images_preloaded()
self.root.after(0, _nothing_to_do)
return
completed = 0
lock = threading.Lock()
def _load_one(game):
nonlocal completed
fetch_header_image(game["app_id"], self.cache_dir,
game_name=game.get("name", ""))
with lock:
completed += 1
c = completed
def _upd(c=c):
self.please_wait_label.config(text=f"Downloading… {c}/{total}")
if pw_holder[0]:
pw_holder[0].update(c, f"Downloading images… {c} of {total}")
self.root.after(0, _upd)
with ThreadPoolExecutor(max_workers=PRELOAD_WORKERS) as ex:
ex.map(_load_one, games_to_fetch)
def _finish():
if pw_holder[0]:
pw_holder[0].close()
self.on_images_preloaded()
self.root.after(0, _finish)
def on_images_preloaded(self):
self.is_images_preloaded = True
self.button_spin.config(state=tk.NORMAL, text="Spin the Wheel")
self.include_uninstalled_checkbox.config(state=tk.NORMAL)
self.filter_achievements_checkbox.config(state=tk.NORMAL)
self.please_wait_label.config(text="")
print("Uninstalled-game images loaded and cached.")
# ------------------------------------------------------------------
# Text helpers
# ------------------------------------------------------------------
def _games_found_text(self) -> str:
lines = ["Installed\nGames Found:"]