-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsgm.py
More file actions
executable file
·3610 lines (3069 loc) · 139 KB
/
Copy pathsgm.py
File metadata and controls
executable file
·3610 lines (3069 loc) · 139 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
"""SteamGrid Manager (sgm) - Protect your custom Steam library artwork.
CLI tool that backs up, restores, and refreshes custom game images
on SteamOS/Linux. Prevents loss of artwork after Steam client updates.
"""
import argparse
import logging
import sys
from pathlib import Path
from typing import Optional
__version__ = '1.0.0'
def setup_logging(level: str = 'info', log_file: str = None) -> None:
"""Configure logging for the application."""
numeric_level = getattr(logging, level.upper(), logging.INFO)
handlers = [logging.StreamHandler(sys.stderr)]
if log_file:
log_path = Path(log_file)
log_path.parent.mkdir(parents=True, exist_ok=True)
handlers.append(logging.FileHandler(log_file, encoding='utf-8'))
logging.basicConfig(
level=numeric_level,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=handlers,
)
def notify_steam_reload() -> None:
"""Tell a running Steam client to reload shortcuts, or print a hint if not running."""
from steam import is_steam_running, reload_steam_shortcuts
if is_steam_running():
if reload_steam_shortcuts():
print("\nSteam is running — shortcuts reloaded. Your games should appear shortly.\n")
else:
print("\nDone! Restart Steam to see your games in the library.\n")
else:
print("\nDone! Start Steam to see your games in the library.\n")
def cmd_status(args: argparse.Namespace) -> int:
"""Show current status of grid images and backups."""
from config import config_exists, load_config, get_resolved_config
from steam import find_steam_path, find_grid_path, get_grid_stats, format_size
from backup import list_backups
print(f"\n SteamGrid Manager (sgm) v{__version__}\n")
# Load config or auto-detect
try:
if config_exists():
config = get_resolved_config()
else:
steam_path = find_steam_path()
config = {
'steam_path': str(steam_path),
'steam_user_id': 'auto',
'api_key': '',
}
except FileNotFoundError as e:
print(f" Error: {e}")
return 1
steam_path = Path(config['steam_path'])
user_id = config.get('steam_user_id', 'auto')
print(f" Steam User: {user_id}")
# Find grid path
try:
grid_path = find_grid_path(steam_path, user_id if user_id != 'auto' else None)
print(f" Grid Path: {grid_path}\n")
except FileNotFoundError as e:
print(f" Grid Path: NOT FOUND ({e})\n")
return 1
# Grid stats
stats = get_grid_stats(grid_path)
print(f" Current Grid Images:")
print(f" Tall capsules: {stats['by_type']['tall']:>5}")
print(f" Wide capsules: {stats['by_type']['wide']:>5}")
print(f" Hero banners: {stats['by_type']['hero']:>5}")
print(f" Logos: {stats['by_type']['logo']:>5}")
print(f" Icons: {stats['by_type']['icon']:>5}")
if stats['by_type']['other']:
print(f" Other: {stats['by_type']['other']:>5}")
print(f" Symlinks: {stats['symlinks']:>5}")
print(f" Total: {stats['total_files']:>5} ({format_size(stats['total_size'])})")
print(f" Unique App IDs: {len(stats['unique_app_ids']):>5}")
# Backup info
print()
try:
backup_path = Path(config.get('backup_path', str(Path.home() / '.local' / 'share' / 'sgm' / 'backups')))
backups = list_backups(backup_path)
if backups:
latest = backups[0]
print(f" Backups:")
print(f" Latest: {latest['timestamp']} ({latest['file_count']:} files, {format_size(latest['total_size'])})")
print(f" Total: {len(backups)} backup(s)")
else:
print(f" Backups: None (run 'sgm backup' to create one)")
except Exception:
print(f" Backups: None (run 'sgm backup' to create one)")
# SRM cache
from steam import find_srm_artwork_cache
srm_cache = find_srm_artwork_cache()
if srm_cache:
try:
import json
with open(srm_cache, 'r') as f:
cache_data = json.load(f)
art = cache_data.get('sgdbToArt', {})
total_mappings = sum(len(v) for v in art.values())
print(f" SRM Cache: Found ({total_mappings:} mappings)")
except Exception:
print(f" SRM Cache: Found (could not read)")
else:
print(f" SRM Cache: Not found")
# API key
api_key = config.get('api_key', '')
api_status = "Configured" if api_key else "Not set (run 'sgm config init')"
print(f" API Key: {api_status}")
# Art cache stats
try:
from art_scraper import DEFAULT_CACHE_DIR
cache_dir = Path(config.get('art_cache_dir', '') or DEFAULT_CACHE_DIR).expanduser()
if cache_dir.exists():
cache_files = list(cache_dir.glob('*.json'))
print(f" Art Cache: {len(cache_files)} game(s) cached")
else:
print(f" Art Cache: Empty (populated during rom art scrape)")
except Exception:
pass
# Auto-monitor
from monitor import is_monitor_installed
monitor_status = "Active" if is_monitor_installed() else "Not installed"
print(f" Monitor: {monitor_status}")
print()
return 0
def cmd_backup(args: argparse.Namespace) -> int:
"""Create a backup of the grid folder."""
from config import config_exists, get_resolved_config
from steam import find_steam_path, find_grid_path
from backup import create_backup
try:
if config_exists():
config = get_resolved_config()
else:
steam_path = find_steam_path()
config = {
'steam_path': str(steam_path),
'steam_user_id': 'auto',
'backup_path': str(Path.home() / '.local' / 'share' / 'sgm' / 'backups'),
}
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
steam_path = Path(config['steam_path'])
user_id = config.get('steam_user_id', 'auto')
backup_path = Path(config.get('backup_path', str(Path.home() / '.local' / 'share' / 'sgm' / 'backups')))
try:
grid_path = find_grid_path(steam_path, user_id if user_id != 'auto' else None)
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
return create_backup(grid_path, backup_path, dry_run=args.dry_run)
def _rebuild_collections_after_restore(steam_path: Path, grid_path: Path, user_id: str) -> None:
"""Rebuild Steam collections from the restored shortcuts.vdf tags.
After a restore, the grid images and shortcuts.vdf are back, but
Steam's collection data in cloud storage may still be wiped. This
reads the shortcut tags and recreates the collections.
"""
from shortcuts import read_shortcuts_vdf, update_steam_collections
vdf_path = grid_path.parent / 'shortcuts.vdf'
if not vdf_path.exists():
return
try:
shortcuts = read_shortcuts_vdf(vdf_path)
except Exception as e:
logging.warning(f"Could not read shortcuts.vdf for collection rebuild: {e}")
return
if not shortcuts:
return
# Group by first tag (= category)
by_category: dict[str, list[int]] = {}
for sc in shortcuts:
tag = list(sc.tags.values())[0] if sc.tags else None
if tag:
by_category.setdefault(tag, []).append(sc.appid & 0xFFFFFFFF)
if not by_category:
return
uid = user_id if user_id != 'auto' else None
ok = update_steam_collections(steam_path, by_category, uid)
if ok:
total = sum(len(v) for v in by_category.values())
print(f" Collections: rebuilt {len(by_category)} collections ({total} memberships)")
else:
print(f" Collections: [WARN] failed to rebuild collections")
def cmd_restore(args: argparse.Namespace) -> int:
"""Restore grid images from a backup."""
from config import config_exists, get_resolved_config
from steam import find_steam_path, find_grid_path
from backup import restore_backup, list_backups
try:
if config_exists():
config = get_resolved_config()
else:
steam_path = find_steam_path()
config = {
'steam_path': str(steam_path),
'steam_user_id': 'auto',
'backup_path': str(Path.home() / '.local' / 'share' / 'sgm' / 'backups'),
}
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
backup_path = Path(config.get('backup_path', str(Path.home() / '.local' / 'share' / 'sgm' / 'backups')))
# List mode
if args.list:
backups = list_backups(backup_path)
if not backups:
print("No backups found.")
return 0
print(f"\nAvailable backups:\n")
for b in backups:
from steam import format_size
print(f" {b['timestamp']} ({b['file_count']:} files, {format_size(b['total_size'])})")
print()
return 0
steam_path = Path(config['steam_path'])
user_id = config.get('steam_user_id', 'auto')
try:
grid_path = find_grid_path(steam_path, user_id if user_id != 'auto' else None)
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
result = restore_backup(
grid_path, backup_path,
timestamp=args.timestamp,
dry_run=args.dry_run,
force=args.force,
)
if result == 0 and not args.dry_run:
# Rebuild Steam collections from the restored shortcuts.vdf tags
_rebuild_collections_after_restore(steam_path, grid_path, user_id)
notify_steam_reload()
return result
def _cmd_refresh_shortcuts(
config: dict,
steam_path: Path,
grid_path: Path,
image_type: Optional[str],
dry_run: bool,
) -> int:
"""Scrape SteamGridDB art for non-ROM shortcuts that are missing images.
Covers Heroic games, flatpak apps, Wine/exe games — anything not tagged
with a known ROM system category.
"""
from shortcuts import read_shortcuts_vdf, generate_short_app_id
from art_scraper import CascadeScraper, save_grid_images, ART_TYPES
# Known ROM system tags — shortcuts with any of these are skipped
ROM_TAGS = {
'Atari 2600', 'Master System', 'VIC-20', 'Game Gear',
'Nintendo Entertainment System', 'Super Nintendo', 'ColecoVision',
'Arcade', 'Genesis', 'Atari 5200', 'Atari Lynx', 'Commodore 64',
'Atari 7800', 'Game Boy Advance', 'Infocom / Z-Machine', 'Z-Machine',
'Amiga', 'Game Boy', 'Intellivision', 'GameCube', 'PlayStation Portable',
'Wii U', 'Game Boy Color', 'Dreamcast', 'PlayStation 2', 'Nintendo DS',
'Xbox', 'DOS', 'Neo Geo', 'PlayStation', 'Wii', 'Nintendo 64',
'Sega Saturn', 'SNES', 'NES', 'PC Engine', 'TurboGrafx-16',
}
# Find shortcuts.vdf
user_id = config.get('steam_user_id', 'auto')
uid = user_id if user_id != 'auto' else None
vdf_path = grid_path.parent / 'shortcuts.vdf'
if not vdf_path.exists():
print("No shortcuts.vdf found.")
return 1
shortcuts = read_shortcuts_vdf(vdf_path)
# Filter to non-ROM shortcuts
non_rom = [
sc for sc in shortcuts
if not any(str(v) in ROM_TAGS for v in sc.tags.values())
]
# Determine which art types to look for
wanted_types: set[str]
if image_type:
wanted_types = {image_type}
else:
wanted_types = set(ART_TYPES)
# Collect suffix map for existence checks
suffix_map = {
'tall': 'p', 'wide': '', 'hero': '_hero', 'logo': '_logo', 'icon': '_icon'
}
suffix_map_filtered = {k: v for k, v in suffix_map.items() if k in wanted_types}
# Find which non-ROM shortcuts are missing art.
# Use the appid already stored in shortcuts.vdf (as unsigned 32-bit) for the
# grid filename prefix — this matches whatever ID SRM/Steam already assigned,
# regardless of how generate_short_app_id() would compute it.
def grid_id_for(sc) -> str:
"""Return the grid filename prefix for an existing shortcut."""
if sc.appid:
# appid is stored as signed 32-bit in VDF; convert to unsigned
return str(sc.appid & 0xFFFFFFFF)
return generate_short_app_id(sc.exe, sc.appname)
to_scrape = []
for sc in non_rom:
grid_id = grid_id_for(sc)
missing_types = set()
for art_type, suffix in suffix_map_filtered.items():
has = any(
(grid_path / f"{grid_id}{suffix}{ext}").exists()
for ext in ('.png', '.jpg')
)
if not has:
missing_types.add(art_type)
if missing_types:
to_scrape.append((sc, grid_id, missing_types))
if not to_scrape:
print("All non-ROM shortcuts already have artwork.")
return 0
print(f"\n Refresh Shortcut Art\n")
print(f" Shortcuts to scrape: {len(to_scrape)}")
if dry_run:
print()
for sc, short_id, missing in sorted(to_scrape, key=lambda x: x[0].appname):
print(f" [WOULD SCRAPE] {sc.appname} (missing: {', '.join(sorted(missing))})")
print(f"\n (dry run — no changes made)\n")
return 0
# Initialize scraper
try:
scraper = CascadeScraper(config)
except Exception as e:
print(f"Error initializing art scraper: {e}")
return 1
total_downloaded = 0
total_failed = 0
total_skipped = 0
print()
for sc, short_id, missing_types in sorted(to_scrape, key=lambda x: x[0].appname):
print(f" {sc.appname}", end='', flush=True)
try:
artwork = scraper.scrape_game(sc.appname, wanted_types=missing_types)
if artwork:
saved = save_grid_images(short_id, artwork, grid_path)
total_downloaded += len(saved)
missing_after = missing_types - set(saved.keys())
if missing_after:
total_failed += len(missing_after)
print(f" [{len(saved)} saved, {len(missing_after)} not found]")
else:
print(f" [{len(saved)} saved]")
else:
total_skipped += 1
print(" [no match]")
except Exception as e:
total_failed += 1
logging.debug(f"Scrape failed for {sc.appname}: {e}")
print(f" [error: {e}]")
print()
print(f" Results:")
print(f" Downloaded: {total_downloaded}")
print(f" Not found: {total_skipped}")
if total_failed:
print(f" Failed: {total_failed}")
print()
return 0
def cmd_refresh(args: argparse.Namespace) -> int:
"""Refresh / re-scrape artwork for all game types.
Covers all three populations in one pass unless filtered:
1. SRM-managed games (artworkCache.json entries -> SteamGridDB)
2. Non-ROM shortcuts (Heroic, Wine, flatpaks -> full cascade)
3. ROM shortcuts (SGM-imported ROMs -> full cascade)
Filters: --srm-only, --shortcuts-only, --roms-only, --system X, --game NAME
Scope: --all re-downloads even existing art; default = missing only
"""
from config import config_exists, get_resolved_config
from steam import find_steam_path, find_grid_path
from refresh import refresh_images
try:
if config_exists():
config = get_resolved_config()
else:
print("Error: Config required for refresh. Run 'sgm config init' first.")
return 1
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
if not config.get('api_key'):
print("Error: SteamGridDB API key required for refresh.")
print("Run 'sgm config set api_key YOUR_KEY' or 'sgm config init'")
print("Get a free key at: https://www.steamgriddb.com/profile/preferences/api")
return 1
steam_path = Path(config['steam_path'])
user_id = config.get('steam_user_id', 'auto')
try:
grid_path = find_grid_path(steam_path, user_id if user_id != 'auto' else None)
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
force_all = getattr(args, 'all', False)
mode = 'all' if force_all else 'missing'
image_type = getattr(args, 'type', None)
system_filter = getattr(args, 'system', None)
game_filter = getattr(args, 'game', None)
srm_only = getattr(args, 'srm_only', False)
shortcuts_only = getattr(args, 'shortcuts_only', False)
roms_only = getattr(args, 'roms_only', False)
dry_run = args.dry_run
# Determine which populations to process
# --system or --game implies ROM scope; --shortcuts-only or --srm-only narrow further
do_srm = not shortcuts_only and not roms_only
do_shortcuts = not srm_only and not roms_only and not system_filter and not game_filter
do_roms = not srm_only and not shortcuts_only
if system_filter or game_filter or roms_only:
do_srm = False
do_shortcuts = False
overall_rc = 0
# ── Population 1: SRM artworkCache entries ──────────────────
if do_srm:
print(f"\n ── SRM-managed art (artworkCache.json) ──")
rc = refresh_images(
grid_path=grid_path,
api_key=config['api_key'],
srm_cache_path=config.get('srm_artwork_cache', ''),
mode=mode,
image_type=image_type,
batch_size=config.get('batch_size', 50),
dry_run=dry_run,
)
if rc != 0:
overall_rc = rc
# ── Population 2: Non-ROM shortcuts (Heroic, Wine, flatpaks) ─
if do_shortcuts:
print(f"\n ── Non-ROM shortcuts (Heroic / other) ──")
rc = _cmd_refresh_shortcuts(
config=config,
steam_path=steam_path,
grid_path=grid_path,
image_type=image_type,
dry_run=dry_run,
)
if rc != 0:
overall_rc = rc
# ── Population 3: ROM shortcuts ──────────────────────────────
if do_roms:
# Reuse the ROM art scrape logic by synthesising a compatible args object
class _RomArgs:
pass
rom_args = _RomArgs()
rom_args.system = system_filter
rom_args.game = game_filter
rom_args.all = force_all
rom_args.dry_run = dry_run
if not (system_filter or game_filter):
print(f"\n ── ROM shortcuts ──")
rc = _cmd_rom_art_scrape(rom_args)
if rc != 0:
overall_rc = rc
return overall_rc
def cmd_config(args: argparse.Namespace) -> int:
"""Manage configuration."""
from config import interactive_setup, show_config, set_config_value
sub = args.config_action
if sub == 'init':
interactive_setup()
return 0
elif sub == 'show':
show_config()
return 0
elif sub == 'set':
if not args.key or not args.value:
print("Usage: sgm config set <key> <value>")
return 1
set_config_value(args.key, args.value)
return 0
else:
# Default: show config
show_config()
return 0
def cmd_emulators_list(args: argparse.Namespace) -> int:
"""List and manage emulator configurations."""
from emulators import (get_registry, list_all_emulators, get_emulators_for_system,
emulators_config_exists, create_emulator_from_id)
from systems import SYSTEMS, get_system
sub = getattr(args, 'emulators_action', None)
if sub == 'add':
# Handled by cmd_emulators_add
return cmd_emulators_add(args)
# List all emulators
print("\n Emulators\n")
emulators = list_all_emulators()
if not emulators:
print(" No emulators configured.")
else:
for em in sorted(emulators, key=lambda x: x['id']):
available = em.get('available', False)
status = "[OK] " if available else "[--] "
print(f" {status}{em['id']}")
if em.get('description'):
print(f" {em['description']}")
# List systems with their default emulators
print("\n Systems\n")
for sys_name in sorted(SYSTEMS.keys()):
sys_def = get_system(sys_name)
if not sys_def:
continue
default_id = sys_def.default_emulator_id or "none"
print(f" {sys_name}: {sys_def.fullname} -> {default_id}")
return 0
def cmd_emulators_add(args: argparse.Namespace) -> int:
"""Add a custom emulator configuration."""
from emulators import get_registry, EMULATORS_CONFIG
import json
emulator_id = args.emulator_id
config = {
"display_name": args.name or emulator_id,
"executable": args.executable or "",
"flatpak_id": args.flatpak_id or "",
"launch_args": args.args,
}
registry = get_registry()
registry.add_custom_emulator(emulator_id, config)
# Associate with systems if specified
if args.system:
for system in args.system:
system_config = {
"default": emulator_id,
"emulators": {
emulator_id: config
}
}
registry._system_configs[system] = system_config
registry.save_config()
print(f"Added emulator '{emulator_id}' to {EMULATORS_CONFIG}")
return 0
def cmd_monitor(args: argparse.Namespace) -> int:
"""Manage the auto-detection monitor."""
from monitor import install_monitor, uninstall_monitor, monitor_status, run_monitor_check
sub = args.monitor_action
if sub == 'install':
return install_monitor()
elif sub == 'uninstall':
return uninstall_monitor()
elif sub == 'status':
return monitor_status()
elif sub == 'run':
return run_monitor_check()
else:
return monitor_status()
def cmd_rom_art(args: argparse.Namespace) -> int:
"""Handle `sgm rom art` subcommands."""
art_action = getattr(args, 'rom_art_action', None)
if art_action == 'remap':
return _cmd_rom_art_remap(args)
if art_action == 'fix-mount':
return _cmd_rom_art_fix_mount(args)
if art_action == 'clear':
return _cmd_rom_art_clear(args)
if art_action == 'scrape':
return _cmd_rom_art_scrape(args)
print("Usage: sgm rom art <clear|scrape|remap|fix-mount> [options]")
return 1
def _extract_rom_path_from_exe(exe: str) -> Optional[Path]:
"""Extract the ROM file path from a RetroArch/emulator shortcut exe string.
RetroArch shortcuts generated by SGM take the form:
"/usr/bin/flatpak" run org.libretro.RetroArch -L /core.so "/path/to/rom.ext"
Strategy: find the last quoted token that looks like a ROM file path (has
an extension, contains a path separator, and is not a .so/.dll library).
Args:
exe: The exe field from a SteamShortcut.
Returns:
Path to the ROM file if detected, None otherwise.
"""
import re as _re
import shlex as _shlex
_lib_exts = {'.so', '.dll', '.dylib', ''}
# Pass 1: last quoted token
for candidate in reversed(_re.findall(r'"([^"]+)"', exe)):
p = Path(candidate)
if p.suffix.lower() not in _lib_exts and '/' in candidate:
return p
# Pass 2: last unquoted token that looks like a file path
try:
for token in reversed(_shlex.split(exe)):
p = Path(token)
if p.suffix.lower() not in _lib_exts and '/' in token:
return p
except Exception:
pass
return None
def _cmd_rom_art_scrape(args: argparse.Namespace) -> int:
"""Scrape missing (or all) artwork for ROM shortcuts by system or game name.
This is the go-to command when 'rom import' missed art for some games.
It re-runs the cascade scraper only for games that are missing images.
"""
from config import config_exists, get_resolved_config
from steam import find_steam_path, find_grid_path
from shortcuts import get_existing_shortcuts, generate_short_app_id
from systems import get_system
from art_scraper import (
CascadeScraper, save_grid_images, ART_TYPES,
store_art_in_cache, DEFAULT_CACHE_DIR,
)
try:
if config_exists():
config = get_resolved_config()
steam_path = Path(config['steam_path'])
user_id = config.get('steam_user_id', 'auto')
else:
steam_path = find_steam_path()
config = {'steam_path': str(steam_path), 'steam_user_id': 'auto'}
user_id = 'auto'
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
if not config.get('api_key'):
print("Error: No SteamGridDB API key configured.")
print("Run: sgm config set api_key YOUR_KEY")
return 1
uid = user_id if user_id != 'auto' else None
try:
grid_path = find_grid_path(steam_path, uid)
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
system_filter = getattr(args, 'system', None)
game_filter = (getattr(args, 'game', None) or '').lower()
force_all = getattr(args, 'all', False)
# Load all shortcuts, filter by system tag
all_shortcuts = get_existing_shortcuts(steam_path, uid)
if system_filter:
sys_def = get_system(system_filter)
if not sys_def:
print(f"Error: Unknown system '{system_filter}'.")
print("Run 'sgm rom systems' to see supported system names.")
return 1
all_tags = sys_def.all_category_tags()
shortcuts = [
sc for sc in all_shortcuts
if any(str(v) in all_tags for v in sc.tags.values())
]
sys_info = {system_filter: sys_def}
else:
# All ROM shortcuts (any known system tag)
from systems import SYSTEMS
all_rom_tags: set[str] = set()
sys_info: dict = {}
for sname, sdef in SYSTEMS.items():
all_rom_tags.update(sdef.all_category_tags())
sys_info[sname] = sdef
shortcuts = [
sc for sc in all_shortcuts
if any(str(v) in all_rom_tags for v in sc.tags.values())
]
# Filter by game name if specified
if game_filter:
shortcuts = [sc for sc in shortcuts if game_filter in sc.appname.lower()]
if not shortcuts:
print(f"\nNo matching ROM shortcuts found.\n")
return 0
# Build work list — check which art is missing unless --all
_art_suffixes = {
'tall': ('p.png', 'p.jpg'),
'wide': ('.png', '.jpg'),
'hero': ('_hero.png', '_hero.jpg'),
'logo': ('_logo.png', '_logo.jpg'),
'icon': ('_icon.png', '_icon.jpg'),
}
work_list = [] # list of (shortcut, short_id, missing_types, sys_def)
for sc in shortcuts:
short_id = str(sc.appid & 0xFFFFFFFF)
if force_all:
missing = set(ART_TYPES)
else:
missing = set()
for art_type, suffixes in _art_suffixes.items():
if not any((grid_path / f"{short_id}{s}").exists() for s in suffixes):
missing.add(art_type)
if missing:
# Find the sys_def for this shortcut's tag
sc_tag_val = next((str(v) for v in sc.tags.values()), '')
matched_sys = None
for sname, sdef in sys_info.items():
if sc_tag_val in sdef.all_category_tags():
matched_sys = sdef
break
work_list.append((sc, short_id, missing, matched_sys, sc_tag_val))
if not work_list:
print(f"\n All {len(shortcuts)} shortcut(s) already have complete artwork.\n")
return 0
print(f"\n ROM Art Scrape")
if system_filter:
print(f" System: {get_system(system_filter).fullname}")
if game_filter:
print(f" Game: {game_filter!r}")
print(f" To scrape: {len(work_list)} game(s) with missing art\n")
if args.dry_run:
for sc, short_id, missing, _, _tag in work_list[:30]:
missing_str = ', '.join(sorted(missing))
rom_path_dry = _extract_rom_path_from_exe(sc.exe)
hash_hint = " [hash]" if (rom_path_dry and rom_path_dry.exists()) else ""
print(f" {sc.appname[:55]:55s} missing: {missing_str}{hash_hint}")
if len(work_list) > 30:
print(f" ... and {len(work_list) - 30} more")
print(f"\n [hash] = ROM file found, hash-based lookup will be used")
print(f" (dry run — no changes made)\n")
return 0
scraper = CascadeScraper(config)
cache_dir = Path(config.get('art_cache_dir', '') or DEFAULT_CACHE_DIR).expanduser()
GREEN = "\033[32m"; YELLOW = "\033[33m"; RED = "\033[31m"
CYAN = "\033[36m"; GREY = "\033[90m"; RESET = "\033[0m"; BOLD = "\033[1m"
BAR_WIDTH = 20
def _bar(current: int, total_b: int, width: int = BAR_WIDTH) -> str:
if total_b <= 0:
return f"[{'─' * width}]"
filled = int(width * current / total_b)
return f"[{'█' * filled}{'─' * (width - filled)}]"
fetched = 0
failed = 0
total = len(work_list)
for idx, (sc, short_id, missing, sdef, sc_tag_val) in enumerate(work_list, 1):
label = sc.appname[:50].ljust(50)
counter = f"{GREY}[{idx:>{len(str(total))}}/{total}]{RESET}"
ss_id = sdef.screenscraper_id if sdef else None
tgdb_id = sdef.thegamesdb_id if sdef else None
# Extract ROM file path from shortcut exe for hash-based lookup
rom_path: Optional[Path] = _extract_rom_path_from_exe(sc.exe)
if rom_path and not rom_path.exists():
rom_path = None # File not accessible (e.g. SD card not mounted)
rom_filename: Optional[str] = rom_path.name if rom_path else None
# Hash progress callback — shows hashing bar then clears when done
hash_label = (rom_filename or sc.appname)[:28].ljust(28)
def _make_hash_cb(lbl: str, ctr: str):
def _cb(done: int, total_b: int) -> None:
bar = _bar(done, total_b)
pct = int(100 * done / total_b) if total_b else 0
print(f"\r {ctr} {GREY}Hashing {lbl} {bar} {pct:3d}%{RESET}",
end="", flush=True)
return _cb
hash_cb = _make_hash_cb(hash_label, counter) if rom_path else None
try:
artwork = scraper.scrape_game(
title=sc.appname,
system_name=sc_tag_val if not sdef else sdef.fullname,
screenscraper_id=ss_id,
thegamesdb_id=tgdb_id,
rom_path=rom_path,
rom_filename=rom_filename,
hash_progress_cb=hash_cb,
wanted_types=missing,
)
if artwork:
saved = save_grid_images(short_id, artwork, grid_path)
if saved:
store_art_in_cache(sc.appname, sdef.fullname if sdef else '', saved, cache_dir=cache_dir)
n = len(saved)
colour = GREEN if n == len(missing) else YELLOW
print(f"\r {counter} {colour}{label}{RESET} {colour}{n}/{len(missing)} images{RESET} ")
fetched += n
else:
print(f"\r {counter} {RED}{label}{RESET} no art found ")
failed += 1
except Exception as e:
print(f"\r {counter} {RED}{label}{RESET} error: {e} ")
failed += 1
print(f"\n {BOLD}Results:{RESET} {GREEN}{total - failed} games with art{RESET}, "
f"{RED}{failed} not found{RESET}, {fetched} images downloaded\n")
return 0
def _cmd_rom_art_remap(args: argparse.Namespace) -> int:
"""Rename grid art files from old SRM appids to current SGM appids.
Reads an old shortcuts.vdf (typically a SRM backup) to discover the old
app-IDs, then maps each game to its current SGM-format app-ID and renames
the art files in the grid folder accordingly. No API calls needed.
"""
from config import config_exists, get_resolved_config
from steam import find_steam_path, find_grid_path
from shortcuts import (
read_shortcuts_vdf,
generate_short_app_id,
SteamShortcut,
)
backup_file = Path(args.backup)
if not backup_file.exists():
print(f"Error: backup file not found: {backup_file}")
return 1
# Resolve grid path
cfg = get_resolved_config() if config_exists() else {}
steam_path_cfg = cfg.get('steam_path', '')
user_id = cfg.get('steam_user_id', 'auto')
try:
sp = find_steam_path()
grid_path = find_grid_path(sp, user_id if user_id != 'auto' else None)
except FileNotFoundError as e:
print(f"Error: {e}")
return 1
# Read old shortcuts
old_shortcuts = read_shortcuts_vdf(backup_file)
print(f"Read {len(old_shortcuts)} shortcuts from {backup_file.name}")
# Read current shortcuts to get the correct exe format per game
vdf_path = grid_path.parent / 'shortcuts.vdf'
current_shortcuts = read_shortcuts_vdf(vdf_path) if vdf_path.exists() else []
# Build lookup: appname -> list of current shortcuts
current_by_name: dict[str, list[SteamShortcut]] = {}
for sc in current_shortcuts:
current_by_name.setdefault(sc.appname, []).append(sc)
art_suffixes = [
'p.png', 'p.jpg', '.png', '.jpg',
'_hero.png', '_hero.jpg',
'_logo.png', '_logo.jpg',
'_icon.png', '_icon.jpg',
]
renames: list[tuple[Path, Path]] = []
skipped_no_art = 0
skipped_same_id = 0
skipped_no_new = 0
skipped_conflict = 0
for old_sc in old_shortcuts:
old_short = generate_short_app_id(old_sc.exe, old_sc.appname)
# Find the matching current shortcut for this game
candidates = current_by_name.get(old_sc.appname, [])
if not candidates:
skipped_no_new += 1
continue
# Prefer candidate whose tag matches the old one, otherwise take first
old_tag = list(old_sc.tags.values())[0] if old_sc.tags else ''
new_sc = candidates[0]
for c in candidates:
c_tag = list(c.tags.values())[0] if c.tags else ''
if c_tag == old_tag:
new_sc = c
break
new_short = generate_short_app_id(new_sc.exe, new_sc.appname)
if old_short == new_short:
skipped_same_id += 1
continue
# Determine whether this old appid has any art at all
has_any_art = any(
(grid_path / f"{old_short}{s}").exists() or
(grid_path / f"{old_short}{s}").is_symlink()
for s in art_suffixes
)
if not has_any_art:
skipped_no_art += 1
continue
# Collect per-suffix renames
for suffix in art_suffixes:
old_file = grid_path / f"{old_short}{suffix}"
new_file = grid_path / f"{new_short}{suffix}"
if not old_file.exists() and not old_file.is_symlink():