summaryrefslogtreecommitdiff
path: root/py_modules/lsfg_vk/installation.py
blob: f7bfdafcb9aef4d33ec7f65ffe3032527a90f288 (plain)
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
import os
import shutil
import tarfile
import tempfile
import traceback
from pathlib import Path
from typing import Dict

from .base_service import BaseService
from .config_schema import ConfigurationManager, DEFAULT_PROFILE_NAME, ProfileData
from .constants import (
    ARCHIVE_FILENAME,
    BIN_DIR,
    CLI_FILENAME,
    JSON_FILENAME,
    JSON_X86_FILENAME,
    LEGACY_JSON_FILENAME,
    LEGACY_LIB_FILENAME,
    LIB_FILENAME,
    LIB_X86_FILENAME,
    LOCAL_SHARE,
    UI_DESKTOP_FILENAME,
    UI_FILENAME,
    UI_ICON_FILENAME,
)
from .runtime_service import RuntimeService
from .steam_service import SteamService
from .types import InstallationCheckResponse, InstallationResponse, UninstallationResponse


class InstallationService(BaseService):
    def __init__(
        self,
        logger=None,
        runtime_service: RuntimeService = None,
        steam_service: SteamService = None,
    ):
        super().__init__(logger)
        self.runtime_service = runtime_service or RuntimeService(logger=self.log)
        self.steam_service = steam_service or SteamService(logger=self.log)
        self.lib_file = self.local_lib_dir / LIB_FILENAME
        self.lib_x86_file = self.local_lib_dir / LIB_X86_FILENAME
        self.json_file = self.local_share_dir / JSON_FILENAME
        self.json_x86_file = self.local_share_dir / JSON_X86_FILENAME
        self.cli_file = self.local_bin_dir / CLI_FILENAME
        self.legacy_lib_file = self.local_lib_dir / LEGACY_LIB_FILENAME
        self.legacy_json_file = self.local_share_dir / LEGACY_JSON_FILENAME

    def install(self) -> InstallationResponse:
        try:
            plugin_dir = Path(__file__).parent.parent.parent
            archive_path = plugin_dir / BIN_DIR / ARCHIVE_FILENAME
            if not archive_path.exists():
                raise FileNotFoundError(f"{ARCHIVE_FILENAME} not found at {archive_path}")

            self._ensure_directories()
            profile_data = self._prepare_config()
            self._install_archive(archive_path)
            config_content = ConfigurationManager.generate_toml_content_multi_profile(profile_data)
            self.runtime_service.validate_config_content(config_content)
            self._write_file(
                self.config_file_path,
                config_content,
                0o644,
            )
            self._create_lsfg_launch_script(profile_data)
            self._remove_legacy_layer_files()
            return self._success_response(InstallationResponse, "lsfg-vk 2.0.0 installed successfully")
        except Exception as error:
            self.log.error(f"Error installing lsfg-vk: {error}")
            return self._error_response(InstallationResponse, str(error), message="")

    def _payload_destinations(self) -> Dict[str, tuple[Path, int]]:
        return {
            f"bin/{CLI_FILENAME}": (self.cli_file, 0o755),
            f"bin/{UI_FILENAME}": (self.local_bin_dir / UI_FILENAME, 0o755),
            f"lib/{LIB_FILENAME}": (self.lib_file, 0o644),
            f"lib/{LIB_X86_FILENAME}": (self.lib_x86_file, 0o644),
            f"share/vulkan/implicit_layer.d/{JSON_FILENAME}": (self.json_file, 0o644),
            f"share/vulkan/implicit_layer.d/{JSON_X86_FILENAME}": (self.json_x86_file, 0o644),
            f"share/applications/{UI_DESKTOP_FILENAME}": (
                self.user_home / LOCAL_SHARE / "applications" / UI_DESKTOP_FILENAME,
                0o644,
            ),
            f"share/icons/hicolor/256x256/apps/{UI_ICON_FILENAME}": (
                self.user_home / LOCAL_SHARE / "icons" / "hicolor" / "256x256" / "apps" / UI_ICON_FILENAME,
                0o644,
            ),
        }

    def _install_archive(self, archive_path: Path) -> None:
        destinations = self._payload_destinations()
        found = set()
        with tarfile.open(archive_path, "r:*") as archive:
            members = {
                member.name.removeprefix("./"): member
                for member in archive.getmembers()
                if member.isfile()
            }
            for source_path, (destination, mode) in destinations.items():
                member = members.get(source_path)
                if member is None:
                    continue
                source = archive.extractfile(member)
                if source is None:
                    continue
                destination.parent.mkdir(parents=True, exist_ok=True)
                temporary_path = None
                try:
                    with tempfile.NamedTemporaryFile(
                        mode="wb",
                        dir=destination.parent,
                        prefix=f".{destination.name}.",
                        delete=False,
                    ) as temporary_file:
                        temporary_path = Path(temporary_file.name)
                        with source:
                            shutil.copyfileobj(source, temporary_file)
                        temporary_file.flush()
                        os.fsync(temporary_file.fileno())
                    temporary_path.chmod(mode)
                    os.replace(temporary_path, destination)
                    found.add(source_path)
                except Exception:
                    if temporary_path is not None:
                        temporary_path.unlink(missing_ok=True)
                    raise

        missing = sorted(set(destinations) - found)
        if missing:
            raise OSError("Archive is missing required files: " + ", ".join(missing))

    def _prepare_config(self) -> ProfileData:
        if self.config_file_path.exists():
            content = self.config_file_path.read_text(encoding="utf-8")
            legacy = ConfigurationManager.is_legacy_v1(content)
            profile_data = ConfigurationManager.parse_toml_content_multi_profile(content)
            if legacy:
                backup_path = self.config_file_path.with_name(f"{self.config_file_path.name}.v1.bak")
                if not backup_path.exists():
                    self._write_file(backup_path, content, 0o644)
        else:
            default = dict(ConfigurationManager.get_defaults())
            profile_data = ProfileData(
                current_profile=DEFAULT_PROFILE_NAME,
                profiles={DEFAULT_PROFILE_NAME: default},
                global_config={
                    "dll": default.get("dll", ""),
                    "no_fp16": default.get("no_fp16", False),
                },
            )

        self._resolve_dll_path(profile_data)
        defaults = dict(ConfigurationManager.get_defaults())
        for profile_name, raw_profile in list(profile_data["profiles"].items()):
            profile_data["profiles"][profile_name] = ConfigurationManager.validate_config(
                {**defaults, **raw_profile, **profile_data["global_config"]}
            )
        profile_data["current_profile"] = DEFAULT_PROFILE_NAME
        return profile_data

    def _resolve_dll_path(self, profile_data: ProfileData) -> bool:
        current_path = str(profile_data["global_config"].get("dll") or "")
        if current_path and Path(current_path).is_file():
            return False

        dll_path = self.steam_service.find_lsfg_vk_dll()
        if dll_path and current_path != dll_path:
            profile_data["global_config"]["dll"] = dll_path
            return True
        return False

    def _create_lsfg_launch_script(self, profile_data: ProfileData) -> None:
        from .configuration import ConfigurationService

        configuration_service = ConfigurationService(logger=self.log)
        configuration_service.user_home = self.user_home
        configuration_service.config_dir = self.config_dir
        configuration_service.config_file_path = self.config_file_path
        configuration_service.lsfg_script_path = self.lsfg_launch_script_path
        self._write_file(
            self.lsfg_launch_script_path,
            configuration_service._generate_script_content_for_profile(profile_data),
            0o755,
        )

    def _remove_legacy_layer_files(self) -> None:
        for path in (self.legacy_lib_file, self.legacy_json_file):
            self._remove_if_exists(path)

    def needs_v2_migration(self) -> bool:
        legacy_layer = self.legacy_lib_file.exists() or self.legacy_json_file.exists()
        legacy_config = False
        if self.config_file_path.exists():
            try:
                legacy_config = ConfigurationManager.is_legacy_v1(
                    self.config_file_path.read_text(encoding="utf-8")
                )
            except OSError:
                legacy_config = False
        if legacy_layer or legacy_config:
            return True
        try:
            if self.config_file_path.exists():
                data = ConfigurationManager.parse_toml_content_multi_profile(
                    self.config_file_path.read_text(encoding="utf-8")
                )
                configured = str(data["global_config"].get("dll") or "")
                if (not configured or not Path(configured).is_file()) and self.steam_service.find_lsfg_vk_dll():
                    return True
            return not self.runtime_service.is_healthy()
        except Exception:
            return True

    def get_launch_script_path(self) -> str:
        return str(self.lsfg_launch_script_path)

    def check_installation(self) -> InstallationCheckResponse:
        try:
            script_exists = self.lsfg_launch_script_path.exists()
            installation_error = None
            try:
                installed = script_exists and self.runtime_service.is_healthy()
            except Exception as error:
                installed = False
                installation_error = str(error)

            lossless_scaling = self.runtime_service.check_lossless_scaling()
            return {
                "installed": installed,
                "lossless_scaling_installed": bool(lossless_scaling["installed"]),
                "lossless_scaling_status": str(lossless_scaling["status"]),
                "error": installation_error,
            }
        except Exception as error:
            return {
                "installed": False,
                "lossless_scaling_installed": False,
                "lossless_scaling_status": str(error),
                "error": str(error),
            }

    def uninstall(self) -> UninstallationResponse:
        try:
            removed = []
            for path in (
                self.lib_file,
                self.lib_x86_file,
                self.json_file,
                self.json_x86_file,
                self.cli_file,
                self.local_bin_dir / UI_FILENAME,
                self.user_home / LOCAL_SHARE / "applications" / UI_DESKTOP_FILENAME,
                self.user_home / LOCAL_SHARE / "icons" / "hicolor" / "256x256" / "apps" / UI_ICON_FILENAME,
                self.legacy_lib_file,
                self.legacy_json_file,
                self.lsfg_launch_script_path,
            ):
                if self._remove_if_exists(path):
                    removed.append(str(path))
            if not removed:
                return self._success_response(
                    UninstallationResponse,
                    "No lsfg-vk files found to remove",
                    removed_files=None,
                )
            return self._success_response(
                UninstallationResponse,
                f"lsfg-vk uninstalled successfully. Removed {len(removed)} files.",
                removed_files=removed,
            )
        except Exception as error:
            return self._error_response(
                UninstallationResponse,
                str(error),
                message="",
                removed_files=None,
            )

    def cleanup_on_uninstall(self) -> None:
        try:
            self.uninstall()
        except Exception as error:
            self.log.error(f"Error cleaning up lsfg-vk files during uninstall: {error}")
            self.log.error(traceback.format_exc())