This repository was archived by the owner on Dec 6, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
2936 lines (2451 loc) · 150 KB
/
main.py
File metadata and controls
2936 lines (2451 loc) · 150 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 decky
import os
import subprocess
import shutil
from pathlib import Path
import json
import glob
import re
import time
class Plugin:
def __init__(self):
self.environment = {
'XDG_DATA_HOME': os.path.expandvars('$HOME/.local/share'),
'UPDATE_RESHADE': '1',
'MERGE_SHADERS': '1',
'VULKAN_SUPPORT': '0',
'GLOBAL_INI': 'ReShade.ini',
'DELETE_RESHADE_FILES': '0',
'FORCE_RESHADE_UPDATE_CHECK': '0',
'RESHADE_ADDON_SUPPORT': '0',
'RESHADE_VERSION': 'latest',
'AUTOHDR_ENABLED': '0'
}
# Main paths for ReShade
self.main_path = os.path.join(self.environment['XDG_DATA_HOME'], 'reshade')
# Cache for executable paths
self.executable_cache = {}
# Create necessary directories
os.makedirs(self.main_path, exist_ok=True)
def _get_assets_dir(self) -> Path:
"""Get the assets directory, checking both possible locations"""
plugin_dir = Path(decky.DECKY_PLUGIN_DIR)
# Check defaults/assets first (development)
defaults_assets = plugin_dir / "defaults" / "assets"
if defaults_assets.exists():
decky.logger.info(f"Using assets from: {defaults_assets}")
return defaults_assets
# Check assets (decky store installation)
assets = plugin_dir / "assets"
if assets.exists():
decky.logger.info(f"Using assets from: {assets}")
return assets
# Fallback to defaults/assets even if it doesn't exist (for error reporting)
decky.logger.warning(f"Neither {defaults_assets} nor {assets} exists, defaulting to {defaults_assets}")
return defaults_assets
async def _main(self):
assets_dir = self._get_assets_dir()
for script in assets_dir.glob("*.sh"):
script.chmod(0o755)
decky.logger.info("ReShade plugin loaded")
async def _unload(self):
decky.logger.info("ReShade plugin unloaded")
async def parse_steam_logs_for_executable(self, appid: str) -> dict:
"""Parse Steam console logs to find the exact executable path Steam uses"""
try:
decky.logger.info(f"Parsing Steam logs for App ID: {appid}")
# Check cache first
cache_key = f"steam_log_{appid}"
if cache_key in self.executable_cache:
cached_result = self.executable_cache[cache_key]
# Check if cache is less than 1 hour old
if time.time() - cached_result.get('timestamp', 0) < 3600:
decky.logger.info(f"Using cached result for {appid}")
return cached_result
# Steam log file locations
log_files = [
"/home/deck/.steam/steam/logs/console-linux.txt",
"/home/deck/.steam/steam/logs/console_log.txt",
"/home/deck/.steam/steam/logs/console_log.previous.txt"
]
executable_path = None
launch_command = None
for log_file in log_files:
if not os.path.exists(log_file):
continue
decky.logger.info(f"Checking log file: {log_file}")
try:
# Read the log file (check last 10000 lines for performance)
with open(log_file, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
# Check recent lines first (Steam logs can be large)
recent_lines = lines[-10000:] if len(lines) > 10000 else lines
# Look for game launch patterns
for line in recent_lines:
# Pattern 1: Direct executable in launch command
# Example: AppId=501300 -- ... '/path/to/game.exe'
if f"AppId={appid}" in line and ".exe" in line:
# Extract the executable path
exe_match = re.search(r"'([^']*\.exe)'", line)
if exe_match:
potential_exe = exe_match.group(1)
# Verify this is a real path and not a temp file
if "/steamapps/common/" in potential_exe and os.path.exists(potential_exe):
executable_path = potential_exe
launch_command = line.strip()
decky.logger.info(f"Found executable from logs: {executable_path}")
break
# Pattern 2: Game process added/updated logs
# Example: Game process added : AppID 501300 "command with exe path"
if f"AppID {appid}" in line and (".exe" in line or "Game process" in line):
exe_match = re.search(r"'([^']*\.exe)'", line)
if not exe_match:
# Try different quote patterns
exe_match = re.search(r'"([^"]*\.exe)"', line)
if exe_match:
potential_exe = exe_match.group(1)
if "/steamapps/common/" in potential_exe and os.path.exists(potential_exe):
executable_path = potential_exe
launch_command = line.strip()
decky.logger.info(f"Found executable from process log: {executable_path}")
break
if executable_path:
break
except Exception as e:
decky.logger.error(f"Error reading log file {log_file}: {str(e)}")
continue
if executable_path:
# Cache the result
result = {
"status": "success",
"method": "steam_logs",
"executable_path": executable_path,
"directory_path": os.path.dirname(executable_path),
"filename": os.path.basename(executable_path),
"launch_command": launch_command,
"timestamp": time.time()
}
self.executable_cache[cache_key] = result
return result
else:
decky.logger.info(f"No executable found in logs for App ID: {appid}")
return {
"status": "not_found",
"method": "steam_logs",
"message": "No executable path found in Steam logs"
}
except Exception as e:
decky.logger.error(f"Error parsing Steam logs: {str(e)}")
return {
"status": "error",
"method": "steam_logs",
"message": str(e)
}
async def find_game_executable_enhanced(self, appid: str) -> dict:
"""Enhanced executable detection with simplified Linux game detection"""
try:
decky.logger.info(f"Enhanced detection with simplified Linux check for App ID: {appid}")
# Get the base game path using existing method
try:
steam_root = Path(decky.HOME) / ".steam" / "steam"
library_file = steam_root / "steamapps" / "libraryfolders.vdf"
if not library_file.exists():
return {"status": "error", "message": "Steam library file not found"}
library_paths = []
with open(library_file, "r", encoding="utf-8") as file:
for line in file:
if '"path"' in line:
path = line.split('"path"')[1].strip().strip('"').replace("\\\\", "/")
library_paths.append(path)
base_game_path = None
game_name = None
for library_path in library_paths:
manifest_path = Path(library_path) / "steamapps" / f"appmanifest_{appid}.acf"
if manifest_path.exists():
with open(manifest_path, "r", encoding="utf-8") as manifest:
manifest_content = manifest.read()
for line in manifest_content.split('\n'):
if '"installdir"' in line:
install_dir = line.split('"installdir"')[1].strip().strip('"')
base_game_path = str(Path(library_path) / "steamapps" / "common" / install_dir)
game_name = install_dir
elif '"name"' in line:
game_title = line.split('"name"')[1].strip().strip('"')
if not game_name:
game_name = game_title
break
if not base_game_path:
return {"status": "error", "message": f"Could not find installation directory for AppID: {appid}"}
decky.logger.info(f"Base game path: {base_game_path}")
decky.logger.info(f"Game name from Steam: {game_name}")
# Check appmanifest for Linux indicators
manifest_has_linux = False
for library_path in library_paths:
manifest_path = Path(library_path) / "steamapps" / f"appmanifest_{appid}.acf"
if manifest_path.exists():
with open(manifest_path, "r", encoding="utf-8") as manifest:
manifest_content = manifest.read().lower()
if "linux" in manifest_content:
manifest_has_linux = True
decky.logger.info("Found 'linux' in appmanifest")
break
except Exception as e:
return {"status": "error", "message": str(e)}
game_path_obj = Path(base_game_path)
if not game_path_obj.exists():
return {"status": "error", "message": f"Game path not found: {base_game_path}"}
# Simplified Linux detection - only check for key indicators
linux_indicators = {
'so_files': [],
'sh_files': []
}
all_executables = []
decky.logger.info(f"Scanning directory tree for executables and Linux indicators: {base_game_path}")
# Single directory traversal
for root, dirs, files in os.walk(base_game_path):
for file in files:
file_path = os.path.join(root, file)
file_obj = Path(file_path)
rel_path = os.path.relpath(file_path, base_game_path)
try:
file_size = os.path.getsize(file_path)
except:
continue
# Check for Windows executables
if file.lower().endswith('.exe'):
all_executables.append({
"path": file_path,
"directory_path": os.path.dirname(file_path),
"relative_path": rel_path,
"filename": file,
"size": file_size,
"size_mb": round(file_size / (1024 * 1024), 1),
"type": "windows_exe"
})
decky.logger.debug(f"Found Windows exe: {file} ({rel_path}) - {round(file_size / (1024 * 1024), 1)}MB")
# Simplified Linux detection - only .so and .sh files
file_lower = file.lower()
# Check for .so files
if file_lower.endswith('.so') or '.so.' in file_lower:
linux_indicators['so_files'].append(rel_path)
decky.logger.debug(f"Found .so file: {rel_path}")
# Check for .sh files
elif file_lower.endswith('.sh'):
linux_indicators['sh_files'].append(rel_path)
decky.logger.debug(f"Found .sh file: {rel_path}")
# Filter out utility executables from Windows list
main_windows_executables = []
for exe in all_executables:
if exe["type"] == "windows_exe":
exe_name = exe["filename"].lower()
if not any(skip in exe_name for skip in ["unins", "redist", "vcredist", "directx", "setup", "install"]):
main_windows_executables.append(exe)
# Simplified Linux game determination
is_linux_game = False
linux_confidence = "low"
linux_reasons = []
# Check for Linux indicators
so_file_count = len(linux_indicators['so_files'])
sh_file_count = len(linux_indicators['sh_files'])
if manifest_has_linux:
is_linux_game = True
linux_confidence = "high"
linux_reasons.append("Steam manifest contains 'linux'")
if so_file_count >= 5: # Multiple .so files is a strong indicator
is_linux_game = True
if linux_confidence != "high":
linux_confidence = "medium"
linux_reasons.append(f"Found {so_file_count} shared library (.so) files")
if sh_file_count >= 2: # Multiple shell scripts
is_linux_game = True
if linux_confidence == "low":
linux_confidence = "medium"
linux_reasons.append(f"Found {sh_file_count} shell script (.sh) files")
# If no Windows executables and Linux indicators present
if not main_windows_executables and (so_file_count > 0 or sh_file_count > 0):
is_linux_game = True
if linux_confidence == "low":
linux_confidence = "medium"
linux_reasons.append("No Windows executables found, Linux files present")
# If it's determined to be a Linux game, return early with warning
if is_linux_game and linux_confidence in ["high", "medium"]:
return {
"status": "linux_game_detected",
"method": "enhanced_detection_with_simplified_linux_check",
"is_linux_game": True,
"linux_confidence": linux_confidence,
"linux_reasons": linux_reasons,
"linux_indicators": linux_indicators,
"windows_executables_found": len(main_windows_executables),
"message": "Linux version detected - ReShade requires Windows version through Proton",
"details": {
"game_path": base_game_path,
"total_files_scanned": len(all_executables),
"windows_exe_count": len(main_windows_executables),
"so_files_count": so_file_count,
"sh_files_count": sh_file_count
},
"scan_summary": {
"total_files_scanned": len(all_executables),
"windows_executables": len(all_executables),
"main_windows_executables": len(main_windows_executables),
"so_files": so_file_count,
"sh_files": sh_file_count,
"linux_indicators_found": so_file_count + sh_file_count
}
}
# Continue with Windows executable analysis if not a Linux game
if not main_windows_executables:
return {
"status": "error",
"method": "enhanced_detection_with_simplified_linux_check",
"is_linux_game": is_linux_game,
"linux_confidence": linux_confidence,
"message": f"No suitable Windows executables found in game directory: {base_game_path}",
"details": {
"total_executables_found": len(all_executables),
"windows_exe_count": len(all_executables),
"main_windows_exe_count": len(main_windows_executables),
"so_files_count": so_file_count,
"sh_files_count": sh_file_count
},
"scan_summary": {
"total_files_scanned": len(all_executables),
"windows_executables": len(all_executables),
"main_windows_executables": len(main_windows_executables),
"so_files": so_file_count,
"sh_files": sh_file_count,
"linux_indicators_found": so_file_count + sh_file_count
}
}
decky.logger.info(f"Found {len(main_windows_executables)} Windows executables for scoring")
# ENHANCED SCORING for Windows executables (keeping existing logic)
def score_executable(exe_info):
score = 50
filename = exe_info["filename"].lower()
filename_no_ext = os.path.splitext(filename)[0]
rel_path = exe_info["relative_path"].lower()
size_mb = exe_info["size_mb"]
decky.logger.debug(f"Scoring {filename} at {rel_path}")
# Enhanced game name matching with multiple normalization approaches
clean_game_name = re.sub(r'[^a-z0-9]', '', game_name.lower()) if game_name else ""
clean_filename = re.sub(r'[^a-z0-9]', '', filename_no_ext)
# Split into words for more flexible matching
game_name_words = re.findall(r'[a-z0-9]+', game_name.lower()) if game_name else []
filename_words = re.findall(r'[a-z0-9]+', filename_no_ext)
# Calculate various types of matches
name_match_score = 0
# Exact matches (highest priority)
if clean_filename == clean_game_name:
name_match_score += 60
decky.logger.debug(f" Exact name match: +60 (normalized names match exactly)")
# Substantial partial matches (high priority)
elif clean_game_name and (clean_game_name in clean_filename or clean_filename in clean_game_name):
# Calculate how much of the string matches
match_ratio = max(
len(clean_game_name) / len(clean_filename) if len(clean_filename) > 0 else 0,
len(clean_filename) / len(clean_game_name) if len(clean_game_name) > 0 else 0
)
# Scale the score based on how much of the string matches (max 45 points)
partial_score = min(45, int(match_ratio * 45))
name_match_score += partial_score
decky.logger.debug(f" Partial name match: +{partial_score} (ratio: {match_ratio:.2f})")
# Word-level matches (medium priority)
else:
# Find matching words between game name and filename
matching_words = set(game_name_words).intersection(set(filename_words))
if matching_words:
# Calculate match percentage relative to the source words
match_percentage = len(matching_words) / len(game_name_words) if game_name_words else 0
word_score = len(matching_words) * 8 * (1 + match_percentage) # Scale based on percentage match
name_match_score += min(40, round(word_score)) # Cap at 40 points
decky.logger.debug(f" Word match: +{min(40, round(word_score))} ({matching_words})")
# Common game executable names bonus
if any(common in filename_no_ext.lower() for common in ["game", "main", "client", "app", "play"]):
common_bonus = 15
name_match_score += common_bonus
decky.logger.debug(f" Common game exe name: +{common_bonus}")
# Add the name match score to the total score
score += name_match_score
# Size-based scoring (reduced weights)
size_score = 0
if size_mb > 50: # Large games
size_score = 10 # Reduced from 35
elif size_mb > 20: # Medium games
size_score = 8 # Reduced from 25
elif size_mb > 5: # Small games
size_score = 5 # Reduced from 15
elif size_mb > 1: # Small but not tiny
size_score = 2 # Reduced from 5
elif size_mb < 0.5: # Very small files (likely utilities)
size_score = -20 # Keep this penalty to avoid tiny utility executables
score += size_score
decky.logger.debug(f" Size score: +{size_score} ({size_mb} MB)")
# Path-based scoring (more moderate)
path_score = 0
if "binaries/win64" in rel_path or "binaries\\win64" in rel_path: # Unreal Engine pattern
path_score += 15 # Reduced from 25
elif "bin" in rel_path: # Common bin directory
path_score += 10 # Reduced from 15
elif "game" in rel_path: # Game subdirectory
path_score += 8 # Reduced from 10
elif rel_path.count("/") == 0 and rel_path.count("\\") == 0: # Root directory
path_score += 5 # Reduced from 8
score += path_score
decky.logger.debug(f" Path score: +{path_score}")
# Special patterns from real data (more moderate)
special_score = 0
if "shipping" in filename: # Unreal shipping builds
special_score += 15 # Reduced from 20
elif "win64" in filename: # 64-bit indicator
special_score += 5 # Reduced from 8
elif "launcher" in filename: # Launchers (lower score but don't exclude)
special_score -= 25 # Increased penalty from 15
score += special_score
if special_score != 0:
decky.logger.debug(f" Special pattern score: {special_score}")
# Moderate penalty for deep nesting
path_depth = rel_path.count("/") + rel_path.count("\\")
if path_depth > 4: # Increased threshold
depth_penalty = (path_depth - 4) * 3
score -= depth_penalty
decky.logger.debug(f" Deep nesting penalty: -{depth_penalty}")
# Cap score between 0 and 100
score = max(0, min(100, score))
# Round to 1 decimal place for cleaner display
score = round(score, 1)
decky.logger.debug(f" Final score for {filename}: {score} (name match: {name_match_score})")
return score
# Score all Windows executables
scored_executables = []
for exe_info in main_windows_executables:
score = score_executable(exe_info)
if score > 0:
scored_executables.append({
**exe_info,
"score": score
})
else:
decky.logger.debug(f"Filtered out {exe_info['filename']} with score {score}")
if not scored_executables:
return {
"status": "error",
"method": "enhanced_detection_with_simplified_linux_check",
"is_linux_game": is_linux_game,
"message": "No suitable Windows executables found after scoring",
"scan_summary": {
"total_files_scanned": len(all_executables),
"windows_executables": len(all_executables),
"main_windows_executables": len(main_windows_executables),
"so_files": so_file_count,
"sh_files": sh_file_count,
"linux_indicators_found": so_file_count + sh_file_count
}
}
# Sort and get top results
scored_executables.sort(key=lambda x: x["score"], reverse=True)
top_executables = scored_executables[:5]
best_executable = top_executables[0]
decky.logger.info(f"Top executable: {best_executable['filename']} (score: {best_executable['score']})")
return {
"status": "success",
"method": "enhanced_detection_with_simplified_linux_check",
"executable_path": best_executable["path"],
"directory_path": best_executable["directory_path"],
"filename": best_executable["filename"],
"all_executables": top_executables,
"confidence": "high" if best_executable["score"] > 70 else "medium",
"is_linux_game": is_linux_game,
"linux_confidence": linux_confidence,
"linux_reasons": linux_reasons if linux_reasons else None,
"scan_summary": {
"total_files_scanned": len(all_executables),
"windows_executables": len(all_executables),
"main_windows_executables": len(main_windows_executables),
"so_files": so_file_count,
"sh_files": sh_file_count,
"linux_indicators_found": so_file_count + sh_file_count
}
}
except Exception as e:
decky.logger.error(f"Enhanced detection error: {str(e)}")
return {
"status": "error",
"method": "enhanced_detection_with_simplified_linux_check",
"message": str(e)
}
async def find_game_executable_path(self, appid: str) -> dict:
"""
Primary method that runs BOTH Steam logs and enhanced detection, returning both results
"""
try:
decky.logger.info(f"Finding executable path for App ID: {appid}")
# Method 1: Steam console logs
steam_logs_result = await self.parse_steam_logs_for_executable(appid)
# Method 2: Enhanced detection (now includes Linux detection)
enhanced_result = await self.find_game_executable_enhanced(appid)
# Handle special case where enhanced detection found a Linux game
if enhanced_result.get("status") == "linux_game_detected":
# Return the Linux detection as the enhanced result
return {
"status": "success",
"steam_logs_result": steam_logs_result,
"enhanced_detection_result": enhanced_result,
"recommended_method": "enhanced_detection", # Linux detection takes priority
"linux_game_warning": True
}
# Determine recommended method for Windows games
recommended_method = "steam_logs"
if steam_logs_result["status"] != "success":
recommended_method = "enhanced_detection"
return {
"status": "success",
"steam_logs_result": steam_logs_result,
"enhanced_detection_result": enhanced_result,
"recommended_method": recommended_method
}
except Exception as e:
decky.logger.error(f"Error in find_game_executable_path: {str(e)}")
return {
"status": "error",
"message": str(e)
}
async def find_heroic_game_executable_path(self, game_path: str, game_name: str) -> dict:
"""
Find executable paths for a Heroic game, similar to Steam game detection
"""
try:
decky.logger.info(f"Finding executable path for Heroic game: {game_name} at {game_path}")
# Check cache first
cache_key = f"heroic_{game_path}_{game_name}"
if cache_key in self.executable_cache:
cached_result = self.executable_cache[cache_key]
# Check if cache is less than 1 hour old
if time.time() - cached_result.get('timestamp', 0) < 3600:
decky.logger.info(f"Using cached result for {game_name}")
return cached_result
# Verify game path exists
if not os.path.exists(game_path):
return {"status": "error", "message": f"Game path not found: {game_path}"}
game_path_obj = Path(game_path)
# Find all executables in the game directory
all_executables = []
decky.logger.info(f"Walking directory tree starting from: {game_path}")
for root, dirs, files in os.walk(game_path):
for file in files:
if file.lower().endswith('.exe'):
exe_path = os.path.join(root, file)
try:
file_size = os.path.getsize(exe_path)
rel_path = os.path.relpath(exe_path, game_path)
all_executables.append({
"path": exe_path,
"directory_path": os.path.dirname(exe_path),
"relative_path": rel_path,
"filename": file,
"size": file_size,
"size_mb": round(file_size / (1024 * 1024), 1)
})
decky.logger.debug(f"Found exe: {file} ({rel_path}) - {round(file_size / (1024 * 1024), 1)}MB")
except Exception as e:
decky.logger.warning(f"Error getting size for {exe_path}: {str(e)}")
continue
if not all_executables:
return {
"status": "error",
"method": "heroic_enhanced_detection",
"message": f"No executables found in game directory: {game_path}"
}
decky.logger.info(f"Found {len(all_executables)} total executables")
# Enhanced filtering based on discovered patterns
def score_executable(exe_info):
score = 50 # Start with a base score
filename = exe_info["filename"].lower()
filename_no_ext = os.path.splitext(filename)[0] # Remove extension
rel_path = exe_info["relative_path"].lower()
size_mb = exe_info["size_mb"]
decky.logger.debug(f"Scoring {filename} at {rel_path}")
# LESS aggressive utility filtering - only skip very obvious ones
utility_keywords = ["unins", "setup", "vcredist", "directx", "redist"]
if any(skip in filename for skip in utility_keywords):
decky.logger.debug(f" Utility file detected: {filename}")
return 0
# Enhanced game name matching with multiple normalization approaches
# 1. Get directory name and clean game name
dir_name = os.path.basename(game_path).lower()
clean_game_name = game_name.lower()
# 2. Clean up names by removing spaces, special chars, etc.
clean_dir_name = re.sub(r'[^a-z0-9]', '', dir_name)
norm_game_name = re.sub(r'[^a-z0-9]', '', clean_game_name)
norm_filename = re.sub(r'[^a-z0-9]', '', filename_no_ext)
# 3. Split into words for more flexible matching
dir_words = re.findall(r'[a-z0-9]+', dir_name)
game_name_words = re.findall(r'[a-z0-9]+', clean_game_name)
filename_words = re.findall(r'[a-z0-9]+', filename_no_ext)
# Log the normalized values for debugging
decky.logger.debug(f" Normalized names - Dir: '{clean_dir_name}', Game: '{norm_game_name}', File: '{norm_filename}'")
# 4. Calculate various types of matches
name_match_score = 0
# Exact matches (highest priority)
if norm_filename == norm_game_name or norm_filename == clean_dir_name:
name_match_score += 60
decky.logger.debug(f" Exact name match: +60 (normalized names match exactly)")
# Handle specific cases like "among us.exe" vs "amongus" folder
elif (norm_filename.replace(" ", "") == norm_game_name or
norm_game_name.replace(" ", "") == norm_filename or
norm_filename.replace(" ", "") == clean_dir_name or
clean_dir_name.replace(" ", "") == norm_filename):
name_match_score += 55
decky.logger.debug(f" Space-normalized match: +55")
# Substantial partial matches (high priority)
elif (norm_game_name in norm_filename or norm_filename in norm_game_name or
clean_dir_name in norm_filename or norm_filename in clean_dir_name):
# Calculate how much of the string matches
match_ratio = max(
len(norm_game_name) / len(norm_filename) if len(norm_filename) > 0 else 0,
len(norm_filename) / len(norm_game_name) if len(norm_game_name) > 0 else 0,
len(clean_dir_name) / len(norm_filename) if len(norm_filename) > 0 else 0,
len(norm_filename) / len(clean_dir_name) if len(clean_dir_name) > 0 else 0
)
# Scale the score based on how much of the string matches (max 45 points)
partial_score = min(45, int(match_ratio * 45))
name_match_score += partial_score
decky.logger.debug(f" Partial name match: +{partial_score} (ratio: {match_ratio:.2f})")
# Extra case for when folder has additional characters (like "DREDGEmKMzX" vs "DREDGE.exe")
if (norm_filename in clean_dir_name and len(norm_filename) > 4 and
len(norm_filename) >= len(clean_dir_name) * 0.5):
extra_bonus = 15
name_match_score += extra_bonus
decky.logger.debug(f" Extra partial match bonus: +{extra_bonus} (likely main game exe)")
# Word-level matches (medium priority)
else:
# Find matching words between game name/dir and filename
matching_game_words = set(game_name_words).intersection(set(filename_words))
matching_dir_words = set(dir_words).intersection(set(filename_words))
# Use the best match (dir or game name)
best_matches = matching_game_words if len(matching_game_words) > len(matching_dir_words) else matching_dir_words
if best_matches:
# Calculate match percentage relative to the source words
match_percentage = len(best_matches) / len(game_name_words) if game_name_words else 0
word_score = len(best_matches) * 5.0 * (1 + match_percentage) # Scale based on percentage match
name_match_score += min(40, round(word_score)) # Cap at 40 points
decky.logger.debug(f" Word match: +{min(40, round(word_score))} ({best_matches})")
# Common game executable names bonus
if any(common in filename_no_ext.lower() for common in ["game", "main", "client", "app", "play"]):
common_bonus = 15
name_match_score += common_bonus
decky.logger.debug(f" Common game exe name: +{common_bonus}")
# Add the name match score to the total score
score += name_match_score
# Size-based scoring (reduced weights)
size_score = 0
if size_mb > 50: # Large games
size_score = 10 # Reduced from 35
elif size_mb > 20: # Medium games
size_score = 8 # Reduced from 25
elif size_mb > 5: # Small games
size_score = 5 # Reduced from 15
elif size_mb > 1: # Small but not tiny
size_score = 2 # Reduced from 5
elif size_mb < 0.5: # Very small files (likely utilities)
size_score = -10 # Reduced from 20
score += size_score
decky.logger.debug(f" Size score: +{size_score} ({size_mb} MB)")
# Path-based scoring
path_score = 0
if "binaries/win64" in rel_path or "binaries\\win64" in rel_path: # Unreal Engine pattern
path_score += 15 # Reduced from 25
elif "bin" in rel_path: # Common bin directory
path_score += 10 # Reduced from 15
elif "game" in rel_path: # Game subdirectory
path_score += 8 # Reduced from 10
elif rel_path.count("/") == 0 and rel_path.count("\\") == 0: # Root directory
path_score += 5 # Reduced from 8
score += path_score
decky.logger.debug(f" Path score: +{path_score}")
# Special patterns scoring
special_score = 0
if "shipping" in filename: # Unreal shipping builds
special_score += 15 # Reduced from 20
elif "win64" in filename: # 64-bit indicator
special_score += 5 # Reduced from 8
elif "launcher" in filename: # Launchers (lower score but don't exclude)
special_score -= 25 # Increased penalty from 15
score += special_score
if special_score != 0:
decky.logger.debug(f" Special pattern score: {special_score}")
# Moderate penalty for deep nesting
path_depth = rel_path.count("/") + rel_path.count("\\")
if path_depth > 4: # Increased threshold
depth_penalty = (path_depth - 4) * 3
score -= depth_penalty
decky.logger.debug(f" Deep nesting penalty: -{depth_penalty}")
# Cap score between 0 and 100
score = max(0, min(100, score))
# Round to 1 decimal place for cleaner display
score = round(score, 1)
decky.logger.debug(f" Final score for {filename}: {score} (name match: {name_match_score})")
return score
# Score all executables
scored_executables = []
for exe_info in all_executables:
score = score_executable(exe_info)
if score > 0:
scored_executables.append({
**exe_info,
"score": score
})
else:
decky.logger.debug(f"Filtered out {exe_info['filename']} with score {score}")
if not scored_executables:
# If we filtered everything out, include everything with any positive score
decky.logger.warning("All executables filtered out, using less restrictive filtering")
for exe_info in all_executables:
score = score_executable(exe_info)
if score >= 0:
scored_executables.append({
**exe_info,
"score": score
})
if not scored_executables:
# Last resort: include everything
decky.logger.warning("Still no executables, including all found")
for exe_info in all_executables:
scored_executables.append({
**exe_info,
"score": score_executable(exe_info)
})
# Sort by score (highest first) and take top 5
scored_executables.sort(key=lambda x: x["score"], reverse=True)
top_executables = scored_executables[:5]
best_executable = top_executables[0]
decky.logger.info(f"Total executables after filtering: {len(scored_executables)}")
decky.logger.info(f"Top 5 executables:")
for i, exe in enumerate(top_executables):
decky.logger.info(f" {i+1}. {exe['filename']} (score: {exe['score']}) at {exe['relative_path']}")
result = {
"status": "success",
"heroic_enhanced_detection_result": {
"status": "success",
"method": "heroic_enhanced_detection",
"executable_path": best_executable["path"],
"directory_path": best_executable["directory_path"],
"filename": best_executable["filename"],
"all_executables": top_executables,
"confidence": "high" if best_executable["score"] > 70 else "medium"
},
"recommended_method": "heroic_enhanced_detection",
"timestamp": time.time()
}
# Cache the result
self.executable_cache[cache_key] = result
return result
except Exception as e:
decky.logger.error(f"Heroic executable detection error: {str(e)}")
return {
"status": "error",
"method": "heroic_enhanced_detection",
"message": str(e)
}
async def save_shader_preferences(self, selected_shaders: list) -> dict:
"""Save user's shader preferences to a file"""
try:
preferences_file = os.path.join(self.main_path, "user_preferences.json")
# Load existing preferences to preserve other settings
existing_preferences = {}
if os.path.exists(preferences_file):
try:
with open(preferences_file, 'r') as f:
existing_preferences = json.load(f)
except:
pass # If file is corrupted, start fresh
# Update shader preferences while preserving other settings
existing_preferences.update({
"selected_shaders": selected_shaders,
"last_updated": int(time.time()),
"version": "1.1"
})
# Ensure directory exists
os.makedirs(self.main_path, exist_ok=True)
with open(preferences_file, 'w') as f:
json.dump(existing_preferences, f, indent=2)
decky.logger.info(f"Saved shader preferences: {selected_shaders}")
return {"status": "success", "message": "Shader preferences saved successfully"}
except Exception as e:
decky.logger.error(f"Error saving shader preferences: {str(e)}")
return {"status": "error", "message": str(e)}
async def load_shader_preferences(self) -> dict:
"""Load user's shader preferences from file"""
try:
preferences_file = os.path.join(self.main_path, "user_preferences.json")
# Also check old file for migration
old_preferences_file = os.path.join(self.main_path, "shader_preferences.json")
preferences = None
# Try to load from new file first
if os.path.exists(preferences_file):
with open(preferences_file, 'r') as f:
preferences = json.load(f)
# Migrate from old file if exists
elif os.path.exists(old_preferences_file):
with open(old_preferences_file, 'r') as f:
old_prefs = json.load(f)
# Migrate to new format
preferences = {
"selected_shaders": old_prefs.get("selected_shaders", []),
"last_updated": old_prefs.get("last_updated", int(time.time())),
"version": "1.1",
"autohdr_enabled": False # Default for migrated preferences
}
# Save in new format and remove old file
with open(preferences_file, 'w') as f:
json.dump(preferences, f, indent=2)
try:
os.remove(old_preferences_file)
except:
pass
if not preferences:
return {"status": "success", "preferences": None, "message": "No preferences file found"}
# Validate the preferences structure
if "selected_shaders" not in preferences:
return {"status": "error", "message": "Invalid preferences file format"}
decky.logger.info(f"Loaded shader preferences: {preferences['selected_shaders']}")
return {
"status": "success",
"preferences": preferences,
"selected_shaders": preferences["selected_shaders"]
}
except Exception as e:
decky.logger.error(f"Error loading shader preferences: {str(e)}")
return {"status": "error", "message": str(e)}
async def has_shader_preferences(self) -> dict:
"""Check if user has saved shader preferences"""
try:
preferences_file = os.path.join(self.main_path, "user_preferences.json")
old_preferences_file = os.path.join(self.main_path, "shader_preferences.json")
exists = os.path.exists(preferences_file) or os.path.exists(old_preferences_file)
if exists:
# Also load and return a summary
result = await self.load_shader_preferences()
if result["status"] == "success" and result["preferences"]:
shader_count = len(result["selected_shaders"])
return {
"status": "success",
"has_preferences": True,
"shader_count": shader_count,
"last_updated": result["preferences"].get("last_updated", 0)
}
return {"status": "success", "has_preferences": False}
except Exception as e:
decky.logger.error(f"Error checking shader preferences: {str(e)}")
return {"status": "error", "message": str(e)}
async def save_autohdr_preference(self, autohdr_enabled: bool) -> dict:
"""Save user's AutoHDR preference"""
try:
preferences_file = os.path.join(self.main_path, "user_preferences.json")
# Load existing preferences to preserve other settings
existing_preferences = {}
if os.path.exists(preferences_file):