-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathoptiscaler_manager.py
More file actions
2580 lines (2162 loc) · 112 KB
/
optiscaler_manager.py
File metadata and controls
2580 lines (2162 loc) · 112 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
import os
import sys
import json
import shutil
import zipfile
import subprocess
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import configparser
class DependencyManager:
"""Manages automatic detection and installation of dependencies."""
def __init__(self):
self.package_managers = {
'apt': ['apt', 'apt-get'],
'pacman': ['pacman'],
'dnf': ['dnf', 'yum'],
'zypper': ['zypper'],
'emerge': ['emerge'],
'apk': ['apk'],
'xbps': ['xbps-install'],
'pkg': ['pkg'],
'brew': ['brew']
}
self.detected_pm = None
self.clipboard_apps = {
'xclip': {
'name': 'xclip',
'description': 'Simple clipboard utility (most common)',
'packages': {
'apt': 'xclip',
'pacman': 'xclip',
'dnf': 'xclip',
'zypper': 'xclip',
'emerge': 'x11-misc/xclip',
'apk': 'xclip',
'xbps': 'xclip',
'pkg': 'xclip'
}
},
'xsel': {
'name': 'xsel',
'description': 'Alternative clipboard utility',
'packages': {
'apt': 'xsel',
'pacman': 'xsel',
'dnf': 'xsel',
'zypper': 'xsel',
'emerge': 'x11-misc/xsel',
'apk': 'xsel',
'xbps': 'xsel',
'pkg': 'xsel'
}
},
'wl-copy': {
'name': 'wl-copy',
'description': 'Wayland clipboard utility',
'packages': {
'apt': 'wl-clipboard',
'pacman': 'wl-clipboard',
'dnf': 'wl-clipboard',
'zypper': 'wl-clipboard',
'emerge': 'gui-apps/wl-clipboard',
'apk': 'wl-clipboard',
'xbps': 'wl-clipboard',
'pkg': 'wl-clipboard'
}
}
}
def detect_package_manager(self) -> Optional[str]:
"""Detect the system's package manager."""
if self.detected_pm:
return self.detected_pm
for pm_name, commands in self.package_managers.items():
for cmd in commands:
try:
result = subprocess.run(['which', cmd], capture_output=True, text=True)
if result.returncode == 0:
self.detected_pm = pm_name
return pm_name
except Exception:
continue
return None
def detect_distro(self) -> str:
"""Detect Linux distribution."""
try:
with open('/etc/os-release', 'r') as f:
content = f.read()
if 'ID=' in content:
for line in content.split('\n'):
if line.startswith('ID='):
return line.split('=')[1].strip('"')
except:
pass
return "unknown"
def is_wayland(self) -> bool:
"""Check if running on Wayland."""
return os.environ.get('WAYLAND_DISPLAY') is not None
def install_package(self, package_name: str, pm_name: str = None) -> bool:
"""Install a package using the system package manager."""
if not pm_name:
pm_name = self.detect_package_manager()
if not pm_name:
print("❌ No supported package manager found")
return False
print(f"🔧 Installing {package_name} using {pm_name}...")
install_commands = {
'apt': ['sudo', 'apt', 'install', '-y', package_name],
'pacman': ['sudo', 'pacman', '-S', '--noconfirm', package_name],
'dnf': ['sudo', 'dnf', 'install', '-y', package_name],
'zypper': ['sudo', 'zypper', 'install', '-y', package_name],
'emerge': ['sudo', 'emerge', package_name],
'apk': ['sudo', 'apk', 'add', package_name],
'xbps': ['sudo', 'xbps-install', '-y', package_name],
'pkg': ['sudo', 'pkg', 'install', '-y', package_name],
'brew': ['brew', 'install', package_name]
}
if pm_name not in install_commands:
print(f"❌ Package manager {pm_name} not supported")
return False
try:
result = subprocess.run(install_commands[pm_name], capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ Successfully installed {package_name}")
return True
else:
print(f"❌ Failed to install {package_name}: {result.stderr}")
return False
except Exception as e:
print(f"❌ Error installing {package_name}: {e}")
return False
def check_python_module(self, module_name: str, pip_name: str = None) -> bool:
"""Check if a Python module is available and install if needed."""
if not pip_name:
pip_name = module_name
try:
__import__(module_name)
return True
except ImportError:
print(f"❌ Missing Python module: {module_name}")
pip_commands = ['pip3', 'pip', 'python3 -m pip', 'python -m pip']
for pip_cmd in pip_commands:
try:
# Check if pip command exists
check_cmd = pip_cmd.split()[0] if ' ' not in pip_cmd else pip_cmd.split()[-1]
result = subprocess.run(['which', check_cmd], capture_output=True)
if result.returncode != 0:
continue
print(f"🔧 Installing {pip_name} using {pip_cmd}...")
# Try installing with pip
install_cmd = f"{pip_cmd} install --user {pip_name}".split()
result = subprocess.run(install_cmd, capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ Successfully installed {pip_name}")
# Try importing again
try:
__import__(module_name)
return True
except ImportError:
print("⚠️ Module installed but still not importable, may need to restart")
return False
else:
print(f"❌ Failed with {pip_cmd}: {result.stderr}")
except Exception as e:
print(f"❌ Error with {pip_cmd}: {e}")
continue
# If pip installation failed, try system package manager
pm = self.detect_package_manager()
if pm:
python_packages = {
'requests': {
'apt': 'python3-requests',
'pacman': 'python-requests',
'dnf': 'python3-requests',
'zypper': 'python3-requests',
'emerge': 'dev-python/requests',
'apk': 'py3-requests',
'xbps': 'python3-requests'
}
}
if pip_name in python_packages and pm in python_packages[pip_name]:
package_name = python_packages[pip_name][pm]
return self.install_package(package_name, pm)
return False
def check_system_tool(self, tool_name: str, package_name: str = None, auto_install: bool = False) -> bool:
"""Check if a system tool is available and install if needed."""
if not package_name:
package_name = tool_name
try:
result = subprocess.run(['which', tool_name], capture_output=True, text=True)
if result.returncode == 0:
return True
except Exception:
pass
print(f"❌ Missing system tool: {tool_name}")
# Ask user if they want to install (unless auto_install is True)
if auto_install:
choice = 'y'
else:
choice = input(f"Install {tool_name}? (y/n): ").lower()
if choice == 'y':
pm = self.detect_package_manager()
if pm:
# Map some common package names
package_mappings = {
'7z': {
'apt': 'p7zip-full',
'pacman': 'p7zip',
'dnf': 'p7zip',
'zypper': 'p7zip',
'emerge': 'app-arch/p7zip',
'apk': 'p7zip',
'xbps': 'p7zip'
},
'git': {
'apt': 'git',
'pacman': 'git',
'dnf': 'git',
'zypper': 'git',
'emerge': 'dev-vcs/git',
'apk': 'git',
'xbps': 'git'
},
'wine': {
'apt': 'wine',
'pacman': 'wine',
'dnf': 'wine',
'zypper': 'wine',
'emerge': 'app-emulation/wine-vanilla',
'apk': 'wine',
'xbps': 'wine'
},
'curl': {
'apt': 'curl',
'pacman': 'curl',
'dnf': 'curl',
'zypper': 'curl',
'emerge': 'net-misc/curl',
'apk': 'curl',
'xbps': 'curl'
},
'wget': {
'apt': 'wget',
'pacman': 'wget',
'dnf': 'wget',
'zypper': 'wget',
'emerge': 'net-misc/wget',
'apk': 'wget',
'xbps': 'wget'
}
}
if tool_name in package_mappings and pm in package_mappings[tool_name]:
package_name = package_mappings[tool_name][pm]
return self.install_package(package_name, pm)
return False
def setup_clipboard_app(self) -> bool:
"""Set up clipboard functionality by installing a clipboard app."""
# Check if any clipboard app is already installed
installed_apps = []
for app_name, app_info in self.clipboard_apps.items():
try:
result = subprocess.run(['which', app_name], capture_output=True, text=True)
if result.returncode == 0:
installed_apps.append(app_name)
except Exception:
pass
if installed_apps:
print(f"✅ Found clipboard app(s): {', '.join(installed_apps)}")
return True
print("❌ No clipboard application found")
print("Clipboard functionality is needed for copying Steam launch commands")
# Recommend based on display server
if self.is_wayland():
print("🔍 Detected Wayland - recommending wl-copy")
recommended = 'wl-copy'
else:
print("🔍 Detected X11 - recommending xclip")
recommended = 'xclip'
print("\nAvailable clipboard applications:")
for i, (app_name, app_info) in enumerate(self.clipboard_apps.items(), 1):
marker = " (recommended)" if app_name == recommended else ""
print(f"{i}. {app_info['name']}: {app_info['description']}{marker}")
print(f"{len(self.clipboard_apps) + 1}. Install all clipboard apps")
print(f"{len(self.clipboard_apps) + 2}. Skip clipboard setup")
try:
choice = int(input(f"\nSelect clipboard app (1-{len(self.clipboard_apps) + 2}): "))
if choice == len(self.clipboard_apps) + 2:
print("⚠️ Skipping clipboard setup - launch commands won't be copied automatically")
return False
elif choice == len(self.clipboard_apps) + 1:
# Install all
pm = self.detect_package_manager()
if not pm:
print("❌ No package manager detected")
return False
success = True
for app_name, app_info in self.clipboard_apps.items():
if pm in app_info['packages']:
package_name = app_info['packages'][pm]
if not self.install_package(package_name, pm):
success = False
return success
elif 1 <= choice <= len(self.clipboard_apps):
# Install selected app
app_name = list(self.clipboard_apps.keys())[choice - 1]
app_info = self.clipboard_apps[app_name]
pm = self.detect_package_manager()
if not pm:
print("❌ No package manager detected")
return False
if pm in app_info['packages']:
package_name = app_info['packages'][pm]
return self.install_package(package_name, pm)
else:
print(f"❌ Package not available for {pm}")
return False
else:
print("❌ Invalid selection")
return False
except ValueError:
print("❌ Invalid input")
return False
def check_all_dependencies(self) -> bool:
"""Check and install all required dependencies."""
print("🔍 Checking dependencies...")
# Detect system info
pm = self.detect_package_manager()
distro = self.detect_distro()
is_wayland = self.is_wayland()
print(f"📊 System Info:")
print(f" Distribution: {distro}")
print(f" Package Manager: {pm or 'Not detected'}")
print(f" Display Server: {'Wayland' if is_wayland else 'X11'}")
all_ok = True
# Check Python modules
print("\n🐍 Checking Python modules...")
if not self.check_python_module('requests'):
all_ok = False
# Check system tools
print("\n🔧 Checking system tools...")
system_tools = {
'7z': 'p7zip',
'git': 'git',
'wine': 'wine',
'curl': 'curl',
'wget': 'wget'
}
missing_tools = []
for tool_name, package_name in system_tools.items():
try:
result = subprocess.run(['which', tool_name], capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ {tool_name} found")
else:
missing_tools.append((tool_name, package_name))
print(f"❌ {tool_name} not found")
except Exception:
missing_tools.append((tool_name, package_name))
print(f"❌ {tool_name} not found")
if missing_tools:
print(f"\n🔧 Found {len(missing_tools)} missing tools")
choice = input("Install all missing tools automatically? (y/n): ").lower()
if choice == 'y':
for tool_name, package_name in missing_tools:
self.check_system_tool(tool_name, package_name, auto_install=True)
else:
print("⚠️ Some tools are missing - you can install them individually later")
# Check clipboard apps
print("\n📋 Checking clipboard functionality...")
if not self.setup_clipboard_app():
print("⚠️ Clipboard functionality limited")
# Check terminal emulators
print("\n💻 Checking terminal emulators...")
terminal_found = False
terminals = ['konsole', 'gnome-terminal', 'xfce4-terminal', 'alacritty', 'kitty', 'terminator', 'xterm']
for terminal in terminals:
try:
result = subprocess.run(['which', terminal], capture_output=True, text=True)
if result.returncode == 0:
terminal_found = True
print(f"✅ Found terminal: {terminal}")
break
except Exception:
pass
if not terminal_found:
print("⚠️ No common terminal emulator found - OptiScaler setup scripts may need manual execution")
return all_ok
# Initialize dependency manager
dep_manager = DependencyManager()
# Check dependencies at startup
if not dep_manager.check_python_module('requests'):
print("❌ Critical dependency 'requests' could not be installed")
print("Please install it manually and restart the program")
sys.exit(1)
# Now we can safely import requests
import requests
class OptiScalerManager:
def __init__(self):
self.config_dir = Path.home() / ".config" / "optiscaler_manager"
self.config_dir.mkdir(parents=True, exist_ok=True)
self.installs_file = self.config_dir / "installations.json"
self.steam_path = self._find_steam_path()
self.github_api_url = "https://api.github.com/repos/optiscaler/OptiScaler/releases"
self.fsr4_dll_path = self._find_fsr4_dll()
def _find_steam_path(self) -> Optional[Path]:
steam_paths = [
Path.home() / ".steam" / "steam",
Path.home() / ".local" / "share" / "Steam",
Path("/usr/share/steam"),
Path.home() / ".steam" / "root",
Path.home() / "snap" / "steam" / "common" / ".steam" / "steam",
Path("/var/lib/flatpak/app/com.valvesoftware.Steam/home/.steam/steam"),
Path.home() / ".var" / "app" / "com.valvesoftware.Steam" / "home" / ".steam" / "steam",
]
for path in steam_paths:
if path.exists():
print(f"Found Steam at: {path}")
return path
print("Steam installation not found in standard locations")
return None
def _find_all_steam_libraries(self) -> List[Path]:
"""Find all Steam library folders across all drives including external and NTFS."""
libraries = []
# Start with the main Steam installation
if self.steam_path:
libraries.append(self.steam_path)
# Check for libraryfolders.vdf which lists additional Steam libraries
library_config = self.steam_path / "steamapps" / "libraryfolders.vdf"
if library_config.exists():
try:
with open(library_config, 'r', encoding='utf-8') as f:
content = f.read()
# Parse VDF format to find library paths
import re
path_matches = re.findall(r'"path"\s*"([^"]+)"', content)
for path_str in path_matches:
library_path = Path(path_str)
if library_path.exists() and library_path not in libraries:
libraries.append(library_path)
print(f"Found additional Steam library: {library_path}")
except Exception as e:
print(f"Error reading libraryfolders.vdf: {e}")
# Scan all mounted drives for Steam libraries
additional_libraries = self._scan_all_drives_for_steam()
for lib in additional_libraries:
if lib not in libraries:
libraries.append(lib)
return libraries
def _scan_all_drives_for_steam(self) -> List[Path]:
"""Scan all mounted drives for Steam installations and libraries."""
steam_libraries = []
# Get all mounted filesystems
try:
result = subprocess.run(['mount'], capture_output=True, text=True)
mount_lines = result.stdout.split('\n')
mount_points = []
for line in mount_lines:
parts = line.split()
if len(parts) >= 3 and parts[1] == 'on':
mount_point = parts[2]
# Include common mount points and external drives
if (mount_point.startswith('/mnt/') or
mount_point.startswith('/media/') or
mount_point.startswith('/run/media/') or
mount_point == '/' or
mount_point.startswith('/home')):
mount_points.append(Path(mount_point))
# Also check common external drive locations
external_locations = [
Path('/mnt'),
Path('/media'),
Path('/run/media'),
]
for ext_path in external_locations:
if ext_path.exists():
try:
for subdir in ext_path.iterdir():
if subdir.is_dir():
mount_points.append(subdir)
# Check subdirectories for user folders
try:
for user_dir in subdir.iterdir():
if user_dir.is_dir():
mount_points.append(user_dir)
except PermissionError:
pass
except PermissionError:
pass
# Search each mount point for Steam-related directories
for mount_point in mount_points:
steam_dirs = self._find_steam_dirs_in_path(mount_point)
steam_libraries.extend(steam_dirs)
except Exception as e:
print(f"Error scanning drives: {e}")
return steam_libraries
def _find_steam_dirs_in_path(self, search_path: Path) -> List[Path]:
"""Find Steam directories in a given path."""
steam_dirs = []
if not search_path.exists():
return steam_dirs
try:
# Common Steam directory patterns
steam_patterns = [
"Steam",
"steam",
".steam",
".local/share/Steam",
"SteamLibrary",
"Games/Steam",
"Program Files/Steam",
"Program Files (x86)/Steam",
]
# Search for Steam directories
for pattern in steam_patterns:
potential_steam = search_path / pattern
if potential_steam.exists():
# Check if it's a valid Steam directory
steamapps_path = potential_steam / "steamapps"
if steamapps_path.exists():
steam_dirs.append(potential_steam)
print(f"Found Steam library at: {potential_steam}")
# Also do a broader search for steamapps folders
try:
for item in search_path.iterdir():
if item.is_dir() and item.name.lower() in ['steamapps', 'steam']:
parent = item.parent
if parent not in steam_dirs:
# Verify it's a Steam directory
if (item / "common").exists() or (parent / "steam.exe").exists():
steam_dirs.append(parent)
print(f"Found Steam directory via steamapps: {parent}")
except (PermissionError, OSError):
# Skip directories we can't access
pass
except (PermissionError, OSError):
# Skip paths we can't access
pass
return steam_dirs
def _is_ntfs_drive(self, path: Path) -> bool:
"""Check if a path is on an NTFS filesystem."""
try:
result = subprocess.run(['stat', '-f', '-c', '%T', str(path)],
capture_output=True, text=True)
return 'ntfs' in result.stdout.lower()
except Exception:
return False
def _safe_case_insensitive_glob(self, path: Path, pattern: str) -> List[Path]:
"""Perform case-insensitive glob for NTFS drives."""
matches = []
# Regular glob first
matches.extend(path.glob(pattern))
# If on NTFS, also try case variations
if self._is_ntfs_drive(path):
variations = [
pattern.lower(),
pattern.upper(),
pattern.title(),
]
for variation in variations:
try:
matches.extend(path.glob(variation))
except Exception:
pass
# Remove duplicates
return list(set(matches))
def _find_fsr4_dll(self) -> Optional[Path]:
# Check config directory first (user's selected version)
config_dll = self.config_dir / "amdxcffx64.dll"
if config_dll.exists():
return config_dll
search_paths = [
# Current directory
Path.cwd() / "amdxcffx64.dll",
# Script directory
Path(__file__).parent / "amdxcffx64.dll",
# Common locations
Path.home() / "Downloads" / "amdxcffx64.dll",
Path("/usr/lib/amdxcffx64.dll"),
Path("/usr/local/lib/amdxcffx64.dll"),
# Search in common FSR directories
Path.home() / "Documents" / "fsr4" / "FSR 4.0" / "FSR 4.0.1" / "amdxcffx64.dll",
]
for path in search_paths:
if path.exists():
return path
# Search for FSR directories and bundled versions
fsr_search_dirs = [
Path.cwd() / "fsr4_dlls", # Bundled with script
Path(__file__).parent / "fsr4_dlls", # Script directory
Path.home() / "Documents" / "fsr4",
Path.home() / "Downloads",
]
for search_dir in fsr_search_dirs:
if search_dir.exists():
for fsr_dir in search_dir.rglob("*FSR*"):
if fsr_dir.is_dir():
dll_file = fsr_dir / "amdxcffx64.dll"
if dll_file.exists():
return dll_file
return None
def find_available_fsr4_versions(self) -> Dict[str, Path]:
versions = {}
# Search for bundled FSR4 DLLs
fsr_search_dirs = [
Path.cwd() / "fsr4_dlls",
Path(__file__).parent / "fsr4_dlls",
Path.home() / "Documents" / "fsr4",
Path.home() / "Downloads",
]
for search_dir in fsr_search_dirs:
if not search_dir.exists():
continue
# Look for version directories
for version_dir in search_dir.iterdir():
if version_dir.is_dir():
dll_file = version_dir / "amdxcffx64.dll"
if dll_file.exists():
version_name = version_dir.name
versions[version_name] = dll_file
# Also check direct DLL files with version names
for dll_file in search_dir.glob("**/amdxcffx64*.dll"):
if dll_file.exists():
parent_name = dll_file.parent.name
if "4.0" in parent_name or "FSR" in parent_name:
versions[parent_name] = dll_file
return versions
def select_fsr4_version(self) -> bool:
versions = self.find_available_fsr4_versions()
if not versions:
print("No FSR4 DLL versions found in bundled directories.")
return self.download_fsr4_dll()
print("\n=== Available FSR4 DLL Versions ===")
version_list = list(versions.items())
for i, (version_name, dll_path) in enumerate(version_list, 1):
print(f"{i}. {version_name}")
print(f" Path: {dll_path}")
print(f"{len(version_list) + 1}. Browse for custom DLL")
print(f"{len(version_list) + 2}. Cancel")
try:
choice = int(input(f"\nSelect FSR4 version (1-{len(version_list) + 2}): "))
if 1 <= choice <= len(version_list):
selected_version, selected_path = version_list[choice - 1]
# Copy selected version to config directory
target_dll = self.config_dir / "amdxcffx64.dll"
shutil.copy2(selected_path, target_dll)
print(f"✓ Selected FSR4 version: {selected_version}")
print(f"✓ Copied to: {target_dll}")
self.fsr4_dll_path = target_dll
return True
elif choice == len(version_list) + 1:
return self.download_fsr4_dll()
else:
print("Cancelled FSR4 version selection")
return False
except (ValueError, IndexError):
print("Invalid selection")
return False
def download_fsr4_dll(self) -> bool:
print("amdxcffx64.dll not found. This file is required for FSR4 functionality.")
print("Please obtain amdxcffx64.dll from your system32 folder and place it in one of these locations:")
print(f"1. Current directory: {Path.cwd()}")
print(f"2. Script directory: {Path(__file__).parent}")
print(f"3. Config directory: {self.config_dir}")
print("\nYou can copy it from: C:\\Windows\\System32\\amdxcffx64.dll (on Windows)")
print("Or from your Wine prefix system32 folder if you have it installed there.")
choice = input("\nDo you want to specify a custom path to amdxcffx64.dll? (y/n): ").lower()
if choice == 'y':
custom_path = input("Enter full path to amdxcffx64.dll: ").strip()
source_dll = Path(custom_path)
if source_dll.exists():
target_dll = self.config_dir / "amdxcffx64.dll"
try:
shutil.copy2(source_dll, target_dll)
self.fsr4_dll_path = target_dll
print(f"Copied amdxcffx64.dll to {target_dll}")
return True
except Exception as e:
print(f"Error copying DLL: {e}")
else:
print("File not found at specified path")
return False
def get_steam_games(self) -> List[Dict]:
if not self.steam_path:
print("Steam installation not found")
return []
games = []
# Get all Steam library locations
steam_libraries = self._find_all_steam_libraries()
print(f"Scanning {len(steam_libraries)} Steam libraries for games...")
for library_path in steam_libraries:
steamapps_path = library_path / "steamapps"
if not steamapps_path.exists():
continue
print(f"Scanning library: {library_path}")
# Find all manifest files in this library (with NTFS support)
manifest_files = self._safe_case_insensitive_glob(steamapps_path, "appmanifest_*.acf")
for manifest_file in manifest_files:
try:
with open(manifest_file, 'r', encoding='utf-8') as f:
content = f.read()
app_id = None
name = None
install_dir = None
for line in content.split('\n'):
line = line.strip()
if line.startswith('"appid"'):
app_id = line.split('"')[3]
elif line.startswith('"name"'):
name = line.split('"')[3]
elif line.startswith('"installdir"'):
install_dir = line.split('"')[3]
if app_id and name and install_dir:
game_path = steamapps_path / "common" / install_dir
if game_path.exists():
# Check if we already have this game from another library
existing_game = next((g for g in games if g["app_id"] == app_id), None)
if not existing_game:
games.append({
"app_id": app_id,
"name": name,
"install_dir": install_dir,
"path": str(game_path),
"library_path": str(library_path)
})
else:
# Game exists in multiple libraries, keep the one with more recent activity
try:
existing_mtime = Path(existing_game["path"]).stat().st_mtime
current_mtime = game_path.stat().st_mtime
if current_mtime > existing_mtime:
# Replace with more recent version
for i, game in enumerate(games):
if game["app_id"] == app_id:
games[i] = {
"app_id": app_id,
"name": name,
"install_dir": install_dir,
"path": str(game_path),
"library_path": str(library_path)
}
break
except OSError:
pass # Can't get mtime, keep existing
except Exception as e:
print(f"Error reading manifest {manifest_file}: {e}")
print(f"Found {len(games)} games across all Steam libraries")
return sorted(games, key=lambda x: x["name"])
def find_game_executable_paths(self, game_path: str) -> List[Dict[str, str]]:
"""Find all possible executable locations with details about what's in each folder"""
game_dir = Path(game_path)
exe_locations = []
# Find all executable files and analyze them
for exe_file in game_dir.rglob("*.exe"):
if not exe_file.is_file():
continue
# Skip obvious non-game executables
skip_paths = ["engine", "redist", "directx", "vcredist", "_commonredist", "tools", "crash"]
skip_names = ["unins", "setup", "launcher", "redist", "vcredist", "directx", "crash"]
path_str = str(exe_file.parent).lower()
name_str = exe_file.name.lower()
# Skip if in excluded paths or has excluded names
if (any(skip in path_str for skip in skip_paths) or
any(skip in name_str for skip in skip_names)):
continue
# Determine the type/priority of this executable
exe_type = "Other"
priority = 3
if exe_file.parent == game_dir:
exe_type = "Main Game Directory"
priority = 1
elif "_shipping" in name_str:
exe_type = "Shipping Executable (UE)"
priority = 1
elif any(folder in str(exe_file.parent).lower() for folder in ["bin/x64", "retail", "binaries/win64"]):
exe_type = "Common Game Folder"
priority = 2
elif "ue4" in name_str or "ue5" in name_str:
continue # Skip UE engine executables
# Create location info
location_info = {
"path": str(exe_file.parent),
"exe_name": exe_file.name,
"type": exe_type,
"priority": priority,
"relative_path": str(exe_file.parent.relative_to(game_dir))
}
# Check if we already have this path
existing = next((loc for loc in exe_locations if loc["path"] == location_info["path"]), None)
if existing:
# If we find a better executable in the same folder, update it
if priority < existing["priority"]:
existing.update(location_info)
else:
exe_locations.append(location_info)
# Sort by priority (lower number = higher priority) then by path depth
exe_locations.sort(key=lambda x: (x["priority"], len(Path(x["path"]).parts), x["path"]))
return exe_locations
def get_compatdata_path(self, app_id: str) -> Optional[Path]:
if not self.steam_path:
return None
compatdata_path = self.steam_path / "steamapps" / "compatdata" / app_id
if compatdata_path.exists():
return compatdata_path
return None
def copy_fsr4_dll_to_compatdata(self, app_id: str) -> bool:
if not self.fsr4_dll_path or not self.fsr4_dll_path.exists():
print("FSR4 DLL not found. Please select a version...")
if not self.select_fsr4_version():
return False
compatdata_path = self.get_compatdata_path(app_id)
if not compatdata_path:
print(f"Compatdata folder not found for app ID {app_id}")
return False
system32_path = compatdata_path / "pfx" / "drive_c" / "windows" / "system32"
system32_path.mkdir(parents=True, exist_ok=True)
target_dll = system32_path / "amdxcffx64.dll"
try:
shutil.copy2(self.fsr4_dll_path, target_dll)
print(f"Copied amdxcffx64.dll to {target_dll}")
return True
except Exception as e:
print(f"Error copying FSR4 DLL: {e}")
return False
def download_latest_nightly(self) -> Optional[str]:
try:
response = requests.get(self.github_api_url)
response.raise_for_status()
releases = response.json()
for release in releases:
if release.get("latest", False) or release.get("tag_name") == "latest":
for asset in release["assets"]:
if asset["name"].endswith((".zip", ".7z")):
download_url = asset["browser_download_url"]
filename = asset["name"]
print(f"Downloading {filename}...")
zip_response = requests.get(download_url)
zip_response.raise_for_status()
download_path = self.config_dir / filename
with open(download_path, "wb") as f:
f.write(zip_response.content)
return str(download_path)
# If no nightly found, try latest stable release
if releases:
latest_release = releases[0]