Repository navigation
Expand file tree
/
Copy pathvortextricks.py
More file actions
executable file
·949 lines (810 loc) · 35.7 KB
/
Copy pathvortextricks.py
File metadata and controls
executable file
·949 lines (810 loc) · 35.7 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
#!/usr/bin/env python3
"""
VortexTricks - Automate Vortex setup and game registration for Steam & GOG
This script performs the following high-level tasks:
1. **Detect installed game stores** - finds Steam and Heroic (GOG) installations.
2. **Enumerate installed games** - builds a mapping of app-IDs to `InstalledGame` objects.
3. **Resolve duplicate titles** - prompts the user to decide which copy of a game to keep
(Steam vs. GOG) and optionally creates separate bottles.
4. **Create/locate WINE prefixes** - creates a Vortex-specific prefix.
5. **Register games inside Vortex** - writes registry entries and symlinks for each game.
6. **Install Vortex** - downloads the latest release from GitHub and installs it into the
chosen prefix.
The module relies on several helper modules:
- `protontricks` - to locate the Steam installation.
- `gameinfo` - provides a registry of known games and their metadata.
- `vortex_symlink` - handles creation of game-specific symlinks.
- `requests` - for downloading the Vortex installer.
"""
import json
import logging
import os
import shutil
import subprocess
import tempfile
import urllib.parse
from pathlib import Path, PureWindowsPath, PurePosixPath
from enum import Enum
from typing import Any, Optional
from warnings import deprecated
import protontricks
import requests
import vortex_symlink
import gameinfo
from gameinfo import InstalledGame, JSON_INDENT
class Store(Enum):
"""
Enumeration of supported game distribution platforms.
Represents the primary store platform for a game's distribution.
Currently supports Steam and GOG, with potential for expansion.
Attributes
----------
STEAM : Store
Represents Steam platform (App IDs in steamapp_ids).
GOG : Store
Represents GOG/heroic platform (IDs in gog_id).
"""
STEAM = "Steam"
GOG = "GOG"
BOTTLES_PACKAGE = 'com.usebottles.bottles'
logging.basicConfig(
level=logging.INFO,
format="[%(levelname)s] %(asctime)s %(message)s",
datefmt="%H:%M:%S",
)
os.environ['WINEDEBUG'] = 'fixme-all'
# Build the registry
with open('gameinfo.json', 'r', encoding='utf-8') as json_file:
game_registry = gameinfo.load_games_from_json(json_file.read())
def main() -> int:
"""
High-level orchestration of the Vortex setup workflow.
Steps:
1. Enumerate installed Steam/GOG games.
2. Detect if the user is using Bottles or WINE.
3. Create WINE prefix(es) for Vortex if necessary.
4. Register the games inside the prefix.
5. Ensure Vortex is installed; otherwise download & install it.
Returns
-------
int
Process exit code (0 on success).
"""
steam_path, steam_root = protontricks.find_steam_path()
steam_games: dict[str, InstalledGame] = {}
heroic_path = find_heroic()
gog_games: dict[str, InstalledGame] = {}
# ----------------------------------------------------------------------------------------------------- #
# 1. Gather installed games
# ----------------------------------------------------------------------------------------------------- #
if steam_path is not None and steam_root is not None:
os.environ['STEAM_COMPAT_CLIENT_INSTALL_PATH'] = str(steam_path)
libraries: set[Path] = set(protontricks.get_steam_lib_paths(steam_path))
steam_apps: list[protontricks.SteamApp] = protontricks.get_steam_apps(steam_root, steam_path, libraries)
steam_games = list_compatible_steam_games(steam_apps)
logging.debug(steam_games)
if heroic_path is not None:
gog_games = list_compatible_gog_games(heroic_path)
logging.debug(gog_games)
duplicates = find_duplicate_games(steam_games, gog_games)
if duplicates:
for game_id, (steam_app, gog_app) in duplicates.items():
logging.warning("Duplicate game detected: %s (Steam=%s, GOG=%s)", game_id, steam_app, gog_app)
# ----------------------------------------------------------------------------------------------------- #
# 2. Determine prefix(es) to use for Vortex, create prefix(es) if necessary, and handle duplicate games
# ----------------------------------------------------------------------------------------------------- #
try:
wine_command = detect_bottles()
logging.info("Bottles CLI: %s", ' '.join(wine_command))
if duplicates:
steam_games, gog_games, bottle_names = handle_duplicates(duplicates, steam_games, gog_games, wine_command)
bottles_path = get_bottles_path(wine_command)
prefixes: dict[Store, Path] = {
store: bottles_path / bottle_names[store] for store in [Store.STEAM, Store.GOG]
}
else:
# No duplicates – keep default bottle name mapping
bottle_names = {Store.STEAM: "Vortex", Store.GOG: "Vortex"}
if not is_existing_bottle(wine_command):
logging.info("Creating default 'Vortex' bottle.")
vortex_prefix = create_bottle(wine_command)
else:
vortex_prefix = get_bottles_path(wine_command) / 'Vortex'
prefixes = {Store.STEAM: vortex_prefix, Store.GOG: vortex_prefix}
except (RuntimeError, subprocess.CalledProcessError) as e:
if shutil.which("wine") is None:
raise RuntimeError("Could not locate bottles-cli or wine") from e
wine_command = ['wine']
if duplicates:
steam_games, gog_games, bottle_names = handle_duplicates(duplicates, steam_games, gog_games, wine_command)
else:
bottle_names = {Store.STEAM: "Vortex", Store.GOG: "Vortex"}
vortex_prefix = find_vortex_prefix()
prefixes = {Store.STEAM: vortex_prefix, Store.GOG: vortex_prefix}
create_wine_prefix()
# ----------------------------------------------------------------------------------------------------- #
# 3. Register games inside the prefix(es)
# ----------------------------------------------------------------------------------------------------- #
for store in [Store.STEAM, Store.GOG]:
store_library = gog_games if store == Store.GOG else steam_games
if store_library:
configure_vortex_environment(wine_command, store, store_library, prefixes[store], bottle_names[store])
# ----------------------------------------------------------------------------------------------------- #
# 4. Install Vortex into the prefix(es) that are used
# ----------------------------------------------------------------------------------------------------- #
shortcut_directory = Path.home() / ".local" / "share" / "applications"
if using_bottles(wine_command):
temp_dir = get_bottles_path(wine_command).parent.joinpath("temp")
unique_bottle_names = sorted(list(set(bottle_names.values())), key=str.lower)
for bottle_name in unique_bottle_names:
programs = run(wine_command + ["--json", "programs", "-b", bottle_name], check=True, capture_output=True, text=True).stdout
if "Vortex.exe" not in programs:
temp_dir.mkdir(parents=True, exist_ok=True)
vortex_installer_path = download_vortex(temp_dir, "v1.16.9")
install_program(wine_command, vortex_installer_path, bottle_name)
run(wine_command + ["edit", "-b", bottle_name, "--params", "decorated:false"], check=True, capture_output=True)
content = Path('vortex.desktop').read_text(encoding='utf-8')
content = content.replace("Name=Vortex (NXM)", f"Name={bottle_name} (NXM)")
content += f'\nExec={" ".join(wine_command)} run -p Vortex -b "{bottle_name}" -- -d %u'
shortcut = shortcut_directory.joinpath(f"{bottle_name}.desktop")
shortcut.write_text(content, encoding='utf-8')
if shutil.which("xdg-mime") and len(unique_bottle_names) == 1:
run(["xdg-mime", "default", shortcut.name, "x-scheme-handler/nxm"], check=False)
if shutil.which("xdg-mime") and len(unique_bottle_names) > 1:
print("\nChoose a default NXM handler:")
print(" 0) None")
handler_choice:int | None = None
ctr = int(1)
for bottle_name in unique_bottle_names:
print(f" {ctr}) Use {bottle_name}")
ctr += 1
while handler_choice not in range(len(unique_bottle_names) + 1):
handler_choice = int(input(f"Enter choice (0-{len(unique_bottle_names)}): ").strip())
if handler_choice and handler_choice > 0:
shortcut = shortcut_directory.joinpath(f"{unique_bottle_names[handler_choice - 1]}.desktop")
run(["xdg-mime", "default", shortcut.name, "x-scheme-handler/nxm"], check=False)
elif not Path(Path(os.environ['WINEPREFIX']) / "drive_c/Program Files/Black Tree Gaming Ltd/Vortex/Vortex.exe").exists() and not Path(Path(os.environ['WINEPREFIX']) / "drive_c/Program Files/Vortex/Vortex.exe").exists():
temp_dir = Path(tempfile.gettempdir())
vortex_installer_path = download_vortex(temp_dir, "v1.16.9")
install_program(wine_command, vortex_installer_path)
if shutil.which("update-desktop-database") and shortcut_directory.exists():
run(["update-desktop-database", str(shortcut_directory)], check=False, capture_output=True)
logging.info("Vortex installed and configured successfully.")
return 0
def run(args: list[str], check: bool = True, **kwargs) -> subprocess.CompletedProcess:
"""
Wrap subprocess.run() and automatically inject `run` for proton binaries.
Expands user (~) and environment variables in the executable name,
prefers sudo-rs over sudo when available, and injects the `run`
subcommand when the executable is a proton binary.
Parameters
----------
args : list[str]
Command and arguments to execute.
check : bool, optional
Whether to raise on a non-zero exit code (default True).
**kwargs
Additional keyword arguments forwarded to subprocess.run().
Returns
-------
subprocess.CompletedProcess
Result of the executed command.
Raises
------
subprocess.CalledProcessError
If `check` is True and the command exits non-zero.
"""
# Expand user (~) and environment vars
command = os.path.expanduser(args[0])
command = os.path.expandvars(command)
if os.path.basename(command).endswith("proton") and (len(args) == 1 or args[1] != "run"):
# Inject 'run' if executable ends with 'proton'
args = [command, "run", *args[1:]]
elif command == "sudo" and shutil.which("sudo-rs"):
# Prefer sudo-rs if available
args = ["sudo-rs", *args[1:]]
else:
args = [command, *args[1:]]
logging.debug("Running: %s", " ".join(args))
return subprocess.run(args, check=check, **kwargs)
def detect_bottles() -> list[str]:
"""
Return the first found bottles CLI command.
Returns
-------
list[str]
Command list that invokes bottles-cli, either directly or via flatpak.
Raises
------
RuntimeError
If neither a working bottles-cli nor flatpak can be located.
"""
if shutil.which("bottles-cli") is not None:
return ["bottles-cli"]
elif shutil.which("flatpak") is not None:
bottles_command = ["flatpak", "run", "--command=bottles-cli", BOTTLES_PACKAGE]
if run(bottles_command + ["info", "health-check"], check=True, capture_output=True):
return bottles_command
else:
raise RuntimeError("Could not locate bottles-cli")
else:
raise RuntimeError("Could not locate bottles-cli or flatpak")
def using_bottles(wine_command: list[str]) -> bool:
"""
Return whether the given command uses bottles.
Parameters
----------
wine_command : list[str]
The wine or bottles command list to inspect.
Returns
-------
bool
True if the command invokes bottles-cli, False otherwise.
"""
return "bottles-cli" in wine_command or "--command=bottles-cli" in wine_command
def is_existing_bottle(bottles_command: list[str], bottle_name: str = "Vortex") -> bool:
"""
Check if a specific bottle exists in the Bottles configuration.
Executes the provided command with --json flag to list bottles, parses the
JSON output, and verifies if the specified bottle name exists in the
configuration.
Parameters
----------
bottles_command : list[str]
Base command to interact with Bottles (e.g., ['bottles-cli']).
bottle_name : str, optional
Name of the bottle to check (default: "Vortex").
Returns
-------
bool
True if the bottle exists, False otherwise.
Raises
------
subprocess.CalledProcessError
If the bottles list command exits non-zero.
"""
bottles: dict[str, Any] = json.loads(run(bottles_command + ["--json", "list", "bottles"], check=True, capture_output=True).stdout)
bottle = bottles.get(bottle_name)
if bottle is not None:
logging.debug(json.dumps(bottle, indent=JSON_INDENT))
return True
else:
return False
def create_bottle(bottles_command: list[str], bottle_name: str = "Vortex") -> Path:
"""
Create a new bottle with the appropriate runner configuration.
Selects either the sys-wine runner or a default runner based on available
components, then creates a new bottle with the specified name.
Parameters
----------
bottles_command : list[str]
List of command-line arguments for the bottles tool.
bottle_name : str, optional
Name of the new bottle (default: "Vortex").
Returns
-------
Path
Path object pointing to the created bottle's directory.
Raises
------
subprocess.CalledProcessError
If a bottles command exits non-zero.
"""
if bottles_command[0] == "flatpak":
fix_flatpak_permissions()
components = json.loads(run(bottles_command + ["--json", "list", "components"], check=True, capture_output=True).stdout)
logging.debug(json.dumps(components, indent=JSON_INDENT))
runners = components.get('runners')
sys_wine_entry = next(
(runner for runner in runners if runner.startswith("sys-wine")),
None
)
if sys_wine_entry is not None:
run(bottles_command + ["new", "--bottle-name", bottle_name, "--environment", "application", "--runner", sys_wine_entry], check=True)
else:
logging.warning("No sys-wine runner found. Using default runner.")
run(bottles_command + ["new", "--bottle-name", bottle_name, "--environment", "application"], check=True)
return Path(get_bottles_path(bottles_command)) / bottle_name
def find_vortex_prefix() -> Path:
"""
Locate or create the WINEPREFIX directory for Vortex Wine configuration.
Checks if the 'WINEPREFIX' environment variable is set. If not,
defaults to creating a directory at $HOME/Games/vortex/pfx.
Returns
-------
Path
The absolute path to the Vortex Wine prefix directory.
"""
if 'WINEPREFIX' not in os.environ:
os.environ['WINEPREFIX'] = str(Path.home() / 'Games/vortex/pfx')
os.environ['STEAM_COMPAT_DATA_PATH'] = str(Path(os.environ['WINEPREFIX']).parent)
return Path(os.environ['WINEPREFIX'])
def find_heroic() -> Path | None:
"""
Locate the Heroic games launcher configuration directory.
Searches for the default configuration path used by the Heroic games
launcher (now part of GOG's platform). The default path is constructed
as: ~/.var/app/com.heroicgameslauncher.hgl/config/heroic
This is used to locate game-specific configuration files for GOG games
managed through the Heroic launcher.
Returns
-------
Path | None
The Heroic configuration directory if it exists, otherwise None.
"""
path = Path.home() / ".var/app/com.heroicgameslauncher.hgl/config/heroic"
if path.exists():
return path
def create_wine_prefix(proton_path: str | None = None) -> subprocess.CompletedProcess:
"""
Create the WINEPREFIX directory and initialize Wine configuration.
Ensures the WINEPREFIX environment directory exists, then executes
`wineboot -u` to initialize Wine. If proton_path is provided, it uses
that executable instead of the default Wine binary.
Parameters
----------
proton_path : str | None, optional
Optional path to Proton/Wine executable (default: None).
Returns
-------
subprocess.CompletedProcess
Result of the wineboot command execution.
Raises
------
subprocess.CalledProcessError
If wineboot exits non-zero.
"""
os.makedirs(os.environ['WINEPREFIX'], exist_ok=True)
if proton_path is None:
return run(["wineboot", "-u"], check=True)
else:
return run([proton_path, "wineboot", "-u"], check=True)
def configure_vortex_environment(wine_command: list[str], store: Store, library: dict[str, InstalledGame], vortex_prefix: Path, bottle_name: str = "Vortex") -> None:
"""
Register the games in the user's library inside the Vortex bottle.
For each game, adds the registry entries known to the game registry and
creates game-specific symlinks between the Proton/Heroic prefix and the
Vortex prefix.
Parameters
----------
wine_command : list[str]
The wine or bottles command list to use.
store : Store
The store platform the library belongs to.
library : dict[str, InstalledGame]
Mapping of app-id to `InstalledGame` instance, as returned by
``list_compatible_steam_games`` or ``list_compatible_gog_games``.
vortex_prefix : Path
Path to the Vortex Wine prefix.
bottle_name : str, optional
Name of the bottle to register the games in (default: "Vortex").
Returns
-------
None
Raises
------
ValueError
If a GOG game is missing its GOG ID.
"""
for app_id, installed_game in library.items():
# Look up the game metadata in the registry
game = game_registry.get_game_by_id(app_id)
if game is None:
logging.warning("Game %s not found in registry", app_id)
continue
# Verify that the app‑id actually belongs to this game
if store == Store.STEAM and app_id not in game.steamapp_ids:
continue
if store == Store.GOG and app_id not in (game.gog_id or []):
continue
logging.info("Found game %s (appid=%s)", game.game_id, app_id)
# Add all registry entries
for key, value in game.registry_entries.items():
# Convert the Unix path to a Windows‑style path that Vortex expects
win_path = PureWindowsPath("z:", PurePosixPath(installed_game.game_path))
logging.info("Adding registry entry: %s -> %s\\%s", win_path, key, value)
add_registry_entry(wine_command, key, value, str(win_path), bottle_name)
# Create the game‑specific symlinks when we’re dealing with Steam
if store == Store.STEAM:
vortex_symlink.create_game_symlinks(
game=installed_game,
vortex_prefix=vortex_prefix,
game_prefix=Path.home() / f'.local/share/Steam/steamapps/compatdata/{app_id}/pfx')
elif store == Store.GOG:
if installed_game.gog_id:
folder_name = vortex_symlink.get_sorting_title(installed_game.gog_id)
if folder_name:
vortex_symlink.create_game_symlinks(
game=installed_game,
vortex_prefix=vortex_prefix,
game_prefix=Path.home() / "Games" / "Heroic" / "Prefixes" / "default" / folder_name)
else:
raise ValueError("Missing GOG ID")
def list_compatible_steam_games(steam_apps: list[protontricks.SteamApp]) -> dict[str, InstalledGame]:
"""
Return the installed Steam games that are known to be moddable.
Parameters
----------
steam_apps : list[protontricks.SteamApp]
A list of SteamApp objects to filter.
Returns
-------
dict[str, InstalledGame]
Mapping of Steam app-id to an `InstalledGame` for each game found in
the registry.
"""
games: dict[str, dict[str, str]] = {}
moddable_games: dict[str, InstalledGame] = {}
for app in steam_apps:
try:
if app.appid and app.is_tool == False:
appid = str(app.appid)
name: str = app.name
install_path = app.install_path
games[appid] = {
"name": name,
"path": str(install_path)
}
game = game_registry.get_game_by_id(appid)
if game:
moddable_games.update({appid: InstalledGame(name=game.name, game_id=game.game_id, steamapp_ids=[appid], gog_id=game.gog_id, ms_id=game.ms_id, epic_id=game.epic_id, registry_entries=game.registry_entries, game_path = install_path, override_appdata=game.override_appdata, override_mygames=game.override_mygames)})
except Exception as e:
logging.exception(e)
continue
logging.debug(json.dumps(list(games.values()), indent=JSON_INDENT))
return moddable_games
def list_compatible_gog_games(heroic_path: Path) -> dict[str, InstalledGame]:
"""
List all compatible GOG games managed by Heroic (Flatpak).
Parameters
----------
heroic_path : Path
Path to the Heroic configuration directory.
Returns
-------
dict[str, InstalledGame]
Mapping of app-id to an `InstalledGame` for each game found in the
registry.
Raises
------
FileNotFoundError
If Heroic's gog_store/installed.json is missing.
TypeError
If the 'installed' section is not a list.
"""
gog_store_path = heroic_path / "gog_store" / "installed.json"
if not gog_store_path.exists():
raise FileNotFoundError(f"GOG installed.json not found: {gog_store_path}")
with gog_store_path.open("r", encoding="utf-8") as file:
data = json.load(file)
installed_section = data.get("installed", [])
if not isinstance(installed_section, list):
raise TypeError(f"Expected 'installed' to be a list, got {type(installed_section).__name__}")
games:list[dict[str, str | None]] = []
moddable_games: dict[str, InstalledGame] = {}
for entry in installed_section:
if not isinstance(entry, dict):
continue
install_path = Path(entry.get("install_path", ""))
name = install_path.name if install_path else entry.get("appName", "Unknown")
appid = entry.get("appName") or name
games.append({
"appid": appid,
"name": name,
"path": str(install_path),
"platform": entry.get("platform"),
"version": entry.get("version"),
})
game = game_registry.get_game_by_id(appid)
if game:
moddable_games.update({appid: InstalledGame(name=game.name, game_id=game.game_id, steamapp_ids=game.steamapp_ids, gog_id=appid, ms_id=game.ms_id, epic_id=game.epic_id, registry_entries=game.registry_entries, game_path = install_path, override_appdata=game.override_appdata, override_mygames=game.override_mygames)})
logging.debug(json.dumps(games, indent=JSON_INDENT))
return moddable_games
def add_registry_entry(wine_command: list[str], key: str, value: str, data: str, bottle_name: str = "Vortex") -> subprocess.CompletedProcess:
"""
Add a registry entry using Wine's reg command, bottled or not.
Constructs and executes a registry add command via Wine, supporting:
- Bottled environments with specified bottle name
- Non-bottled environments
Parameters
----------
wine_command : list[str]
Base Wine command list for execution.
key : str
Registry key path (e.g., "HKEY_CURRENT_USER\\Software").
value : str
Registry value name.
data : str
Registry data.
bottle_name : str, optional
Name of the wine bottle to use (default: "Vortex").
Returns
-------
subprocess.CompletedProcess
Result of the registry operation.
Raises
------
subprocess.CalledProcessError
If the reg command exits non-zero.
"""
if using_bottles(wine_command):
result = run(wine_command + ["reg", "-b", bottle_name, "-k",
key, "-v", value, "-d",
data, "-t", "REG_SZ", "add"], check=True, capture_output=True)
else:
result = run(wine_command + ["reg", "add",
key,
"/t", "REG_SZ", "/v", value, "/d",
data], check=True)
return result
def download(url: str | bytes, destination: Path) -> Path:
"""
Download a file from a URL using requests.
If `destination` is an existing directory, the file is saved inside it
under the name taken from the final response URL.
Parameters
----------
url : str | bytes
URL to download.
destination : Path
Destination file path, or an existing directory to save into.
Returns
-------
Path
The path the file was actually written to.
Raises
------
requests.exceptions.RequestException
If the request fails or the server returns an error status.
"""
logging.info("Downloading %s to %s", url, destination)
response = requests.get(url, stream=True, timeout=10)
response.raise_for_status()
if destination.is_dir():
destination = destination / urllib.parse.urlparse(response.url).path.split("/")[-1]
with open(destination, "wb") as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
return destination
def download_vortex(directory: Path, version: str | None = None) -> Path:
"""
Download the Vortex setup executable from GitHub releases.
Fetches the latest release tag from the Nexus-Mods/Vortex repository,
constructs the download URL for the Windows installer, and saves it
to the specified directory with a filename formatted as:
vortex-setup-{tag_version}.exe
Parameters
----------
directory : Path
Target directory for saving the downloaded file.
version : str | None, optional
Specific version to download. If None, fetches the latest release
(default: None).
Returns
-------
Path
Absolute path to the downloaded Vortex setup executable.
Raises
------
requests.exceptions.RequestException
If API request fails or network error occurs.
ValueError
If required release information is missing from the API response.
"""
if version is None:
logging.info("Fetching latest Vortex release from GitHub...")
api_url = "https://api.github.com/repos/Nexus-Mods/Vortex/releases/latest"
response = requests.get(api_url, timeout=10)
response.raise_for_status()
release: dict[str, Any] = response.json()
tag_version = release.get("tag_name")
if not isinstance(tag_version, str):
raise ValueError("GitHub API response is missing required 'tag_name' field")
logging.info("Latest tag: %s", tag_version)
else:
tag_version = version
filename = f"vortex-setup-{tag_version.lstrip('v')}.exe"
download_url = f"https://github.com/Nexus-Mods/Vortex/releases/download/{tag_version}/{filename}"
path = directory.joinpath(filename)
download(download_url, path)
return path
def install_program(wine_command: list[str], installer_path: Path, bottle_name: str = "Vortex") -> subprocess.CompletedProcess:
"""
Install an application using WINE or Bottles, then delete the installer.
Parameters
----------
wine_command : list[str]
The wine or bottles command list to use.
installer_path : Path
Path to the installer executable.
bottle_name : str, optional
Name of the bottle to install into (default: "Vortex").
Returns
-------
subprocess.CompletedProcess
Result of the installer execution.
Raises
------
subprocess.CalledProcessError
If the installer exits non-zero.
"""
if using_bottles(wine_command):
result = run(wine_command + ["run", "-b", bottle_name, "-e", str(installer_path)], check=True)
else:
result = run(wine_command + [str(installer_path)], check=True)
installer_path.unlink(missing_ok=True)
return result
def fix_flatpak_permissions() -> None:
"""
Grant the Bottles flatpak access to Steam and Heroic directories.
This function executes flatpak override commands to allow Bottles to access:
1. Steam's xdg-data directory for game configuration files
2. Heroic Games directory for game installations
The overrides are necessary for Bottles to properly access game data when
running Windows applications through the Linux environment.
Returns
-------
None
Raises
------
subprocess.CalledProcessError
If a flatpak override command exits non-zero.
"""
run(["flatpak", "override", "--user", BOTTLES_PACKAGE, "--filesystem=xdg-data/Steam"], check=True)
run(["flatpak", "override", "--user", BOTTLES_PACKAGE, "--filesystem=~/Games/Heroic"], check=True)
def find_duplicate_games(
steam_games: dict[str, InstalledGame],
gog_games: dict[str, InstalledGame]
) -> dict[str, tuple[Optional[str], Optional[str]]]:
"""
Detect games that appear in **both** the Steam and GOG libraries.
Parameters
----------
steam_games : dict[str, InstalledGame]
Mapping of Steam app-id to installed game.
gog_games : dict[str, InstalledGame]
Mapping of GOG app-id to installed game.
Returns
-------
dict[str, tuple[Optional[str], Optional[str]]]
Mapping from the canonical `game_id` (e.g. "skyrimse") to a tuple
`(steam_app_id, gog_app_id)`. Either element may be `None` if the
game is present on only one platform.
"""
# ----------------------------------------------------------
# 1. Build app‑id -> GameInfo maps (skip unknown IDs)
# ----------------------------------------------------------
steam_appid_to_info: dict[str, gameinfo.GameInfo] = {}
for app_id in steam_games:
game_info = game_registry.get_game_by_id(app_id)
if game_info is not None:
steam_appid_to_info[app_id] = game_info
gog_appid_to_info: dict[str, gameinfo.GameInfo] = {}
for app_id in gog_games:
game_info = game_registry.get_game_by_id(app_id)
if game_info is not None:
gog_appid_to_info[app_id] = game_info
# ----------------------------------------------------------
# 2. Canonical game_id -> app‑id maps
# ----------------------------------------------------------
steam_id_to_appid: dict[str, str] = {}
for app_id, game_info in steam_appid_to_info.items():
steam_id_to_appid[game_info.game_id] = app_id
gog_id_to_appid: dict[str, str] = {}
for app_id, game_info in gog_appid_to_info.items():
gog_id_to_appid[game_info.game_id] = app_id
# ----------------------------------------------------------
# 3. Find common canonical IDs
# ----------------------------------------------------------
common_ids = set(steam_id_to_appid) & set(gog_id_to_appid)
# ----------------------------------------------------------
# 4. Build the result mapping
# ----------------------------------------------------------
duplicates: dict[str, tuple[Optional[str], Optional[str]]] = {}
for cid in common_ids:
duplicates[cid] = (
steam_id_to_appid.get(cid),
gog_id_to_appid.get(cid),
)
return duplicates
def handle_duplicates(
duplicates: dict[str, tuple[Optional[str], Optional[str]]],
steam_games: dict[str, InstalledGame],
gog_games: dict[str, InstalledGame],
wine_command: list[str]
) -> tuple[dict[str, InstalledGame], dict[str, InstalledGame], dict[Store, str]]:
"""
Ask the user how to resolve each duplicate game.
Parameters
----------
duplicates : dict
Mapping from canonical game_id to (steam_appid, gog_appid).
steam_games, gog_games : dict
The game dictionaries that will be cleaned.
wine_command : list[str]
The bottles-cli or wine command.
Returns
-------
steam_games, gog_games : dict
The cleaned dictionaries.
bottle_names : dict
Mapping Store -> bottle name (default "Vortex").
"""
bottle_names: dict[Store, str] = {Store.STEAM: "Vortex", Store.GOG: "Vortex"}
separate_bottles = False
bottles = using_bottles(wine_command)
for canonical_id, (steam_appid, gog_appid) in duplicates.items():
print(f"\nDuplicate detected for '{canonical_id}':")
print(f" 1) Use Steam version (AppID={steam_appid})")
print(f" 2) Use GOG version (AppID={gog_appid})")
choice = ""
if bottles:
print(" 3) Separate bottle for each store")
while choice not in ("1", "2", "3"):
choice = input("Enter 1, 2, or 3: ").strip()
else:
while choice not in ("1", "2"):
choice = input("Enter 1 or 2: ").strip()
if choice == "1":
# Keep Steam entry, drop GOG
if gog_appid in gog_games:
del gog_games[gog_appid]
elif choice == "2":
# Keep GOG entry, drop Steam
if steam_appid in steam_games:
del steam_games[steam_appid]
elif choice == "3" and bottles:
separate_bottles = True
# Create (or reuse) the appropriate bottles
if bottles:
if separate_bottles:
# Create two bottles if they don't exist
for store, bottle_name in [(Store.STEAM, "Vortex-Steam"),
(Store.GOG, "Vortex-GOG")]:
if not is_existing_bottle(wine_command, bottle_name):
logging.info("Creating bottle '%s' for %s store.", bottle_name, store.value)
create_bottle(wine_command, bottle_name=bottle_name)
bottle_names[store] = bottle_name
else:
# Create one bottle if it does not exist
if not is_existing_bottle(wine_command, "Vortex"):
logging.info("Creating default 'Vortex' bottle.")
create_bottle(wine_command, bottle_name="Vortex")
return steam_games, gog_games, bottle_names
def get_bottles_path(bottles_command: list[str]) -> Path:
"""
Retrieve the path to the bottles directory.
Parameters
----------
bottles_command : list[str]
Base command to interact with Bottles.
Returns
-------
Path
Absolute path to the directory containing all bottles.
Raises
------
subprocess.CalledProcessError
If the bottles info command exits non-zero.
"""
return Path(run(bottles_command + ["info", "bottles-path"], check=True, capture_output=True, text=True).stdout.strip())
@deprecated('xdg-mime seems to work despite the error message.')
def fix_plasma6() -> subprocess.CompletedProcess | None:
"""
Fix `xdg-mime default` on KDE Plasma 6 by symlinking qtpaths.
Creates a symlink from /usr/bin/qtpaths6 to /usr/local/bin/qtpaths when
xdg-mime is present, qtpaths is missing, and qtpaths6 exists.
See: https://gitlab.freedesktop.org/xdg/xdg-utils/-/issues/283
Returns
-------
subprocess.CompletedProcess | None
Result of the symlink command, or None if no fix was needed.
Raises
------
subprocess.CalledProcessError
If the symlink command exits non-zero.
"""
if shutil.which("xdg-mime") is not None and shutil.which("qtpaths") is None and Path("/usr/bin/qtpaths6").exists() and not Path("/usr/local/bin/qtpaths").exists():
return run(["sudo", "ln", "-s", "/usr/bin/qtpaths6", "/usr/local/bin/qtpaths"], check=True)
if __name__ == "__main__":
main()