-
-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathmanager.py
More file actions
2170 lines (1872 loc) · 80.5 KB
/
manager.py
File metadata and controls
2170 lines (1872 loc) · 80.5 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
# manager.py
#
# Copyright 2025 mirkobrombin <brombin94@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, in version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import contextlib
import fnmatch
import os
import random
import shutil
import subprocess
import time
import uuid
from datetime import datetime
from gettext import gettext as _
from glob import glob
from threading import Event
from typing import Any, Callable, Dict, List, Optional, Tuple
import pathvalidate
from bottles.backend.dlls.dxvk import DXVKComponent
from bottles.backend.dlls.latencyflex import LatencyFleXComponent
from bottles.backend.dlls.nvapi import NVAPIComponent
from bottles.backend.dlls.vkd3d import VKD3DComponent
from bottles.backend.globals import Paths
from bottles.backend.logger import Logger
from bottles.backend.managers.btrfssubvolume import BtrfsSubvolumeManager
from bottles.backend.managers.component import ComponentManager
from bottles.backend.managers.data import DataManager, UserDataKeys
from bottles.backend.managers.dependency import DependencyManager
from bottles.backend.managers.epicgamesstore import EpicGamesStoreManager
from bottles.backend.managers.importer import ImportManager
from bottles.backend.managers.installer import InstallerManager
from bottles.backend.managers.library import LibraryManager
from bottles.backend.managers.playtime import ProcessSessionTracker
from bottles.backend.managers.registry_rule import RegistryRuleManager
from bottles.backend.managers.repository import RepositoryManager
from bottles.backend.managers.steam import SteamManager
from bottles.backend.managers.template import TemplateManager
from bottles.backend.managers.ubisoftconnect import UbisoftConnectManager
from bottles.backend.managers.versioning import VersioningManager
from bottles.backend.models.config import BottleConfig
from bottles.backend.models.process import (
ProcessFinishedPayload,
ProcessStartedPayload,
)
from bottles.backend.models.result import Result
from bottles.backend.models.samples import Samples
from bottles.backend.state import EventManager, Events, SignalManager, Signals
from bottles.backend.utils import yaml
from bottles.backend.utils.connection import ConnectionUtils
from bottles.backend.utils.file import FileUtils
from bottles.backend.utils.generic import sort_by_version
from bottles.backend.utils.gpu import GPUUtils, GPUVendors
from bottles.backend.utils.gsettings_stub import GSettingsStub
from bottles.backend.utils.lnk import LnkUtils
from bottles.backend.utils.manager import ManagerUtils
from bottles.backend.utils.singleton import Singleton
from bottles.backend.utils.steam import SteamUtils
from bottles.backend.utils.threading import RunAsync
from bottles.backend.wine.reg import Reg
from bottles.backend.wine.regkeys import RegKeys
from bottles.backend.wine.uninstaller import Uninstaller
from bottles.backend.wine.wineboot import WineBoot
from bottles.backend.wine.winepath import WinePath
from bottles.backend.wine.wineserver import WineServer
logging = Logger()
class Manager(metaclass=Singleton):
"""
This is the core of Bottles, everything starts from here. There should
be only one instance of this class, as it checks for the existence of
the bottles' directories and creates them if they don't exist. Also
check for components, dependencies, and installers so this check should
not be performed every time the manager is initialized.
"""
# component lists
runtimes_available = []
winebridge_available = []
runners_available = []
dxvk_available = []
vkd3d_available = []
nvapi_available = []
latencyflex_available = []
local_bottles: Dict[str, BottleConfig] = {}
supported_runtimes = {}
supported_winebridge = {}
supported_wine_runners = {}
supported_proton_runners = {}
supported_dxvk = {}
supported_vkd3d = {}
supported_nvapi = {}
supported_latencyflex = {}
supported_dependencies = {}
supported_installers = {}
_playtime_signals_connected: bool = False
def __init__(
self,
g_settings: Any = None,
check_connection: bool = True,
is_cli: bool = False,
**kwargs,
):
super().__init__(**kwargs)
times = {"start": time.time()}
# common variables
self.is_cli = is_cli
self.settings = g_settings or GSettingsStub
self.utils_conn = ConnectionUtils(
force_offline=self.is_cli or self.settings.get_boolean("force-offline")
)
self.data_mgr = DataManager()
_offline = True
if check_connection:
_offline = not self.utils_conn.check_connection()
# validating user-defined Paths.bottles
if user_bottles_path := self.data_mgr.get(UserDataKeys.CustomBottlesPath):
if os.path.exists(user_bottles_path):
Paths.bottles = user_bottles_path
else:
logging.error(
f"Custom bottles path {user_bottles_path} does not exist! "
f"Falling back to default path."
)
# sub-managers
self.repository_manager = RepositoryManager(get_index=not _offline)
if self.repository_manager.aborted_connections > 0:
self.utils_conn.status = False
_offline = True
times["RepositoryManager"] = time.time()
self.versioning_manager = VersioningManager(self)
times["VersioningManager"] = time.time()
self.btrfs_subvolume_manager = BtrfsSubvolumeManager(self)
self.component_manager = ComponentManager(self, _offline)
self.installer_manager = InstallerManager(self, _offline)
self.dependency_manager = DependencyManager(self, _offline)
self.import_manager = ImportManager(self)
times["ImportManager"] = time.time()
self.steam_manager = SteamManager()
times["SteamManager"] = time.time()
# Initialize playtime tracker
self._initialize_playtime_tracker()
times["PlaytimeTracker"] = time.time()
# React to runtime changes in playtime preference when available
if hasattr(self.settings, "connect"):
try:
self.settings.connect(
"changed::playtime-enabled", self._on_playtime_enabled_changed
)
except Exception:
pass
# Subscribe to playtime signals (connect once per process)
if not Manager._playtime_signals_connected:
SignalManager.connect(Signals.ProgramStarted, self._on_program_started)
SignalManager.connect(Signals.ProgramFinished, self._on_program_finished)
Manager._playtime_signals_connected = True
if not self.is_cli:
times.update(self.checks(install_latest=False, first_run=True).data)
else:
logging.set_silent()
if "BOOT_TIME" in os.environ:
_temp_times = times.copy()
last = 0
times_str = "Boot times:"
for f, t in _temp_times.items():
if last == 0:
last = int(round(t))
continue
t = int(round(t))
times_str += f"\n\t - {f} took: {t - last}s"
last = t
logging.info(times_str)
def checks(
self,
install_latest=False,
first_run=False,
progress_callback: Optional[Callable[..., None]] = None,
) -> Result:
logging.info("Performing Bottles checks…")
rv = Result(status=True, data={})
steps: List[Tuple[Optional[str], str, Callable[[], bool | None]]] = [
("check_app_dirs", _("Preparing folders…"), self.check_app_dirs),
(
"check_dxvk",
_("Setting up DXVK…"),
lambda: self.check_dxvk(install_latest),
),
(
"check_vkd3d",
_("Setting up VKD3D…"),
lambda: self.check_vkd3d(install_latest),
),
(
"check_nvapi",
_("Setting up NVAPI…"),
lambda: self.check_nvapi(install_latest),
),
(
"check_latencyflex",
_("Setting up LatencyFleX…"),
lambda: self.check_latencyflex(install_latest),
),
(
"check_runtimes",
_("Preparing runtimes…"),
lambda: self.check_runtimes(install_latest),
),
(
"check_winebridge",
_("Preparing WineBridge…"),
lambda: self.check_winebridge(install_latest),
),
(
"check_runners",
_("Preparing runners…"),
lambda: self.check_runners(install_latest),
),
]
if first_run:
steps.extend(
[
(
None,
_("Organizing components…"),
self.organize_components,
),
(
None,
_("Cleaning temporary files…"),
self.__clear_temp,
),
]
)
steps.extend(
[
(
None,
_("Organizing dependencies…"),
self.organize_dependencies,
),
(
None,
_("Organizing installers…"),
self.organize_installers,
),
("check_bottles", _("Loading bottles…"), self.check_bottles),
]
)
total_steps = len(steps)
for index, (data_key, description, func) in enumerate(steps, start=1):
if progress_callback:
try:
progress_callback(
description=description,
current_step=index,
total_steps=total_steps,
completed=False,
)
except Exception as error: # pragma: no cover - defensive
logging.debug(f"Progress callback start failed: {error}")
result = func()
if result is False:
rv.set_status(False)
if progress_callback:
try:
progress_callback(
description=description,
current_step=index,
total_steps=total_steps,
completed=True,
)
except Exception as error: # pragma: no cover - defensive
logging.debug(f"Progress callback end failed: {error}")
if data_key:
rv.data[data_key] = time.time()
return rv
def __del__(self):
# best-effort shutdown of playtime tracker
try:
if hasattr(self, "playtime_tracker") and self.playtime_tracker:
self.playtime_tracker.shutdown()
except Exception:
pass
def _initialize_playtime_tracker(self) -> None:
playtime_enabled = self.settings.get_boolean("playtime-enabled")
playtime_interval = self.settings.get_int("playtime-heartbeat-interval")
tracker = ProcessSessionTracker(
enabled=playtime_enabled,
heartbeat_interval=playtime_interval if playtime_interval > 0 else 60,
)
tracker.recover_open_sessions()
self.playtime_tracker = tracker
def _on_playtime_enabled_changed(self, _settings, _key) -> None:
enabled = self.settings.get_boolean("playtime-enabled")
if not enabled:
if (
getattr(self, "playtime_tracker", None)
and self.playtime_tracker.enabled
):
self._launch_to_session.clear()
self.playtime_tracker.disable_tracking()
return
if getattr(self, "playtime_tracker", None) and self.playtime_tracker.enabled:
return
self._initialize_playtime_tracker()
# Playtime signal handlers
_launch_to_session: Dict[str, int] = {}
# Public Playtime API (wrap tracker with Result)
def playtime_start(
self,
*,
bottle_id: str,
bottle_name: str,
bottle_path: str,
program_name: str,
program_path: str,
) -> Result[int]:
try:
sid = self.playtime_tracker.start_session(
bottle_id=bottle_id,
bottle_name=bottle_name,
bottle_path=bottle_path,
program_name=program_name,
program_path=program_path,
)
return Result(True, data=sid)
except Exception as e:
logging.exception(e)
return Result(False, message=str(e))
def playtime_finish(
self,
session_id: int,
*,
status: str = "success",
ended_at: Optional[int] = None,
) -> Result[None]:
try:
if status == "success":
self.playtime_tracker.mark_exit(
session_id, status="success", ended_at=ended_at
)
else:
self.playtime_tracker.mark_failure(session_id, status=status)
return Result(True)
except Exception as e:
logging.exception(e)
return Result(False, message=str(e))
def _on_program_started(self, data: Optional[Result] = None) -> None:
try:
if not data or not data.data:
return
payload: ProcessStartedPayload = data.data # type: ignore
logging.debug(
f"Playtime signal: started launch_id={payload.launch_id} bottle={payload.bottle_name} program={payload.program_name}"
)
res = self.playtime_start(
bottle_id=payload.bottle_id,
bottle_name=payload.bottle_name,
bottle_path=payload.bottle_path,
program_name=payload.program_name,
program_path=payload.program_path,
)
if not res.ok:
return
sid = int(res.data or -1)
self._launch_to_session[payload.launch_id] = sid
config = self._get_payload_config(payload)
if config:
RegistryRuleManager.apply_rules(config, trigger="start_program")
except Exception:
pass
def _on_program_finished(self, data: Optional[Result] = None) -> None:
try:
if not data or not data.data:
return
payload: ProcessFinishedPayload = data.data # type: ignore
sid = self._launch_to_session.pop(payload.launch_id, -1)
if sid and sid > 0:
status = payload.status
ended_at = int(payload.ended_at or time.time())
logging.debug(
f"Playtime signal: finished launch_id={payload.launch_id} status={status} sid={sid}"
)
self.playtime_finish(sid, status=status, ended_at=ended_at)
config = self._get_payload_config(payload)
if config:
RegistryRuleManager.apply_rules(config, trigger="stop_program")
except Exception:
pass
def _get_payload_config(self, payload) -> Optional[BottleConfig]:
config = self.local_bottles.get(payload.bottle_name)
if isinstance(config, BottleConfig):
return config
try:
config_path = os.path.join(payload.bottle_path, "bottle.yml")
except Exception:
return None
loaded = BottleConfig.load(config_path)
if loaded.status:
return loaded.data
return None
def __clear_temp(self, force: bool = False):
"""Clears the temp directory if user setting allows it. Use the force
parameter to force clearing the directory.
"""
if self.settings.get_boolean("temp") or force:
try:
shutil.rmtree(Paths.temp)
os.makedirs(Paths.temp, exist_ok=True)
logging.info("Temp directory cleaned successfully!")
except FileNotFoundError:
self.check_app_dirs()
def get_cache_details(self) -> dict:
self.check_app_dirs()
file_utils = FileUtils()
temp_size_bytes = file_utils.get_path_size(Paths.temp, human=False)
templates = []
templates_size_bytes = 0
for template in TemplateManager.get_templates():
template_uuid = template.get("uuid", "")
template_path = os.path.join(Paths.templates, template_uuid)
size_bytes = file_utils.get_path_size(template_path, human=False)
templates_size_bytes += size_bytes
templates.append(
{
"uuid": template_uuid,
"env": template.get("env", ""),
"created": template.get("created", ""),
"size": file_utils.get_human_size(size_bytes),
"size_bytes": size_bytes,
}
)
total_size_bytes = temp_size_bytes + templates_size_bytes
return {
"temp": {
"path": Paths.temp,
"size": file_utils.get_human_size(temp_size_bytes),
"size_bytes": temp_size_bytes,
},
"templates": templates,
"templates_size": file_utils.get_human_size(templates_size_bytes),
"templates_size_bytes": templates_size_bytes,
"total_size": file_utils.get_human_size(total_size_bytes),
"total_size_bytes": total_size_bytes,
}
def clear_temp_cache(self) -> Result[None]:
try:
self.__clear_temp(force=True)
except Exception as ex:
logging.error(f"Failed to clear temp cache: {ex}")
return Result(False, message=str(ex))
return Result(True)
def clear_template_cache(self, template_uuid: str) -> Result[None]:
self.check_app_dirs()
try:
TemplateManager.delete_template(template_uuid)
except Exception as ex:
logging.error(f"Failed to clear template cache: {ex}")
return Result(False, message=str(ex))
return Result(True)
def clear_templates_cache(self) -> Result[None]:
self.check_app_dirs()
try:
for template in TemplateManager.get_templates():
TemplateManager.delete_template(template.get("uuid", ""))
except Exception as ex:
logging.error(f"Failed to clear templates cache: {ex}")
return Result(False, message=str(ex))
return Result(True)
def clear_all_caches(self) -> Result[None]:
temp_result = self.clear_temp_cache()
if not temp_result.ok:
return temp_result
templates_result = self.clear_templates_cache()
if not templates_result.ok:
return templates_result
return Result(True)
def update_bottles(self, silent: bool = False):
"""Checks for new bottles and update the list view."""
self.check_bottles(silent)
SignalManager.send(Signals.ManagerLocalBottlesLoaded)
def check_app_dirs(self):
"""
Checks for the existence of the bottles' directories, and creates them
if they don't exist.
"""
if not os.path.isdir(Paths.runners):
logging.info("Runners path doesn't exist, creating now.")
os.makedirs(Paths.runners, exist_ok=True)
if not os.path.isdir(Paths.runtimes):
logging.info("Runtimes path doesn't exist, creating now.")
os.makedirs(Paths.runtimes, exist_ok=True)
if not os.path.isdir(Paths.winebridge):
logging.info("WineBridge path doesn't exist, creating now.")
os.makedirs(Paths.winebridge, exist_ok=True)
if not os.path.isdir(Paths.bottles):
logging.info("Bottles path doesn't exist, creating now.")
os.makedirs(Paths.bottles, exist_ok=True)
if (
self.settings.get_boolean("steam-proton-support")
and self.steam_manager.is_steam_supported
):
if not os.path.isdir(Paths.steam):
logging.info("Steam path doesn't exist, creating now.")
os.makedirs(Paths.steam, exist_ok=True)
if not os.path.isdir(Paths.dxvk):
logging.info("Dxvk path doesn't exist, creating now.")
os.makedirs(Paths.dxvk, exist_ok=True)
if not os.path.isdir(Paths.vkd3d):
logging.info("Vkd3d path doesn't exist, creating now.")
os.makedirs(Paths.vkd3d, exist_ok=True)
if not os.path.isdir(Paths.nvapi):
logging.info("Nvapi path doesn't exist, creating now.")
os.makedirs(Paths.nvapi, exist_ok=True)
if not os.path.isdir(Paths.templates):
logging.info("Templates path doesn't exist, creating now.")
os.makedirs(Paths.templates, exist_ok=True)
if not os.path.isdir(Paths.temp):
logging.info("Temp path doesn't exist, creating now.")
os.makedirs(Paths.temp, exist_ok=True)
if not os.path.isdir(Paths.latencyflex):
logging.info("LatencyFleX path doesn't exist, creating now.")
os.makedirs(Paths.latencyflex, exist_ok=True)
@RunAsync.run_async
def organize_components(self):
"""Get components catalog and organizes into supported_ lists."""
EventManager.wait(Events.ComponentsFetching)
catalog = self.component_manager.fetch_catalog()
if len(catalog) == 0:
EventManager.done(Events.ComponentsOrganizing)
logging.info("No components found.")
return
self.supported_wine_runners = catalog["wine"]
self.supported_proton_runners = catalog["proton"]
self.supported_runtimes = catalog["runtimes"]
self.supported_winebridge = catalog["winebridge"]
self.supported_dxvk = catalog["dxvk"]
self.supported_vkd3d = catalog["vkd3d"]
self.supported_nvapi = catalog["nvapi"]
self.supported_latencyflex = catalog["latencyflex"]
EventManager.done(Events.ComponentsOrganizing)
@RunAsync.run_async
def organize_dependencies(self):
"""Organizes dependencies into supported_dependencies."""
EventManager.wait(Events.DependenciesFetching)
catalog = self.dependency_manager.fetch_catalog()
if len(catalog) == 0:
EventManager.done(Events.DependenciesOrganizing)
logging.info("No dependencies found!")
return
self.supported_dependencies = catalog
EventManager.done(Events.DependenciesOrganizing)
@RunAsync.run_async
def organize_installers(self):
"""Organizes installers into supported_installers."""
EventManager.wait(Events.InstallersFetching)
catalog = self.installer_manager.fetch_catalog()
if len(catalog) == 0:
EventManager.done(Events.InstallersOrganizing)
logging.info("No installers found!")
return
self.supported_installers = catalog
EventManager.done(Events.InstallersOrganizing)
def remove_dependency(self, config: BottleConfig, dependency: list):
"""Uninstall a dependency and remove it from the bottle config."""
dependency = dependency[0]
logging.info(f"Removing {dependency} dependency from {config.Name}")
uninstallers = config.Uninstallers
# run dependency uninstaller if available
if dependency in uninstallers:
uninstaller = uninstallers[dependency]
Uninstaller(config).from_name(uninstaller)
# remove dependency from bottle configuration
if dependency in config.Installed_Dependencies:
config.Installed_Dependencies.remove(dependency)
self.update_config(
config, key="Installed_Dependencies", value=config.Installed_Dependencies
)
return Result(status=True, data={"removed": True})
def check_runners(self, install_latest: bool = True) -> bool:
"""
Check for available runners (both system and Bottles) and install
the latest version if install_latest is True. It also masks the
winemenubuilder tool.
"""
runners = glob(f"{Paths.runners}/*/")
self.runners_available, runners_available = [], []
# lock winemenubuilder.exe
for runner in runners:
if not SteamUtils.is_proton(runner):
winemenubuilder_paths = [
f"{runner}lib64/wine/x86_64-windows/winemenubuilder.exe",
f"{runner}lib/wine/x86_64-windows/winemenubuilder.exe",
f"{runner}lib32/wine/i386-windows/winemenubuilder.exe",
f"{runner}lib/wine/i386-windows/winemenubuilder.exe",
]
for winemenubuilder in winemenubuilder_paths:
if os.path.isfile(winemenubuilder):
os.rename(winemenubuilder, f"{winemenubuilder}.lock")
# check system wine
if shutil.which("wine") is not None:
"""
If the Wine command is available, get the runner version
and add it to the runners_available list.
"""
version = (
subprocess.Popen("wine --version", stdout=subprocess.PIPE, shell=True)
.communicate()[0]
.decode("utf-8")
)
version = "sys-" + version.split("\n")[0].split(" ")[0]
runners_available.append(version)
# check bottles runners
for runner in runners:
_runner = os.path.basename(os.path.normpath(runner))
runners_available.append(_runner)
runners_available = self.__sort_runners(runners_available, "")
runners_order = {
"soda": [],
"caffe": [],
"vaniglia": [],
"lutris": [],
"others": [],
"sys-": [],
}
for i in runners_available:
for r in runners_order:
if i.startswith(r):
runners_order[r].append(i)
break
else:
runners_order["others"].append(i)
self.runners_available = [x for l in list(runners_order.values()) for x in l]
if len(self.runners_available) > 0:
logging.info(
"Runners found:\n - {0}".format("\n - ".join(self.runners_available))
)
tmp_runners = [x for x in self.runners_available if not x.startswith("sys-")]
if len(tmp_runners) == 0 and install_latest:
logging.warning("No managed runners found.")
if self.utils_conn.check_connection():
# if connected, install the latest runner from repository
try:
if not self.settings.get_boolean("release-candidate"):
tmp_runners = []
for runner in self.supported_wine_runners.items():
if runner[1]["Channel"] not in ["rc", "unstable"]:
tmp_runners.append(runner)
break
runner_name = next(iter(tmp_runners))[0]
else:
tmp_runners = self.supported_wine_runners
runner_name = next(iter(tmp_runners))
self.component_manager.install("runner", runner_name)
except StopIteration:
return False
else:
return False
return True
def check_runtimes(self, install_latest: bool = True) -> bool:
self.runtimes_available = []
if "FLATPAK_ID" in os.environ:
self.runtimes_available = ["flatpak-managed"]
return True
runtimes = os.listdir(Paths.runtimes)
if len(runtimes) == 0:
if install_latest and self.utils_conn.check_connection():
logging.warning("No runtime found.")
try:
version = next(iter(self.supported_runtimes))
return self.component_manager.install("runtime", version)
except StopIteration:
return False
return False
runtime = runtimes[0] # runtimes cannot be more than one
manifest = os.path.join(Paths.runtimes, runtime, "manifest.yml")
if os.path.exists(manifest):
with open(manifest, "r") as f:
data = yaml.load(f)
version = data.get("version")
if version:
version = f"runtime-{version}"
self.runtimes_available = [version]
return True
return False
def __winebridge_status(self) -> tuple[Optional[str], Optional[str], bool]:
def _is_newer(candidate: str, current: str) -> bool:
versions = [candidate, current]
try:
sorted_versions = sort_by_version(list(versions))
except ValueError:
sorted_versions = sorted(versions, reverse=True)
return sorted_versions[0] == candidate and candidate != current
self.winebridge_available = []
winebridge = os.listdir(Paths.winebridge)
latest_supported = None
if self.supported_winebridge:
try:
latest_supported = sort_by_version(
list(self.supported_winebridge.keys())
)[0]
except ValueError:
latest_supported = sorted(
list(self.supported_winebridge.keys()), reverse=True
)[0]
version_file = os.path.join(Paths.winebridge, "VERSION")
installed_identifier = None
if os.path.exists(version_file):
with open(version_file, "r") as f:
version = f.read().strip()
if version:
installed_identifier = f"winebridge-{version}"
self.winebridge_available = [installed_identifier]
missing_installation = len(winebridge) == 0 or not installed_identifier
needs_latest = False
if latest_supported:
needs_latest = (
missing_installation
or _is_newer(latest_supported, installed_identifier)
)
return latest_supported, installed_identifier, needs_latest
def winebridge_update_status(self) -> dict:
latest_supported, installed_identifier, needs_latest = self.__winebridge_status()
return {
"latest_supported": latest_supported,
"installed_identifier": installed_identifier,
"needs_latest": needs_latest,
"missing": not installed_identifier,
}
def check_winebridge(
self, install_latest: bool = True, update: bool = False
) -> bool:
latest_supported, installed_identifier, needs_latest = self.__winebridge_status()
can_install = install_latest or update
if can_install and needs_latest and latest_supported:
if not self.utils_conn.check_connection():
return False
logging.warning("WineBridge installation/update required.")
res = self.component_manager.install("winebridge", latest_supported)
if res.ok:
self.winebridge_available = [latest_supported]
return True
return False
if needs_latest and not can_install:
return False
return bool(self.winebridge_available)
def check_dxvk(self, install_latest: bool = True) -> bool:
res = self.__check_component("dxvk", install_latest)
if res:
self.dxvk_available = res
return res is not False
def check_vkd3d(self, install_latest: bool = True) -> bool:
res = self.__check_component("vkd3d", install_latest)
if res:
self.vkd3d_available = res
return res is not False
def check_nvapi(self, install_latest: bool = True) -> bool:
res = self.__check_component("nvapi", install_latest)
if res:
self.nvapi_available = res
return res is not False
def check_latencyflex(self, install_latest: bool = True) -> bool:
res = self.__check_component("latencyflex", install_latest)
if res:
self.latencyflex_available = res
return res is not False
def get_offline_components(
self, component_type: str, extra_name_check: str = ""
) -> list:
components = {
"dxvk": {
"available": self.dxvk_available,
"supported": self.supported_dxvk,
},
"vkd3d": {
"available": self.vkd3d_available,
"supported": self.supported_vkd3d,
},
"nvapi": {
"available": self.nvapi_available,
"supported": self.supported_nvapi,
},
"latencyflex": {
"available": self.latencyflex_available,
"supported": self.supported_latencyflex,
},
"runner": {
"available": self.runners_available,
"supported": self.supported_wine_runners,
},
"runner:proton": {
"available": self.runners_available,
"supported": self.supported_proton_runners,
},
}
if component_type not in components:
logging.warning(f"Unknown component type found: {component_type}")
raise ValueError("Component type not supported.")
component_list = components[component_type]
offline_components = list(
set(component_list["available"]).difference(
component_list["supported"].keys()
)
)
if component_type == "runner":
offline_components = [
runner
for runner in offline_components
if not runner.startswith("sys-")
and not SteamUtils.is_proton(ManagerUtils.get_runner_path(runner))
]
elif component_type == "runner:proton":
offline_components = [
runner
for runner in offline_components
if SteamUtils.is_proton(ManagerUtils.get_runner_path(runner))
]
if (
extra_name_check
and extra_name_check not in component_list["available"]
and extra_name_check not in component_list["supported"]
):
offline_components.append(extra_name_check)
try:
return sort_by_version(offline_components)
except ValueError:
return sorted(offline_components, reverse=True)
def __check_component(
self, component_type: str, install_latest: bool = True
) -> bool | list:
components = {
"dxvk": {
"available": self.dxvk_available,
"supported": self.supported_dxvk,
"path": Paths.dxvk,
},
"vkd3d": {
"available": self.vkd3d_available,
"supported": self.supported_vkd3d,
"path": Paths.vkd3d,
},
"nvapi": {
"available": self.nvapi_available,
"supported": self.supported_nvapi,
"path": Paths.nvapi,
},
"latencyflex": {
"available": self.latencyflex_available,
"supported": self.supported_latencyflex,
"path": Paths.latencyflex,
},
"runtime": {
"available": self.runtimes_available,
"supported": self.supported_runtimes,
"path": Paths.runtimes,
},
}
if component_type not in components:
logging.warning(f"Unknown component type found: {component_type}")
raise ValueError("Component type not supported.")
component = components[component_type]
component["available"] = os.listdir(component["path"])
if len(component["available"]) > 0:
logging.info(