forked from bottlesdevs/Bottles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinecommand.py
More file actions
911 lines (779 loc) · 32.9 KB
/
Copy pathwinecommand.py
File metadata and controls
911 lines (779 loc) · 32.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
import os
import re
import shlex
import shutil
import stat
import subprocess
import tempfile
from typing import Iterable, Optional
from bottles.backend.globals import (
Paths,
gamemode_available,
gamescope_available,
mangohud_available,
obs_vkc_available,
vmtouch_available,
)
from bottles.backend.logger import Logger
from bottles.backend.managers.runtime import RuntimeManager
from bottles.backend.managers.sandbox import SandboxManager
from bottles.backend.models.config import BottleConfig
from bottles.backend.models.result import Result
from bottles.backend.utils.display import DisplayUtils
from bottles.backend.utils.generic import detect_encoding, is_ntsync_available
from bottles.backend.utils.gpu import GPUUtils
from bottles.backend.utils.manager import ManagerUtils
from bottles.backend.utils.steam import SteamUtils
from bottles.backend.utils.terminal import TerminalUtils
logging = Logger()
class WineEnv:
"""
This class is used to store and return a command environment.
"""
__env: dict = {}
__result: dict = {"envs": {}, "overrides": []}
def __init__(self, clean: bool = False, allowed_keys: Optional[Iterable[str]] = None):
self.__env = {}
if clean:
return
if allowed_keys is None:
self.__env = os.environ.copy()
return
for key in allowed_keys:
if key in os.environ:
self.__env[key] = os.environ[key]
def add(self, key, value, override=False):
if key in self.__env:
if override:
self.__result["overrides"].append(f"{key}={value}")
else:
return
self.__env[key] = value
def add_bundle(self, bundle, override=False):
for key, value in bundle.items():
self.add(key, value, override)
def get(self):
result = self.__result
result["count_envs"] = len(result["envs"])
result["count_overrides"] = len(result["overrides"])
result["envs"] = self.__env
return result
def remove(self, key):
if key in self.__env:
del self.__env[key]
def is_empty(self, key):
return len(self.__env.get(key, "").strip()) == 0
def concat(self, key, values, sep=":"):
if isinstance(values, str):
values = [values]
values = sep.join(values)
if self.has(key):
values = self.__env[key] + sep + values
self.add(key, values, True)
def has(self, key):
return key in self.__env
def apply_wayland_preferences(env: "WineEnv", params) -> None:
if not getattr(params, "wayland", False):
return
if DisplayUtils.display_server_type() != "wayland":
return
wayland_display = os.environ.get("WAYLAND_DISPLAY")
if not env.has("WAYLAND_DISPLAY") and wayland_display:
env.add("WAYLAND_DISPLAY", wayland_display, override=True)
if env.has("WAYLAND_DISPLAY") or wayland_display:
env.remove("DISPLAY")
def _needs_steam_virtual_gamepad_workaround(runner_name: Optional[str]) -> bool:
"""Return True if the runner should force SteamVirtualGamepadInfo."""
if not runner_name:
return False
normalized = runner_name.lower()
if not any(
prefix in normalized for prefix in ("ge-proton", "proton-ge", "wine-ge", "soda")
):
return False
match = re.search(r"(\d+)", normalized)
if not match:
return False
try:
major = int(match.group(1))
except ValueError:
return False
return major <= 8
class WineCommand:
"""
This class is used to run a wine command with a custom environment.
It also handles the launch in a terminal or not.
"""
def __init__(
self,
config: BottleConfig,
command: str,
terminal: bool = False,
arguments: str = "",
environment: dict = {},
communicate: bool = False,
colors: str = "default",
minimal: bool = False, # avoid gamemode/gamescope usage
pre_script: Optional[str] = None,
post_script: Optional[str] = None,
pre_script_args: Optional[str] = None,
post_script_args: Optional[str] = None,
cwd: Optional[str] = None,
sandbox_override: Optional[str] = None,
):
_environment = environment.copy()
self.config = self._get_config(config)
self.minimal = minimal
# Per-launch override of the dedicated sandbox decided in the config:
# None -> follow the bottle setting
# "off" -> run this launch without the dedicated sandbox
self.sandbox_override = sandbox_override
self.arguments = arguments
self.cwd = self._get_cwd(cwd)
self.runner, self.runner_runtime = self._get_runner_info()
self.gamescope_activated = (
environment["GAMESCOPE"] == "1"
if "GAMESCOPE" in environment
else self.config.Parameters.gamescope
)
self.command = self.get_cmd(
command,
pre_script,
post_script,
pre_script_args,
post_script_args,
environment=_environment,
)
self.terminal = terminal
self.env = self.get_env(_environment)
self.communicate = communicate
self.colors = colors
self.vmtouch_files = None
def _get_config(self, config: BottleConfig) -> BottleConfig:
if cnf := config.data.get("config"):
return cnf
if not isinstance(config, BottleConfig):
logging.error("Invalid config type: %s" % type(config))
return BottleConfig()
return config
def _get_cwd(self, cwd) -> str:
config = self.config
if config.Environment == "Steam":
bottle = config.Path
else:
bottle = ManagerUtils.get_bottle_path(config)
if not cwd:
"""
If no cwd is given, use the WorkingDir from the
bottle configuration.
"""
cwd = config.WorkingDir
if cwd == "" or not os.path.exists(cwd):
"""
If the WorkingDir is empty, use the bottle path as
working directory.
"""
cwd = bottle
return cwd
def get_env(
self,
environment: Optional[dict] = None,
return_steam_env: bool = False,
return_clean_env: bool = False,
) -> dict:
config = self.config
clean_env = return_steam_env or return_clean_env
allowed_env_keys: Optional[Iterable[str]] = None
if not clean_env and getattr(config, "Limit_System_Environment", False):
allowed_env_keys = config.Inherited_Environment_Variables
env = WineEnv(clean=clean_env, allowed_keys=allowed_env_keys)
arch = config.Arch
params = config.Parameters
# Bottle Path as environment variable
env.add("BOTTLE", config.Path)
if None in [arch, params]:
return env.get()["envs"]
if environment is None:
environment = {}
bottle = ManagerUtils.get_bottle_path(config)
runner_path = ManagerUtils.get_runner_path(config.Runner)
if config.Environment == "Steam":
bottle = config.Path
runner_path = config.RunnerPath
if SteamUtils.is_proton(runner_path):
runner_path = SteamUtils.get_dist_directory(runner_path)
# Clean some env variables which can cause trouble
# ref: <https://github.com/bottlesdevs/Bottles/issues/2127>
# env.remove("XDG_DATA_HOME")
dll_overrides = []
gpu = GPUUtils().get_gpu()
DisplayUtils.check_nvidia_device()
ld = []
# Bottle environment variables
if _needs_steam_virtual_gamepad_workaround(config.Runner) and not env.has(
"SteamVirtualGamepadInfo"
):
env.add("SteamVirtualGamepadInfo", "", override=True)
if config.Environment_Variables:
for key, value in config.Environment_Variables.items():
env.add(key, value, override=True)
# Environment variables from argument
if environment:
if environment.get("WINEDLLOVERRIDES"):
dll_overrides.append(environment["WINEDLLOVERRIDES"])
del environment["WINEDLLOVERRIDES"]
if environment.get("DXVK_CONFIG_FILE", "") == "bottle_root":
environment["DXVK_CONFIG_FILE"] = os.path.join(bottle, "dxvk.conf")
for e in environment:
env.add(e, environment[e], override=True)
# Language
if config.Language != "sys":
# ensure an encoding is set (e.g. zh_CN -> zh_CN.UTF-8), otherwise
# wine renders non-Latin text as garbage
language = config.Language
if "." not in language:
language = f"{language}.UTF-8"
env.add("LC_ALL", language)
# Bottle DLL_Overrides
if config.DLL_Overrides:
for k, v in config.DLL_Overrides.items():
dll_overrides.append(f"{k}={v}")
# Default DLL overrides
if not return_steam_env:
dll_overrides.append("winemenubuilder=''")
# Get Runtime libraries
if (
(params.use_runtime or params.use_eac_runtime or params.use_be_runtime)
and not self.terminal
and not return_steam_env
):
_rb = RuntimeManager.get_runtime_env("bottles")
if _rb:
_eac = RuntimeManager.get_eac()
_be = RuntimeManager.get_be()
if params.use_runtime:
logging.info("Using Bottles runtime")
ld += _rb
if (
_eac and not self.minimal
): # NOTE: should check for runner compatibility with "eac" (?)
logging.info("Using EasyAntiCheat runtime")
env.add("PROTON_EAC_RUNTIME", _eac)
dll_overrides.append("easyanticheat_x86,easyanticheat_x64=b,n")
if (
_be and not self.minimal
): # NOTE: should check for runner compatibility with "be" (?)
logging.info("Using BattlEye runtime")
env.add("PROTON_BATTLEYE_RUNTIME", _be)
dll_overrides.append("beclient,beclient_x64=b,n")
else:
logging.warning("Bottles runtime was requested but not found")
# Get Runner libraries
if arch == "win64":
runner_libs = [
"lib",
"lib64",
"lib/wine/x86_64-unix",
"lib32/wine/x86_64-unix",
"lib64/wine/x86_64-unix",
"lib/wine/i386-unix",
"lib32/wine/i386-unix",
"lib64/wine/i386-unix",
]
gst_libs = [
"lib64/gstreamer-1.0",
"lib/gstreamer-1.0",
"lib32/gstreamer-1.0",
]
else:
runner_libs = [
"lib",
"lib/wine/i386-unix",
"lib32/wine/i386-unix",
"lib64/wine/i386-unix",
]
gst_libs = ["lib/gstreamer-1.0", "lib32/gstreamer-1.0"]
if not config.Runner.startswith("sys-"):
for lib in runner_libs:
_path = os.path.join(runner_path, lib)
if os.path.exists(_path):
ld.append(_path)
# Embedded GStreamer environment variables
if not env.has("BOTTLES_USE_SYSTEM_GSTREAMER") and not return_steam_env:
gst_env_path = []
for lib in gst_libs:
if os.path.exists(os.path.join(runner_path, lib)):
gst_env_path.append(os.path.join(runner_path, lib))
if len(gst_env_path) > 0:
env.add("GST_PLUGIN_SYSTEM_PATH", ":".join(gst_env_path), override=True)
# DXVK environment variables
if params.dxvk and not return_steam_env:
env.add("WINE_LARGE_ADDRESS_AWARE", "1")
env.add(
"DXVK_SHADER_CACHE_PATH", os.path.join(bottle, "cache", "dxvk_shader")
)
env.add("STAGING_SHARED_MEMORY", "1")
env.add("__GL_SHADER_DISK_CACHE", "1")
env.add(
"__GL_SHADER_DISK_CACHE_PATH",
os.path.join(bottle, "cache", "gl_shader"),
)
env.add(
"MESA_SHADER_CACHE_DIR", os.path.join(bottle, "cache", "mesa_shader")
)
# VKD3D environment variables
if params.vkd3d and not return_steam_env:
env.add(
"VKD3D_SHADER_CACHE_PATH", os.path.join(bottle, "cache", "vkd3d_shader")
)
# LatencyFleX environment variables
if params.latencyflex and not return_steam_env:
_lf_path = ManagerUtils.get_latencyflex_path(config.LatencyFleX)
_lf_layer_path = os.path.join(
_lf_path, "layer/usr/share/vulkan/implicit_layer.d"
)
env.concat("VK_ADD_LAYER_PATH", _lf_layer_path)
env.add("LFX", "1")
ld.append(os.path.join(_lf_path, "layer/usr/lib/x86_64-linux-gnu"))
else:
env.add("DISABLE_LFX", "1")
# Mangohud environment variables
if (
params.mangohud
and not self.minimal
and not (gamescope_available and self.gamescope_activated)
):
env.add("MANGOHUD", "1")
env.add("MANGOHUD_DLSYM", "1")
if not params.mangohud_display_on_game_start:
env.add("MANGOHUD_CONFIG", "read_cfg,no_display")
# vkBasalt environment variables
if params.vkbasalt and not self.minimal:
vkbasalt_conf_path = os.path.join(
ManagerUtils.get_bottle_path(config), "vkBasalt.conf"
)
if os.path.isfile(vkbasalt_conf_path):
env.add("VKBASALT_CONFIG_FILE", vkbasalt_conf_path)
env.add("ENABLE_VKBASALT", "1")
# OBS Vulkan Capture environment variables
if params.obsvkc and not self.minimal:
env.add("OBS_VKCAPTURE", "1")
if DisplayUtils.display_server_type() == "x11":
env.add("OBS_USE_EGL", "1")
# DXVK-Nvapi environment variables
if params.dxvk_nvapi and not return_steam_env:
# NOTE: users reported that DXVK_ENABLE_NVAPI and DXVK_NVAPIHACK must be set to make
# DLSS works. I don't have a GPU compatible with this tech, so I'll trust them
env.add("DXVK_NVAPIHACK", "0")
env.add("DXVK_ENABLE_NVAPI", "1")
# Esync environment variable
if params.sync == "esync":
env.add("WINEESYNC", "1")
# Fsync environment variable
if params.sync == "fsync":
env.add("WINEFSYNC", "1")
# Ntsync environment variable
if params.sync == "ntsync":
if is_ntsync_available(self.runner):
env.add("WINENTSYNC", "1")
else:
logging.warning(
"ntsync requested but unavailable, falling back to fsync"
)
env.add("WINEFSYNC", "1")
# Wine debug level
if not return_steam_env:
debug_level = "fixme-all"
if params.fixme_logs:
debug_level = "+fixme-all"
env.add("WINEDEBUG", debug_level)
# Aco compiler
# if params["aco_compiler"]:
# env.add("ACO_COMPILER", "aco")
# PulseAudio latency
if params.pulseaudio_latency:
env.add("PULSE_LATENCY_MSEC", "60")
# Discrete GPU
if not return_steam_env:
if params.discrete_gpu:
discrete = gpu["prime"]["discrete"]
if discrete is not None:
gpu_envs = discrete["envs"]
for p in gpu_envs:
env.add(p, gpu_envs[p])
env.concat("VK_ICD_FILENAMES", discrete["icd"])
# VK_ICD
if not env.has("VK_ICD_FILENAMES"):
if gpu["prime"]["integrated"] is not None:
"""
System support PRIME but user disabled the discrete GPU
setting (previus check skipped), so using the integrated one.
"""
env.concat("VK_ICD_FILENAMES", gpu["prime"]["integrated"]["icd"])
else:
"""
System doesn't support PRIME, so using the first result
from the gpu vendors list.
"""
if "vendors" in gpu and len(gpu["vendors"]) > 0:
_first = list(gpu["vendors"].keys())[0]
env.concat("VK_ICD_FILENAMES", gpu["vendors"][_first]["icd"])
else:
logging.warning(
"No GPU vendor found, keep going without setting VK_ICD_FILENAMES…"
)
# Add ld to LD_LIBRARY_PATH
if ld:
env.concat("LD_LIBRARY_PATH", ld)
# Vblank
# env.add("__GL_SYNC_TO_VBLANK", "0")
# env.add("vblank_mode", "0")
# DLL Overrides
env.concat("WINEDLLOVERRIDES", dll_overrides, sep=";")
if env.is_empty("WINEDLLOVERRIDES"):
env.remove("WINEDLLOVERRIDES")
if not return_steam_env:
# Wine prefix
env.add("WINEPREFIX", bottle, override=True)
# Wine arch
env.add("WINEARCH", arch)
apply_wayland_preferences(env, params)
return env.get()["envs"]
def _get_runner_info(self) -> tuple[str, str]:
config = self.config
runner = ManagerUtils.get_runner_path(config.Runner)
arch = config.Arch
runner_runtime = ""
if config.Environment == "Steam":
runner = config.RunnerPath
if runner in [None, ""]:
return "", ""
if SteamUtils.is_proton(runner):
"""
If the runner is Proton, set the path to /dist or /files
based on check if files exists.
Additionally, check for its corresponding runtime.
"""
runner_runtime = SteamUtils.get_associated_runtime(runner)
runner = os.path.join(SteamUtils.get_dist_directory(runner), "bin/wine")
elif runner.startswith("sys-"):
"""
If the runner type is system, set the runner binary
path to the system command. Else set it to the full path.
"""
runner = shutil.which("wine")
else:
runner = f"{runner}/bin/wine"
if arch == "win64" and os.path.exists(f"{runner}64"):
runner = f"{runner}64"
runner = shlex.quote(runner) # type: ignore
return runner, runner_runtime
def get_cmd(
self,
command,
pre_script: Optional[str] = None,
post_script: Optional[str] = None,
pre_script_args: Optional[str] = None,
post_script_args: Optional[str] = None,
return_steam_cmd: bool = False,
return_clean_cmd: bool = False,
environment: Optional[dict] = None,
) -> str:
config = self.config
params = config.Parameters
runner = self.runner
if environment is None:
environment = {}
if return_clean_cmd:
return_steam_cmd = True
if not return_steam_cmd and not return_clean_cmd:
command = f"{runner} {command}"
if not self.minimal:
if gamemode_available and params.gamemode:
if not return_steam_cmd:
command = f"{gamemode_available} {command}"
else:
command = f"gamemode {command}"
if mangohud_available and params.mangohud and not self.gamescope_activated:
if not return_steam_cmd:
command = f"{mangohud_available} {command}"
else:
command = f"mangohud {command}"
if gamescope_available and self.gamescope_activated:
# Write the script into Bottles' temp dir (shared with the
# dedicated sandbox) instead of the system /tmp, otherwise
# Gamescope running inside the sandbox cannot see it.
os.makedirs(Paths.temp, exist_ok=True)
gamescope_run = tempfile.NamedTemporaryFile(
mode="w", suffix=".sh", dir=Paths.temp
).name
# Create the sh script where Gamescope will execute it
file = ["#!/usr/bin/env sh\n"]
file.append(f"{command} $@")
if mangohud_available and params.mangohud:
file.append(" &\nmangoapp")
with open(gamescope_run, "w") as f:
f.write("".join(file))
# Update command
command = (
f"{self._get_gamescope_cmd(return_steam_cmd)} -- {gamescope_run}"
)
logging.info(f"Running Gamescope command: '{command}'")
logging.info(f"{gamescope_run} contains:")
with open(gamescope_run, "r") as f:
logging.info(f"\n\n{f.read()}")
# Set file as executable
st = os.stat(gamescope_run)
os.chmod(gamescope_run, st.st_mode | stat.S_IEXEC)
if obs_vkc_available and params.obsvkc:
command = f"{obs_vkc_available} {command}"
if params.use_steam_runtime:
_rs = RuntimeManager.get_runtimes("steam")
_picked = {}
if _rs:
if "sniper" in _rs.keys() and "sniper" in self.runner_runtime:
"""
Sniper is the default runtime used by Proton version >= 8.0
"""
_picked = _rs["sniper"]
elif "soldier" in _rs.keys() and "soldier" in self.runner_runtime:
"""
Sniper is the default runtime used by Proton version >= 5.13 and < 8.0
"""
_picked = _rs["soldier"]
elif "scout" in _rs.keys():
"""
For Wine runners, we cannot make assumption about which runtime would suits
them the best, as it would depend on their build environment.
Sniper/Soldier are not backward-compatible, defaulting to Scout should maximize compatibility.
"""
_picked = _rs["scout"]
else:
logging.warning("Steam runtime was requested but not found")
if _picked:
logging.info(f"Using Steam runtime {_picked['name']}")
command = f"{_picked['entry_point']} {command}"
else:
logging.warning(
"Steam runtime was requested and found but there are no valid combinations"
)
if self.arguments:
prefix, suffix, extracted_env = SteamUtils.handle_launch_options(
self.arguments
)
if prefix:
command = f"{prefix} {command}"
if suffix:
command = f"{command} {suffix}"
if extracted_env:
if extracted_env.get("WINEDLLOVERRIDES") and environment.get(
"WINEDLLOVERRIDES"
):
environment["WINEDLLOVERRIDES"] += ";" + extracted_env.get(
"WINEDLLOVERRIDES"
)
del extracted_env["WINEDLLOVERRIDES"]
environment.update(extracted_env)
if post_script not in (None, ""):
post_cmd_parts = [post_script]
if post_script_args not in (None, ""):
post_cmd_parts.extend(shlex.split(post_script_args))
post_cmd = " ".join(shlex.quote(part) for part in post_cmd_parts)
command = f"{command} ; sh {post_cmd}"
if pre_script not in (None, ""):
pre_cmd_parts = [pre_script]
if pre_script_args not in (None, ""):
pre_cmd_parts.extend(shlex.split(pre_script_args))
pre_cmd = " ".join(shlex.quote(part) for part in pre_cmd_parts)
command = f"sh {pre_cmd} ; {command}"
return command
def _get_gamescope_cmd(self, return_steam_cmd: bool = False) -> str:
config = self.config
params = config.Parameters
gamescope_cmd = []
if gamescope_available and self.gamescope_activated:
gamescope_cmd = [gamescope_available]
if return_steam_cmd:
gamescope_cmd = ["gamescope"]
if params.gamescope_custom_options:
gamescope_cmd.append(params.gamescope_custom_options)
if params.gamescope_fullscreen:
gamescope_cmd.append("-f")
if params.gamescope_borderless:
gamescope_cmd.append("-b")
if params.gamescope_scaling:
gamescope_cmd.append("-S integer")
if params.fsr:
gamescope_cmd.append("-F fsr")
gamescope_cmd.append(
f"--fsr-sharpness {params.fsr_sharpening_strength}"
)
if params.gamescope_fps > 0:
gamescope_cmd.append(f"-r {params.gamescope_fps}")
if params.gamescope_fps_no_focus > 0:
gamescope_cmd.append(f"-o {params.gamescope_fps_no_focus}")
if params.gamescope_game_width > 0:
gamescope_cmd.append(f"-w {params.gamescope_game_width}")
if params.gamescope_game_height > 0:
gamescope_cmd.append(f"-h {params.gamescope_game_height}")
if params.gamescope_window_width > 0:
gamescope_cmd.append(f"-W {params.gamescope_window_width}")
if params.gamescope_window_height > 0:
gamescope_cmd.append(f"-H {params.gamescope_window_height}")
return " ".join(gamescope_cmd)
def _vmtouch_preload(self):
vmtouch_flags = "-t -v -l -d"
vmtouch_file_size = " -m 1024M"
if self.command.find("C:\\") > 0:
s = (
self.cwd + "/" + (self.command.split(" ")[-1].split("\\")[-1])
).replace("'", "")
else:
s = self.command.split(" ")[-1]
self.vmtouch_files = shlex.quote(s)
# if self.config.Parameters.vmtouch_cache_cwd:
# self.vmtouch_files = "'"+self.vmtouch_files+"' '"+self.cwd+"/'" Commented out as fix for #1941
self.command = f"{vmtouch_available} {vmtouch_flags} {vmtouch_file_size} {self.vmtouch_files} && {self.command}"
def _vmtouch_free(self):
subprocess.Popen(
"kill $(pidof vmtouch)",
shell=True,
env=self.env,
cwd=self.cwd,
)
if not self.vmtouch_files:
return
vmtouch_flags = "-e -v"
command = f"{vmtouch_available} {vmtouch_flags} {self.vmtouch_files}"
subprocess.Popen(
command,
shell=True,
env=self.env,
cwd=self.cwd,
)
def _get_sandbox_manager(self) -> SandboxManager:
# Steam/Proton runners live outside Paths.runners (in the Steam data
# directory) and rely on their associated Steam Linux Runtime. Expose
# the runner root and that runtime, otherwise the runtime's own bwrap
# cannot find its entry point inside the dedicated sandbox. Symlinks are
# resolved so the real target gets shared, not just the link.
share_paths_ro = [Paths.runners, Paths.temp]
runner_root = (
self.config.RunnerPath
if self.config.Environment == "Steam" and self.config.RunnerPath
else ManagerUtils.get_runner_path(self.config.Runner)
)
for extra in (runner_root, self.runner_runtime):
if extra and not str(extra).startswith("sys-"):
share_paths_ro.append(os.path.realpath(extra))
# The working directory may be a transient document portal path
# (/run/user/<uid>/doc/<id>/...) which is not reliably reachable inside
# the nested sandbox: it can disappear or simply not be accessible to
# bwrap's chdir, which would make nothing launch at all. Resolve it to a
# real host path and fall back to the bottle path (always exposed and
# present) whenever it is not a usable directory.
bottle_path = ManagerUtils.get_bottle_path(self.config)
chdir = ManagerUtils.resolve_portal_path(self.cwd) if self.cwd else bottle_path
if (
not chdir
or ("/run/user/" in chdir and "/doc/" in chdir)
or not os.path.isdir(chdir)
):
logging.warning(
f"Working directory '{self.cwd}' is not usable inside the "
"dedicated sandbox, falling back to the bottle path.",
jn=True,
)
chdir = bottle_path
return SandboxManager(
envs=self.env,
chdir=chdir,
share_paths_rw=[bottle_path],
share_paths_ro=[p for p in share_paths_ro if p],
share_net=self.config.Sandbox.share_net,
share_sound=self.config.Sandbox.share_sound,
)
def run(self) -> Result[Optional[str]]:
"""
Run command with pre-configured parameters
:return: `status` is True if command executed successfully,
`data` may be available even if `status` is False.
"""
if None in [self.runner, self.env]:
return Result(
False, message="runner or env is not ready, Wine command terminated."
)
# Log the final command that will be executed
logging.info(f"Executing command: {self.command}")
if vmtouch_available and self.config.Parameters.vmtouch and not self.terminal:
self._vmtouch_preload()
use_sandbox = self.config.Parameters.sandbox
if self.sandbox_override == "off":
use_sandbox = False
logging.warning(
"Launching without the dedicated sandbox on user request: the "
"target is outside the bottle and cannot be reached otherwise.",
jn=True,
)
sandbox = self._get_sandbox_manager() if use_sandbox else None
# run command in external terminal if terminal is True
if self.terminal:
if sandbox:
return Result(
status=TerminalUtils().execute(
sandbox.get_cmd(self.command), self.env, self.colors, self.cwd
)
)
else:
return Result(
status=TerminalUtils().execute(
self.command, self.env, self.colors, self.cwd
)
)
# prepare proc if we are going to execute command internally
# proc should always be `Popen[bytes]` to make sure
# stdout_data's type is `bytes`
proc: subprocess.Popen[bytes]
if sandbox:
proc = sandbox.run(self.command)
else:
try:
proc = subprocess.Popen(
self.command,
stdout=subprocess.PIPE,
shell=True,
env=self.env,
cwd=self.cwd,
start_new_session=True,
)
except FileNotFoundError:
return Result(False, message="File not found")
if not self.communicate:
return Result(True)
stdout_data, _ = proc.communicate()
if vmtouch_available and self.config.Parameters.vmtouch:
# don't call vmtouch_free while running via external terminal
self._vmtouch_free()
# Consider changing the locale to C.UTF-8 when
# executing commands, to ensure consistent output and
# enable callers to make use of the returned value,
# also without requiring the encoding detection dance
codec = detect_encoding(stdout_data)
rv: str
try:
rv = stdout_data.decode(codec)
except (UnicodeDecodeError, LookupError, TypeError):
# UnicodeDecodeError: codec mismatch
# LookupError: unknown codec name
# TypeError: codec is None
logging.warning("stdout decoding failed")
rv = str(stdout_data)[2:-1] # trim b''
# "ShellExecuteEx" exception may occur while executing command,
# previously we rerun the command without `cwd` and `stdout=PIPE`
# to fix it, which is removed since it may lead to unexpected behavior
if "ShellExecuteEx" in rv:
logging.warning("ShellExecuteEx exception seems occurred.")
return Result(
False, data=rv, message="ShellExecuteEx exception seems occurred."
)
return Result(True, data=rv)