From c9be32287ad5b72fcd86b10fa726d09dbd97d7fd Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sun, 6 Sep 2026 17:09:54 -0400 Subject: refactor: organize plugin into native tabs --- defaults/i18n/ja.json | 13 - defaults/i18n/ko.json | 13 - defaults/i18n/template.json | 13 - py_modules/lsfg_vk/base_service.py | 6 +- py_modules/lsfg_vk/configuration.py | 64 ++-- py_modules/lsfg_vk/flatpak_service.py | 21 +- py_modules/lsfg_vk/installation.py | 23 +- py_modules/lsfg_vk/plugin.py | 48 +-- py_modules/lsfg_vk/steam_service.py | 77 ++++- src/api/lsfgApi.ts | 12 +- src/components/ConfigFileTab.tsx | 46 +++ src/components/ConfigurationTab.tsx | 54 ++++ src/components/Content.tsx | 223 ++++++------- src/components/FlatpaksModal.tsx | 460 --------------------------- src/components/FlatpaksTab.tsx | 195 ++++++++++++ src/components/GameConfigurationSelector.tsx | 2 +- src/components/NerdStuffModal.tsx | 148 --------- src/components/SetupTab.tsx | 47 +++ src/components/SmartClipboardButton.tsx | 91 ------ src/components/UsageInstructions.tsx | 69 ---- src/components/index.ts | 8 +- src/hooks/useGameConfiguration.ts | 26 +- src/i18n/languages.json | 51 +-- src/styles.ts | 34 ++ 24 files changed, 633 insertions(+), 1111 deletions(-) create mode 100644 src/components/ConfigFileTab.tsx create mode 100644 src/components/ConfigurationTab.tsx delete mode 100644 src/components/FlatpaksModal.tsx create mode 100644 src/components/FlatpaksTab.tsx delete mode 100644 src/components/NerdStuffModal.tsx create mode 100644 src/components/SetupTab.tsx delete mode 100644 src/components/SmartClipboardButton.tsx delete mode 100644 src/components/UsageInstructions.tsx create mode 100644 src/styles.ts diff --git a/defaults/i18n/ja.json b/defaults/i18n/ja.json index 08c87df..7b97bc5 100644 --- a/defaults/i18n/ja.json +++ b/defaults/i18n/ja.json @@ -57,21 +57,12 @@ "FLATPAK_ERROR": "エラー", "FLATPAK_ERROR_STATUS": "拡張ステータスの確認に失敗しました", "FLATPAK_ERROR_APPS": "Flatpakアプリケーションの読み込みに失敗しました", - "FLATPAK_STEAM_CONFIG_TITLE": "Steam設定", - "FLATPAK_STEAM_CONFIG_HEADER": "Steam Flatpakショートカットの設定", - "FLATPAK_STEAM_CONFIG_DESC": "Steamでflatpakゲームを開き、歯車アイコンをクリックしてください。", - "FLATPAK_STEAM_CONFIG_IMPORTANT": "重要: 起動オプションではなくターゲット(TARGET)に設定してください", - "FLATPAK_STEP_TRY_FIRST": "まず試す:", - "FLATPAK_STEP_TRY_FULL_PATH": "うまくいかない場合、フルパスを試す:", - "FLATPAK_STEP_FINAL": "最終的な結果はこのようになります:", "FLATPAK_CLOSE": "閉じる", "NERD_LOADING": "情報を読み込み中...", "NERD_DLL_PATH": "DLLパス", "NERD_NOT_AVAILABLE": "利用不可", "NERD_DLL_HASH": "DLL SHA256ハッシュ", "NERD_DETECTION_SOURCE": "検出ソース", - "NERD_LAUNCH_SCRIPT": "起動スクリプト", - "NERD_SCRIPT_NOT_FOUND_PREFIX": "スクリプトが見つかりません:", "NERD_PATH_PREFIX": "パス:", "NERD_NO_CONTENT": "コンテンツなし", "NERD_CONFIG_FILE": "設定ファイル", @@ -97,11 +88,7 @@ "PROFILE_DELETE_BTN": "削除", "PROFILE_CANNOT_RENAME_TITLE": "デフォルトプロファイルの名前は変更できません", "PROFILE_CANNOT_RENAME_MSG": "デフォルトプロファイルの名前は変更できません", - "USAGE_TITLE": "使用方法", - "USAGE_DESC": "「起動オプションをコピー」ボタンをクリックし、Steamゲームの起動オプションに貼り付けてフレーム生成を有効化してください。", - "USAGE_CONFIG_NOTE": "設定は~/.config/lsfg-vk/conf.tomlに保存され、ゲーム実行中もホットリロードされます。", "CLIPBOARD_COPIED": "クリップボードにコピーしました", "CLIPBOARD_COPYING": "コピー中...", - "CLIPBOARD_COPY_LAUNCH": "起動オプションをコピー", "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" } diff --git a/defaults/i18n/ko.json b/defaults/i18n/ko.json index 5e6f2b7..cbc3a8e 100644 --- a/defaults/i18n/ko.json +++ b/defaults/i18n/ko.json @@ -57,21 +57,12 @@ "FLATPAK_ERROR": "오류", "FLATPAK_ERROR_STATUS": "확장 상태 확인 실패", "FLATPAK_ERROR_APPS": "Flatpak 애플리케이션 로드 실패", - "FLATPAK_STEAM_CONFIG_TITLE": "Steam 설정", - "FLATPAK_STEAM_CONFIG_HEADER": "Steam Flatpak 단축키 설정", - "FLATPAK_STEAM_CONFIG_DESC": "Steam에서 Flatpak 게임을 열고 톱니바퀴를 클릭하세요.", - "FLATPAK_STEAM_CONFIG_IMPORTANT": "중요: 실행 옵션이 아닌 대상(TARGET)에 설정하세요", - "FLATPAK_STEP_TRY_FIRST": "먼저 시도:", - "FLATPAK_STEP_TRY_FULL_PATH": "작동하지 않으면 전체 경로 시도:", - "FLATPAK_STEP_FINAL": "최종 결과는 다음과 같아야 합니다:", "FLATPAK_CLOSE": "닫기", "NERD_LOADING": "정보 불러오는 중...", "NERD_DLL_PATH": "DLL 경로", "NERD_NOT_AVAILABLE": "사용 불가", "NERD_DLL_HASH": "DLL SHA256 해시", "NERD_DETECTION_SOURCE": "감지 소스", - "NERD_LAUNCH_SCRIPT": "실행 스크립트", - "NERD_SCRIPT_NOT_FOUND_PREFIX": "스크립트 없음:", "NERD_PATH_PREFIX": "경로:", "NERD_NO_CONTENT": "내용 없음", "NERD_CONFIG_FILE": "설정 파일", @@ -97,11 +88,7 @@ "PROFILE_DELETE_BTN": "삭제", "PROFILE_CANNOT_RENAME_TITLE": "기본 프로필 이름 변경 불가", "PROFILE_CANNOT_RENAME_MSG": "기본 프로필의 이름은 변경할 수 없습니다", - "USAGE_TITLE": "사용 방법", - "USAGE_DESC": "\"실행 옵션 복사\" 버튼을 클릭한 후, Steam 게임의 실행 옵션에 붙여넣어 프레임 생성을 활성화하세요.", - "USAGE_CONFIG_NOTE": "설정은 ~/.config/lsfg-vk/conf.toml에 저장되며 게임 실행 중에도 즉시 반영됩니다.", "CLIPBOARD_COPIED": "클립보드에 복사됨", "CLIPBOARD_COPYING": "복사 중...", - "CLIPBOARD_COPY_LAUNCH": "실행 옵션 복사", "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" } diff --git a/defaults/i18n/template.json b/defaults/i18n/template.json index cb53b95..b9dfcc5 100644 --- a/defaults/i18n/template.json +++ b/defaults/i18n/template.json @@ -57,21 +57,12 @@ "FLATPAK_ERROR": "Error", "FLATPAK_ERROR_STATUS": "Failed to check extension status", "FLATPAK_ERROR_APPS": "Failed to load Flatpak applications", - "FLATPAK_STEAM_CONFIG_TITLE": "Steam Configuration", - "FLATPAK_STEAM_CONFIG_HEADER": "Configure Steam Flatpak Shortcuts", - "FLATPAK_STEAM_CONFIG_DESC": "In Steam, open your flatpak game and click the cog wheel.", - "FLATPAK_STEAM_CONFIG_IMPORTANT": "IMPORTANT: Set this in TARGET (NOT LAUNCH OPTIONS)", - "FLATPAK_STEP_TRY_FIRST": "Try first:", - "FLATPAK_STEP_TRY_FULL_PATH": "If that doesn't work, try full path:", - "FLATPAK_STEP_FINAL": "Final result should look like:", "FLATPAK_CLOSE": "Close", "NERD_LOADING": "Loading information...", "NERD_DLL_PATH": "DLL Path", "NERD_NOT_AVAILABLE": "Not available", "NERD_DLL_HASH": "DLL SHA256 Hash", "NERD_DETECTION_SOURCE": "Detection Source", - "NERD_LAUNCH_SCRIPT": "Launch Script", - "NERD_SCRIPT_NOT_FOUND_PREFIX": "Script not found:", "NERD_PATH_PREFIX": "Path:", "NERD_NO_CONTENT": "No content", "NERD_CONFIG_FILE": "Configuration File", @@ -97,11 +88,7 @@ "PROFILE_DELETE_BTN": "Delete", "PROFILE_CANNOT_RENAME_TITLE": "Cannot rename default profile", "PROFILE_CANNOT_RENAME_MSG": "The default profile cannot be renamed", - "USAGE_TITLE": "Usage Instructions", - "USAGE_DESC": "Click \"Copy Launch Option\" button, then paste it into your Steam game's launch options to enable frame generation.", - "USAGE_CONFIG_NOTE": "The configuration is stored in ~/.config/lsfg-vk/conf.toml and hot-reloads while games are running.", "CLIPBOARD_COPIED": "Copied to clipboard", "CLIPBOARD_COPYING": "Copying...", - "CLIPBOARD_COPY_LAUNCH": "Copy Launch Option", "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" } diff --git a/py_modules/lsfg_vk/base_service.py b/py_modules/lsfg_vk/base_service.py index c4978c6..036dfc6 100644 --- a/py_modules/lsfg_vk/base_service.py +++ b/py_modules/lsfg_vk/base_service.py @@ -13,12 +13,12 @@ ResponseType = TypeVar("ResponseType", bound=Dict[str, Any]) class BaseService: def __init__(self, logger: Optional[Any] = None): self.log = decky.logger if logger is None else logger - self.user_home = Path.home() + decky_user_home = getattr(decky, "DECKY_USER_HOME", None) + self.user_home = Path(decky_user_home) if decky_user_home else Path.home() self.local_bin_dir = self.user_home / LOCAL_BIN self.local_lib_dir = self.user_home / LOCAL_LIB self.local_share_dir = self.user_home / VULKAN_LAYER_DIR - self.lsfg_script_path = self.user_home / SCRIPT_NAME - self.lsfg_launch_script_path = self.user_home / SCRIPT_NAME + self.legacy_script_path = self.user_home / SCRIPT_NAME self.config_dir = self.user_home / CONFIG_DIR self.config_file_path = self.config_dir / CONFIG_FILENAME diff --git a/py_modules/lsfg_vk/configuration.py b/py_modules/lsfg_vk/configuration.py index 2626a66..a4ee2cc 100644 --- a/py_modules/lsfg_vk/configuration.py +++ b/py_modules/lsfg_vk/configuration.py @@ -1,5 +1,4 @@ import re -import shlex from typing import Any, Dict from .base_service import BaseService @@ -29,10 +28,27 @@ class ConfigurationService(BaseService): self._write_file(self.config_file_path, content, 0o644) @staticmethod - def _game_profile_name(appid: str) -> str: - if not re.fullmatch(r"[0-9]+", str(appid)): - raise ValueError("appid must be numeric") - return f"game-{appid}" + def _profile_name(data: ProfileData, appid: str, game_name: str) -> str: + name = str(game_name).strip() + if not name: + raise ValueError("game name is required") + if name == DEFAULT_PROFILE_NAME: + name = f"{name} ({appid})" + existing = data["profiles"].get(name) + if existing is not None and str(appid) not in existing.get("active_in", []): + name = f"{name} ({appid})" + return name + + @staticmethod + def _profile_for_appid(data: ProfileData, appid: str): + return next( + ( + (name, profile) + for name, profile in data["profiles"].items() + if str(appid) in profile.get("active_in", []) + ), + (None, None), + ) @staticmethod def _public_config(config: Dict[str, Any]) -> Dict[str, Any]: @@ -52,7 +68,7 @@ class ConfigurationService(BaseService): games = [] for name, raw in data["profiles"].items(): active_in = raw.get("active_in", []) - if len(active_in) != 1 or not str(active_in[0]).isdigit(): + if len(active_in) != 1 or not re.fullmatch(r"-?[0-9]+", str(active_in[0])): continue games.append({"appid": str(active_in[0]), "profile": name, "config": self._public_config(raw)}) return self._success_response(dict, default=self._public_config(data["profiles"][DEFAULT_PROFILE_NAME]), games=games) @@ -63,20 +79,20 @@ class ConfigurationService(BaseService): def get_game_config(self, appid: str) -> Dict[str, Any]: try: data = self._get_profile_data() - name = self._game_profile_name(appid) - profile = data["profiles"].get(name) - if profile is None: - profile = next((value for value in data["profiles"].values() if str(appid) in value.get("active_in", [])), None) + _, profile = self._profile_for_appid(data, appid) return self._success_response(dict, appid=str(appid), exists=profile is not None, config=self._public_config(profile or data["profiles"][DEFAULT_PROFILE_NAME])) except Exception as error: return self._error_response(dict, str(error), appid=str(appid), exists=False, config=None) - def update_game_config(self, appid: str, config: Dict[str, Any]) -> Dict[str, Any]: + def update_game_config(self, appid: str, game_name: str, config: Dict[str, Any]) -> Dict[str, Any]: try: data = self._get_profile_data() - name = self._game_profile_name(appid) + old_name, _ = self._profile_for_appid(data, appid) + name = self._profile_name(data, appid, game_name) validated = self._public_config(config) validated["active_in"] = [str(appid)] + if old_name and old_name != name: + data["profiles"].pop(old_name, None) data["profiles"][name] = validated self._save_profile_data(data) return self._success_response(dict, appid=str(appid), config=validated) @@ -86,11 +102,9 @@ class ConfigurationService(BaseService): def reset_game_config(self, appid: str) -> Dict[str, Any]: try: data = self._get_profile_data() - name = self._game_profile_name(appid) - data["profiles"].pop(name, None) - for profile_name, profile in list(data["profiles"].items()): - if profile_name != DEFAULT_PROFILE_NAME and str(appid) in profile.get("active_in", []): - data["profiles"].pop(profile_name) + name, _ = self._profile_for_appid(data, appid) + if name: + data["profiles"].pop(name, None) self._save_profile_data(data) return self._success_response(dict, appid=str(appid), config=self._public_config(data["profiles"][DEFAULT_PROFILE_NAME])) except Exception as error: @@ -116,19 +130,3 @@ class ConfigurationService(BaseService): return self._success_response(dict, config=validated) except Exception as error: return self._error_response(dict, str(error), config=None) - - def update_lsfg_script(self, config: Dict[str, Any]) -> Dict[str, Any]: - return self.update_config_from_dict(config) - - def _generate_script_content_for_profile(self, profile_data: ProfileData) -> str: - return "#!/bin/bash\n" f"export LSFGVK_CONFIG={shlex.quote(str(self.config_file_path))}\n" 'exec "$@"\n' - - def _generate_script_content(self, config: Dict[str, Any]) -> str: - return self._generate_script_content_for_profile(self._default_data()) - - def update_lsfg_script_from_profile_data(self, profile_data: ProfileData) -> Dict[str, Any]: - try: - self._write_file(self.lsfg_script_path, self._generate_script_content_for_profile(profile_data), 0o755) - return self._success_response(dict) - except Exception as error: - return self._error_response(dict, str(error)) diff --git a/py_modules/lsfg_vk/flatpak_service.py b/py_modules/lsfg_vk/flatpak_service.py index 302efc7..6f8a596 100644 --- a/py_modules/lsfg_vk/flatpak_service.py +++ b/py_modules/lsfg_vk/flatpak_service.py @@ -1,4 +1,5 @@ import os +import pwd import shutil import subprocess from pathlib import Path @@ -26,6 +27,7 @@ class FlatpakService(BaseService): def _get_clean_env(self) -> Dict[str, str]: env = os.environ.copy() env.pop("LD_LIBRARY_PATH", None) + env["HOME"] = str(self.user_home) path_entries = [entry for entry in env.get("PATH", "").split(":") if entry] for entry in ("/usr/bin", "/usr/local/bin", "/bin"): if entry not in path_entries: @@ -33,6 +35,12 @@ class FlatpakService(BaseService): env["PATH"] = ":".join(path_entries) return env + def _flatpak_user(self) -> pwd.struct_passwd: + try: + return pwd.getpwuid(self.user_home.stat().st_uid) + except (KeyError, OSError) as error: + raise RuntimeError(f"Unable to resolve Flatpak user for {self.user_home}") from error + def check_flatpak_available(self) -> bool: env = self._get_clean_env() self.flatpak_command = shutil.which("flatpak", path=env["PATH"]) @@ -41,8 +49,15 @@ class FlatpakService(BaseService): def _run_flatpak_command(self, args: List[str], **kwargs): if self.flatpak_command is None and not self.check_flatpak_available(): raise FileNotFoundError("Flatpak command not available") + command = [self.flatpak_command, *args] + target_user = self._flatpak_user() + if os.geteuid() != target_user.pw_uid: + runuser = shutil.which("runuser", path=self._get_clean_env()["PATH"]) + if runuser is None: + raise FileNotFoundError("runuser command not available") + command = [runuser, "--user", target_user.pw_name, "--", *command] return subprocess.run( - [self.flatpak_command, *args], + command, env=self._get_clean_env(), **kwargs, ) @@ -181,7 +196,7 @@ class FlatpakService(BaseService): self.user_home / ".local/share/Steam/steamapps/common/Lossless Scaling/Lossless.dll" ), - "legacy_script": str(self.lsfg_launch_script_path), + "legacy_script": str(self.legacy_script_path), } def _check_app_override_status(self, app_id: str) -> Dict[str, bool]: @@ -200,7 +215,7 @@ class FlatpakService(BaseService): if not self.check_flatpak_available(): raise FileNotFoundError("Flatpak is not available on this system") result = self._run_flatpak_command( - ["list", "--user", "--app", "--columns=name,application"], + ["list", "--app", "--columns=name,application"], capture_output=True, text=True, check=True, diff --git a/py_modules/lsfg_vk/installation.py b/py_modules/lsfg_vk/installation.py index f7bfdaf..0a728c7 100644 --- a/py_modules/lsfg_vk/installation.py +++ b/py_modules/lsfg_vk/installation.py @@ -63,7 +63,6 @@ class InstallationService(BaseService): 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: @@ -170,20 +169,6 @@ class InstallationService(BaseService): 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) @@ -212,15 +197,11 @@ class InstallationService(BaseService): 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() + installed = self.runtime_service.is_healthy() except Exception as error: installed = False installation_error = str(error) @@ -254,7 +235,7 @@ class InstallationService(BaseService): 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, + self.legacy_script_path, ): if self._remove_if_exists(path): removed.append(str(path)) diff --git a/py_modules/lsfg_vk/plugin.py b/py_modules/lsfg_vk/plugin.py index 3b9a97f..8c788a8 100644 --- a/py_modules/lsfg_vk/plugin.py +++ b/py_modules/lsfg_vk/plugin.py @@ -103,8 +103,8 @@ class Plugin: async def get_game_config(self, appid: str) -> Dict[str, Any]: return self.configuration_service.get_game_config(appid) - async def update_game_config(self, appid: str, config: Dict[str, Any]) -> Dict[str, Any]: - return self.configuration_service.update_game_config(appid, config) + async def update_game_config(self, appid: str, game_name: str, config: Dict[str, Any]) -> Dict[str, Any]: + return self.configuration_service.update_game_config(appid, game_name, config) async def reset_game_config(self, appid: str) -> Dict[str, Any]: return self.configuration_service.reset_game_config(appid) @@ -178,18 +178,6 @@ class Plugin: """ return {"success": False, "error": "Use update_game_config with a Steam AppID"} - async def get_launch_option(self) -> Dict[str, Any]: - """Get the launch option that users need to set for their games - - Returns: - Dict containing the launch option string and instructions - """ - return { - "launch_option": "~/lsfg %command%", - "instructions": "Add this to your game's launch options in Steam Properties", - "explanation": "The lsfg script points games at the upstream configuration; profiles are selected by Steam AppID" - } - async def get_config_file_content(self) -> Dict[str, Any]: """Get the current config file content @@ -221,38 +209,6 @@ class Plugin: "error": f"Error reading config file: {str(e)}" } - async def get_launch_script_content(self) -> Dict[str, Any]: - """Get the content of the launch script file - - Returns: - FileContentResponse dict with file content or error information - """ - try: - script_path = self.installation_service.get_launch_script_path() - - if not os.path.exists(script_path): - return { - "success": False, - "error": f"Launch script not found at {script_path}", - "path": str(script_path) - } - - with open(script_path, 'r') as file: - content = file.read() - - return { - "success": True, - "content": content, - "path": str(script_path) - } - - except Exception as e: - decky.logger.error(f"Error reading launch script: {e}") - return { - "success": False, - "error": str(e) - } - async def check_fgmod_directory(self) -> Dict[str, Any]: """Check if the fgmod directory exists in the home directory diff --git a/py_modules/lsfg_vk/steam_service.py b/py_modules/lsfg_vk/steam_service.py index 9b69806..54ac359 100644 --- a/py_modules/lsfg_vk/steam_service.py +++ b/py_modules/lsfg_vk/steam_service.py @@ -39,7 +39,7 @@ class SteamService(BaseService): "1628350", # Steam Linux Runtime 3.0 } - def _steam_library_roots(self): + def _steam_roots(self): candidates = ( self.user_home / ".local/share/Steam", self.user_home / ".steam/steam", @@ -51,6 +51,11 @@ class SteamService(BaseService): for candidate in candidates: yield from self._unique_existing_root(candidate, seen) + def _steam_library_roots(self): + seen = set() + for candidate in self._steam_roots(): + yield from self._unique_existing_root(candidate, seen) + library_file = candidate / "steamapps/libraryfolders.vdf" try: content = library_file.read_text(encoding="utf-8") @@ -61,6 +66,65 @@ class SteamService(BaseService): path = raw_path.replace(r'\"', '"').replace(r'\\', '\\') yield from self._unique_existing_root(Path(path), seen) + @staticmethod + def _read_shortcuts(data: bytes) -> Dict[str, object]: + def read_string(offset: int) -> Tuple[str, int]: + end = data.index(b"\0", offset) + return data[offset:end].decode("utf-8", errors="replace"), end + 1 + + def read_object(offset: int = 0) -> Tuple[Dict[str, object], int]: + values = {} + while offset < len(data): + value_type, offset = data[offset], offset + 1 + if value_type == 8: + return values, offset + key, offset = read_string(offset) + if value_type == 0: + value, offset = read_object(offset) + elif value_type == 1: + value, offset = read_string(offset) + elif value_type == 2: + if offset + 4 > len(data): + raise ValueError("truncated binary VDF integer") + value = int.from_bytes(data[offset:offset + 4], "little", signed=True) + offset += 4 + else: + raise ValueError(f"unsupported binary VDF type {value_type}") + values[key] = value + raise ValueError("unterminated binary VDF object") + + values, offset = read_object() + if offset != len(data): + raise ValueError("trailing binary VDF data") + return values + + @staticmethod + def _shortcut_game(shortcut: object) -> Optional[Dict[str, object]]: + if not isinstance(shortcut, dict): + return None + appid = shortcut.get("appid") + name = shortcut.get("AppName") + if not isinstance(appid, int) or appid == 0 or not isinstance(name, str) or not name: + return None + return {"appid": str(appid), "name": name, "nonSteam": True} + + def _shortcut_games(self): + games = {} + for steam_root in self._steam_roots(): + for shortcuts_file in sorted((steam_root / "userdata").glob("*/config/shortcuts.vdf")): + try: + root = self._read_shortcuts(shortcuts_file.read_bytes()) + except (OSError, ValueError): + continue + shortcuts = root.get("shortcuts", {}) + if not isinstance(shortcuts, dict): + continue + for shortcut in shortcuts.values(): + game = self._shortcut_game(shortcut) + if game and game["appid"] not in self.GAME_SELECTOR_EXCLUDED_APPIDS: + games.setdefault(game["appid"], game) + return list(games.values()) + @staticmethod def _unique_existing_root(path: Path, seen: set[str]): if not path.exists(): @@ -208,7 +272,7 @@ class SteamService(BaseService): def get_installed_games(self) -> Dict[str, object]: """Return installed Steam app IDs and names for the Game Mode selector.""" try: - games = {} + games: Dict[str, Dict[str, object]] = {} for library_root in self._steam_library_roots(): for manifest in (library_root / "steamapps").glob("appmanifest_*.acf"): match = re.fullmatch(r"appmanifest_(\d+)\.acf", manifest.name) @@ -222,7 +286,12 @@ class SteamService(BaseService): if appid in self.GAME_SELECTOR_EXCLUDED_APPIDS: continue name = self._section_value(content, "AppState", "name") or f"App {appid}" - games[appid] = name - return self._success_response(dict, games=[{"appid": appid, "name": name} for appid, name in sorted(games.items(), key=lambda item: item[1].lower())]) + games[appid] = {"appid": appid, "name": name, "nonSteam": False} + for game in self._shortcut_games(): + games.setdefault(str(game["appid"]), game) + return self._success_response( + dict, + games=sorted(games.values(), key=lambda game: str(game["name"]).lower()), + ) except Exception as error: return self._error_response(dict, str(error), games=[]) diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index b38fa3b..04d1309 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -49,7 +49,7 @@ export interface GameConfigEntry { profile: string; config: LsfgConfig; } -export interface InstalledGame { appid: string; name: string; } +export interface InstalledGame { appid: string; name: string; nonSteam: boolean; } export interface InstalledGamesResult { success: boolean; games?: InstalledGame[]; error?: string; } export interface GameConfigsResult { @@ -71,12 +71,6 @@ export interface ConfigSchemaResult { defaults: ConfigurationData; } -export interface LaunchOptionResult { - launch_option: string; - instructions: string; - explanation: string; -} - export interface FileContentResult { success: boolean; content?: string; @@ -131,9 +125,7 @@ export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); export const getLsfgConfig = callable<[], ConfigResult>("get_lsfg_config"); export const getConfigSchema = callable<[], ConfigSchemaResult>("get_config_schema"); -export const getLaunchOption = callable<[], LaunchOptionResult>("get_launch_option"); export const getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); -export const getLaunchScriptContent = callable<[], FileContentResult>("get_launch_script_content"); export const checkFgmodDirectory = callable<[], FgmodCheckResult>("check_fgmod_directory"); // Flatpak management API functions @@ -152,7 +144,7 @@ export const updateLsfgConfig = callable< export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); export const getGameConfig = callable<[string], GameConfigResult>("get_game_config"); -export const updateGameConfig = callable<[string, LsfgConfig], GameConfigResult>("update_game_config"); +export const updateGameConfig = callable<[string, string, LsfgConfig], GameConfigResult>("update_game_config"); export const resetGameConfig = callable<[string], GameConfigResult>("reset_game_config"); export const resetAllGameConfigs = callable<[], GameConfigsResult>("reset_all_game_configs"); diff --git a/src/components/ConfigFileTab.tsx b/src/components/ConfigFileTab.tsx new file mode 100644 index 0000000..60c5c7e --- /dev/null +++ b/src/components/ConfigFileTab.tsx @@ -0,0 +1,46 @@ +import { useEffect, useState } from "react"; +import { Field, Focusable, PanelSection, PanelSectionRow, Spinner } from "@decky/ui"; +import { getConfigFileContent, FileContentResult } from "../api/lsfgApi"; +import t from "../i18n/i18n"; + +export function ConfigFileTab() { + const [result, setResult] = useState(null); + + const copy = async (content: string) => { + try { + await navigator.clipboard.writeText(content); + } catch { + // Clipboard access is unavailable in some Deck UI contexts. + } + }; + + useEffect(() => { + getConfigFileContent().then(setResult).catch((error) => { + setResult({ success: false, error: String(error) }); + }); + }, []); + + if (!result) { + return ( + + + + ); + } + + return ( + + + + {result.success && result.content && ( + void copy(result.content || "")}> +
+                {result.content}
+              
+
+ )} +
+
+
+ ); +} diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx new file mode 100644 index 0000000..6f3f474 --- /dev/null +++ b/src/components/ConfigurationTab.tsx @@ -0,0 +1,54 @@ +import { PanelSection } from "@decky/ui"; +import { ConfigurationData } from "../config/configSchema"; +import { GameTarget } from "../hooks/useGameConfiguration"; +import { ConfigurationSection } from "./ConfigurationSection"; +import { FgmodClipboardButton } from "./FgmodClipboardButton"; +import { FpsMultiplierControl } from "./FpsMultiplierControl"; +import { GameConfigurationSelector } from "./GameConfigurationSelector"; +import t from "../i18n/i18n"; + +interface ConfigurationTabProps { + config: ConfigurationData; + targets: GameTarget[]; + runningGame: GameTarget | null; + selectedAppId: string; + onSelect: (appid: string) => void; + onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; + onReset: () => Promise; + onResetAll: () => Promise; +} + +export function ConfigurationTab({ + config, + targets, + runningGame, + selectedAppId, + onSelect, + onConfigChange, + onReset, + onResetAll, +}: ConfigurationTabProps) { + return ( + <> + + + + + + + + + + + + + + ); +} diff --git a/src/components/Content.tsx b/src/components/Content.tsx index bdb3a04..de8f996 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,20 +1,22 @@ -import { useEffect } from "react"; -import { PanelSection, showModal, ButtonItem, PanelSectionRow } from "@decky/ui"; -import { useInstallationStatus } from "../hooks/useLsfgHooks"; +import { Tabs } from "@decky/ui"; +import { useEffect, useState } from "react"; +import { FaFileAlt, FaGamepad, FaLayerGroup, FaTools } from "react-icons/fa"; +import { ConfigurationData } from "../config/configSchema"; +import { tabStyles } from "../styles"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallationActions } from "../hooks/useInstallationActions"; -import { StatusDisplay } from "./StatusDisplay"; -import { InstallationButton } from "./InstallationButton"; -import { ConfigurationSection } from "./ConfigurationSection"; -import { GameConfigurationSelector } from "./GameConfigurationSelector"; -import { UsageInstructions } from "./UsageInstructions"; -import { SmartClipboardButton } from "./SmartClipboardButton"; -import { FgmodClipboardButton } from "./FgmodClipboardButton"; -import { FpsMultiplierControl } from "./FpsMultiplierControl"; -import { NerdStuffModal } from "./NerdStuffModal"; -import { FlatpaksModal } from "./FlatpaksModal"; -import { ConfigurationData } from "../config/configSchema"; -import t from '../i18n/i18n'; +import { useInstallationStatus } from "../hooks/useLsfgHooks"; +import { ConfigFileTab } from "./ConfigFileTab"; +import { ConfigurationTab } from "./ConfigurationTab"; +import { FlatpaksTab } from "./FlatpaksTab"; +import { SetupTab } from "./SetupTab"; + +const tabIcons = { + configuration: , + flatpak: , + configFile: , + setup: , +}; export function Content() { const { @@ -25,141 +27,98 @@ export function Content() { losslessScalingInstalled, losslessScalingStatus, steamBranchStatus, - checkInstallation + checkInstallation, } = useInstallationStatus(); - - const { config, targets, runningGame, selectedAppId, setSelectedAppId, save, resetSelected, resetAll, reload } = useGameConfiguration(); - + const { + config, + targets, + runningGame, + selectedAppId, + setSelectedAppId, + save, + resetSelected, + resetAll, + reload, + } = useGameConfiguration(); const { isInstalling, isUninstalling, handleInstall, handleUninstall } = useInstallationActions(); + const [tab, setTab] = useState("Setup"); + const setupComplete = + isInstalled && + losslessScalingInstalled && + steamBranchStatus?.success === true && + steamBranchStatus.installed && + !steamBranchStatus.needs_switch; + + useEffect(() => { + setTab(setupComplete ? "Configuration" : "Setup"); + }, [setupComplete]); useEffect(() => { if (isInstalled) void reload(); }, [isInstalled, reload]); - const handleConfigChange = async (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => { + const handleConfigChange = async ( + fieldName: keyof ConfigurationData, + value: boolean | number | string | string[], + ) => { await save({ ...config, [fieldName]: value }); }; const onInstall = () => { - handleInstall(setIsInstalled, setInstallationStatus, reload, checkInstallation); + void handleInstall(setIsInstalled, setInstallationStatus, reload, checkInstallation); }; const onUninstall = () => { - handleUninstall(setIsInstalled, setInstallationStatus, checkInstallation); + void handleUninstall(setIsInstalled, setInstallationStatus, checkInstallation); }; - const handleShowNerdStuff = () => { - showModal(); - }; + const setupContent = ( + + ); - const handleShowFlatpaks = () => { - showModal(); - }; + const tabs = setupComplete + ? [ + { + id: "Configuration", + title: tabIcons.configuration, + content: ( + + ), + }, + { id: "Flatpak", title: tabIcons.flatpak, content: }, + { id: "ConfigFile", title: tabIcons.configFile, content: }, + { id: "Setup", title: tabIcons.setup, content: setupContent }, + ] + : [ + { id: "Setup", title: tabIcons.setup, content: setupContent }, + ]; return ( - - {!isInstalled && ( - <> - - - - - )} - - {isInstalled && ( - <> - -
- {t('CONTENT_FPS_MULTIPLIER', 'FPS Multiplier')} -
-
- - - - )} - - {isInstalled && ( - - )} - - {isInstalled && ( - - )} - - {isInstalled && ( - <> - - - - )} - - - - - - {t('CONTENT_NERD_STUFF', 'Nerd Stuff')} - - - - - - {t('CONTENT_FLATPAK_SETUP', 'Flatpak Setup')} - - - - {isInstalled && ( - <> - - - - - )} -
+
+ + +
); } diff --git a/src/components/FlatpaksModal.tsx b/src/components/FlatpaksModal.tsx deleted file mode 100644 index 8245160..0000000 --- a/src/components/FlatpaksModal.tsx +++ /dev/null @@ -1,460 +0,0 @@ -import { FC, useState, useEffect, CSSProperties } from 'react'; -import { - ModalRoot, - DialogBody, - DialogHeader, - DialogControlsSection, - DialogControlsSectionHeader, - ButtonItem, - PanelSectionRow, - Field, - Toggle, - Spinner, - Focusable, - showModal, - ConfirmModal -} from '@decky/ui'; -import { FaCheck, FaTimes, FaDownload, FaTrash, FaCog } from 'react-icons/fa'; -import flatpakTargetImage from '../../assets/flatpak-target.png'; -import { - checkFlatpakExtensionStatus, - installFlatpakExtension, - uninstallFlatpakExtension, - getFlatpakApps, - setFlatpakAppOverride, - removeFlatpakAppOverride, - FlatpakExtensionStatus, - FlatpakApp, - FlatpakAppInfo -} from '../api/lsfgApi'; -import t from '../i18n/i18n'; -import { showErrorToast } from '../utils/toastUtils'; - -interface FlatpaksModalProps { - closeModal?: () => void; -} - -export const FlatpaksModal: FC = ({ closeModal }) => { - const [extensionStatus, setExtensionStatus] = useState(null); - const [flatpakApps, setFlatpakApps] = useState(null); - const [loading, setLoading] = useState(true); - const [operationInProgress, setOperationInProgress] = useState(null); - const [operationError, setOperationError] = useState(null); - - const loadData = async () => { - setLoading(true); - try { - const [statusResult, appsResult] = await Promise.all([ - checkFlatpakExtensionStatus(), - getFlatpakApps() - ]); - - setExtensionStatus(statusResult); - setFlatpakApps(appsResult); - } catch (error) { - console.error('Error loading Flatpak data:', error); - } finally { - setLoading(false); - } - }; - - useEffect(() => { - loadData(); - }, []); - - const handleExtensionOperation = async (operation: 'install' | 'uninstall', version: string) => { - const operationId = `${operation}-${version}`; - setOperationInProgress(operationId); - setOperationError(null); - - try { - const result = operation === 'install' - ? await installFlatpakExtension(version) - : await uninstallFlatpakExtension(version); - - if (result.success) { - // Reload status after operation - const newStatus = await checkFlatpakExtensionStatus(); - setExtensionStatus(newStatus); - } else { - const message = result.error || result.message || 'Flatpak operation failed'; - setOperationError(message); - showErrorToast('Flatpak operation failed', message); - } - } catch (error) { - console.error(`Error ${operation}ing extension:`, error); - const message = String(error); - setOperationError(message); - showErrorToast('Flatpak operation failed', message); - } finally { - setOperationInProgress(null); - } - }; - - const handleAppOverrideToggle = async (app: FlatpakApp) => { - const hasOverrides = app.has_filesystem_override && app.has_env_override; - const operationId = `app-${app.app_id}`; - setOperationInProgress(operationId); - setOperationError(null); - - try { - const result = hasOverrides - ? await removeFlatpakAppOverride(app.app_id) - : await setFlatpakAppOverride(app.app_id); - - if (result.success) { - // Reload apps data after operation - const newApps = await getFlatpakApps(); - setFlatpakApps(newApps); - } else { - const message = result.error || result.message || 'Flatpak override failed'; - setOperationError(message); - showErrorToast('Flatpak override failed', message); - } - } catch (error) { - console.error('Error toggling app override:', error); - const message = String(error); - setOperationError(message); - showErrorToast('Flatpak override failed', message); - } finally { - setOperationInProgress(null); - } - }; - - const confirmOperation = (operation: () => void, title: string, description: string) => { - showModal( - {}} - /> - ); - }; - - if (loading) { - return ( - - {t('FLATPAK_MODAL_TITLE', 'Flatpak Extensions')} - -
- -
-
-
- ); - } - - const instructionSteps = [ - { - id: 'try-first', - title: t('FLATPAK_STEP_TRY_FIRST', 'Try first:'), - command: '~/lsfg' - }, - { - id: 'try-full-path', - title: t('FLATPAK_STEP_TRY_FULL_PATH', "If that doesn't work, try full path:"), - command: '/home/(username)/lsfg' - }, - { - id: 'final-result', - title: t('FLATPAK_STEP_FINAL', 'Final result should look like:'), - command: '~/lsfg "usr/bin/flatpak"' - } - ]; - - const focusableInstructionStyle: CSSProperties = { - padding: '10px', - background: 'rgba(0, 0, 0, 0.3)', - borderRadius: '6px', - marginBottom: '12px' - }; - - const commandStyle: CSSProperties = { - fontFamily: 'monospace', - fontSize: '0.85em', - background: 'rgba(0, 0, 0, 0.45)', - padding: '8px', - borderRadius: '4px', - marginTop: '6px' - }; - - return ( - - {t('FLATPAK_MODAL_TITLE', 'Flatpak Extensions')} - - - {/* Extension Status Section */} - - {t('FLATPAK_RUNTIME_INSTALLER', 'Runtime Extension Installer')} - - {operationError && ( - - } - /> - - )} - - {extensionStatus && extensionStatus.success ? ( - <> - - : } - > - { - const operation = extensionStatus.installed_23_08 ? 'uninstall' : 'install'; - const action = () => handleExtensionOperation(operation, '23.08'); - - if (operation === 'uninstall') { - confirmOperation( - action, - t('FLATPAK_UNINSTALL_TITLE', 'Uninstall Runtime Extension'), - `${t('FLATPAK_UNINSTALL_CONFIRM_PREFIX', 'Are you sure you want to uninstall the')} 23.08 ${t('FLATPAK_UNINSTALL_CONFIRM_SUFFIX', 'runtime extension?')}` - ); - } else { - action(); - } - }} - disabled={operationInProgress === 'install-23.08' || operationInProgress === 'uninstall-23.08'} - > - {operationInProgress === 'install-23.08' || operationInProgress === 'uninstall-23.08' ? ( - - ) : extensionStatus.installed_23_08 ? ( - <> - {t('FLATPAK_UNINSTALL_BTN', 'Uninstall')} - - ) : ( - <> - {t('FLATPAK_INSTALL_BTN', 'Install')} - - )} - - - - - {/* 24.08 Runtime */} - - : } - > - { - const operation = extensionStatus.installed_24_08 ? 'uninstall' : 'install'; - const action = () => handleExtensionOperation(operation, '24.08'); - - if (operation === 'uninstall') { - confirmOperation( - action, - t('FLATPAK_UNINSTALL_TITLE', 'Uninstall Runtime Extension'), - `${t('FLATPAK_UNINSTALL_CONFIRM_PREFIX', 'Are you sure you want to uninstall the')} 24.08 ${t('FLATPAK_UNINSTALL_CONFIRM_SUFFIX', 'runtime extension?')}` - ); - } else { - action(); - } - }} - disabled={operationInProgress === 'install-24.08' || operationInProgress === 'uninstall-24.08'} - > - {operationInProgress === 'install-24.08' || operationInProgress === 'uninstall-24.08' ? ( - - ) : extensionStatus.installed_24_08 ? ( - <> - {t('FLATPAK_UNINSTALL_BTN', 'Uninstall')} - - ) : ( - <> - {t('FLATPAK_INSTALL_BTN', 'Install')} - - )} - - - - - {/* 25.08 Runtime */} - - : } - > - { - const operation = extensionStatus.installed_25_08 ? 'uninstall' : 'install'; - const action = () => handleExtensionOperation(operation, '25.08'); - - if (operation === 'uninstall') { - confirmOperation( - action, - t('FLATPAK_UNINSTALL_TITLE', 'Uninstall Runtime Extension'), - `${t('FLATPAK_UNINSTALL_CONFIRM_PREFIX', 'Are you sure you want to uninstall the')} 25.08 ${t('FLATPAK_UNINSTALL_CONFIRM_SUFFIX', 'runtime extension?')}` - ); - } else { - action(); - } - }} - disabled={operationInProgress === 'install-25.08' || operationInProgress === 'uninstall-25.08'} - > - {operationInProgress === 'install-25.08' || operationInProgress === 'uninstall-25.08' ? ( - - ) : extensionStatus.installed_25_08 ? ( - <> - {t('FLATPAK_UNINSTALL_BTN', 'Uninstall')} - - ) : ( - <> - {t('FLATPAK_INSTALL_BTN', 'Install')} - - )} - - - - - ) : ( - - } - /> - - )} - - - {/* Flatpak Apps Section */} - - {t('FLATPAK_APPS_TITLE', 'Flatpak Applications')} - - {flatpakApps && flatpakApps.success ? ( - flatpakApps.apps.length > 0 ? ( - flatpakApps.apps.map((app) => { - const hasOverrides = app.has_filesystem_override && app.has_env_override; - const partialOverrides = app.has_filesystem_override || app.has_env_override; - - let statusColor = 'red'; - let statusText = t('FLATPAK_STATUS_NO_OVERRIDES', 'No overrides'); - - if (hasOverrides) { - statusColor = 'green'; - statusText = t('FLATPAK_STATUS_CONFIGURED', 'Configured'); - } else if (partialOverrides) { - statusColor = 'orange'; - statusText = t('FLATPAK_STATUS_PARTIAL', 'Partial'); - } - - return ( - - } - > - handleAppOverrideToggle(app)} - disabled={operationInProgress === `app-${app.app_id}`} - /> - - - ); - }) - ) : ( - - - - ) - ) : ( - - } - /> - - )} - - - {/* Steam Configuration Instructions */} - - {t('FLATPAK_STEAM_CONFIG_TITLE', 'Steam Configuration')} -
-
- {t('FLATPAK_STEAM_CONFIG_HEADER', 'Configure Steam Flatpak Shortcuts')} -
-
- {t('FLATPAK_STEAM_CONFIG_DESC', 'In Steam, open your flatpak game and click the cog wheel.')} -
-
- IMPORTANT: {t('FLATPAK_STEAM_CONFIG_IMPORTANT', 'Set this in TARGET (NOT LAUNCH OPTIONS)')} -
- - {instructionSteps.map((step) => ( - {}} - style={focusableInstructionStyle} - > -
{step.title}
-
{step.command}
-
- ))} - - {}} - style={{ marginTop: '4px' }} - > -
- Steam Properties Target Field Example -
-
-
-
- - {/* Close Button */} - - - - {t('FLATPAK_CLOSE', 'Close')} - - - -
-
-
- ); -}; diff --git a/src/components/FlatpaksTab.tsx b/src/components/FlatpaksTab.tsx new file mode 100644 index 0000000..dc73858 --- /dev/null +++ b/src/components/FlatpaksTab.tsx @@ -0,0 +1,195 @@ +import { useEffect, useState } from "react"; +import { + ButtonItem, + ConfirmModal, + Field, + PanelSection, + PanelSectionRow, + Spinner, + Toggle, + showModal, +} from "@decky/ui"; +import { FaCheck, FaCog, FaDownload, FaTimes, FaTrash } from "react-icons/fa"; +import { + checkFlatpakExtensionStatus, + FlatpakApp, + FlatpakAppInfo, + FlatpakExtensionStatus, + getFlatpakApps, + installFlatpakExtension, + removeFlatpakAppOverride, + setFlatpakAppOverride, + uninstallFlatpakExtension, +} from "../api/lsfgApi"; +import { showErrorToast } from "../utils/toastUtils"; +import t from "../i18n/i18n"; + +const runtimeVersions = [ + { version: "23.08", key: "installed_23_08" }, + { version: "24.08", key: "installed_24_08" }, + { version: "25.08", key: "installed_25_08" }, +] as const; + +interface RuntimeRowProps { + version: string; + installed: boolean; + busy: boolean; + onAction: () => void; +} + +function RuntimeRow({ version, installed, busy, onAction }: RuntimeRowProps) { + return ( + + : } + > + + {busy ? : installed ? <> {t("FLATPAK_UNINSTALL_BTN", "Uninstall")} : <> {t("FLATPAK_INSTALL_BTN", "Install")}} + + + + ); +} + +interface AppRowProps { + app: FlatpakApp; + busy: boolean; + onToggle: () => void; +} + +function AppRow({ app, busy, onToggle }: AppRowProps) { + const configured = app.has_filesystem_override && app.has_env_override; + const partial = app.has_filesystem_override || app.has_env_override; + const status = configured + ? t("FLATPAK_STATUS_CONFIGURED", "Configured") + : partial + ? t("FLATPAK_STATUS_PARTIAL", "Partial") + : t("FLATPAK_STATUS_NO_OVERRIDES", "No overrides"); + + return ( + + } + > + + + + ); +} + +export function FlatpaksTab() { + const [extensionStatus, setExtensionStatus] = useState(null); + const [apps, setApps] = useState(null); + const [loading, setLoading] = useState(true); + const [operation, setOperation] = useState(null); + const [error, setError] = useState(null); + + const load = async () => { + setLoading(true); + try { + const [nextStatus, nextApps] = await Promise.all([ + checkFlatpakExtensionStatus(), + getFlatpakApps(), + ]); + setExtensionStatus(nextStatus); + setApps(nextApps); + } catch (loadError) { + setError(String(loadError)); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + void load(); + }, []); + + const runExtensionOperation = async (version: string, installed: boolean) => { + const action = installed ? "uninstall" : "install"; + setOperation(`${action}-${version}`); + setError(null); + try { + const result = installed + ? await uninstallFlatpakExtension(version) + : await installFlatpakExtension(version); + if (!result.success) throw new Error(result.error || result.message); + setExtensionStatus(await checkFlatpakExtensionStatus()); + } catch (operationError) { + const message = String(operationError); + setError(message); + showErrorToast("Flatpak operation failed", message); + } finally { + setOperation(null); + } + }; + + const confirmExtensionOperation = (version: string, installed: boolean) => { + if (!installed) { + void runExtensionOperation(version, false); + return; + } + showModal( + void runExtensionOperation(version, true)} + onCancel={() => {}} + />, + ); + }; + + const toggleApp = async (app: FlatpakApp) => { + const configured = app.has_filesystem_override && app.has_env_override; + setOperation(`app-${app.app_id}`); + setError(null); + try { + const result = configured + ? await removeFlatpakAppOverride(app.app_id) + : await setFlatpakAppOverride(app.app_id); + if (!result.success) throw new Error(result.error || result.message); + setApps(await getFlatpakApps()); + } catch (operationError) { + const message = String(operationError); + setError(message); + showErrorToast("Flatpak override failed", message); + } finally { + setOperation(null); + } + }; + + if (loading) { + return ; + } + + return ( + <> + + {error && } />} + {extensionStatus?.success ? runtimeVersions.map(({ version, key }) => ( + confirmExtensionOperation(version, extensionStatus[key])} + /> + )) : } + + + + {apps?.success ? apps.apps.length ? apps.apps.map((app) => ( + void toggleApp(app)} + /> + )) : : } + + + ); +} diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 8a0df6c..a231477 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -13,7 +13,7 @@ interface Props { export function GameConfigurationSelector({ targets, runningGame, selectedAppId, onSelect, onReset, onResetAll }: Props) { const options: DropdownOption[] = [ { data: "", label: runningGame ? `Default (editing template) · ${runningGame.name}` : "Default" }, - ...targets.map((target) => ({ data: target.appid, label: `${target.name} · ${target.appid}` })), + ...targets.map((target) => ({ data: target.appid, label: `${target.nonSteam ? "Non-Steam · " : ""}${target.name} · ${target.appid}` })), ]; return <> diff --git a/src/components/NerdStuffModal.tsx b/src/components/NerdStuffModal.tsx deleted file mode 100644 index f075ccb..0000000 --- a/src/components/NerdStuffModal.tsx +++ /dev/null @@ -1,148 +0,0 @@ -import { useState, useEffect } from "react"; -import { - ModalRoot, - Field, - Focusable, - DialogControlsSection, - PanelSectionRow, - ButtonItem -} from "@decky/ui"; -import { - getConfigFileContent, - getLaunchScriptContent, - FileContentResult, -} from "../api/lsfgApi"; -import t from '../i18n/i18n'; - -interface NerdStuffModalProps { - closeModal?: () => void; -} - -export function NerdStuffModal({ closeModal }: NerdStuffModalProps) { - const [configContent, setConfigContent] = useState(null); - const [scriptContent, setScriptContent] = useState(null); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - - useEffect(() => { - const loadData = async () => { - try { - setLoading(true); - setError(null); - - // Load all data in parallel - const [configResult, scriptResult] = await Promise.all([ - getConfigFileContent(), - getLaunchScriptContent(), - ]); - - setConfigContent(configResult); - setScriptContent(scriptResult); - } catch (err) { - setError(err instanceof Error ? err.message : "Failed to load data"); - } finally { - setLoading(false); - } - }; - - loadData(); - }, []); - - const copyToClipboard = async (text: string) => { - try { - await navigator.clipboard.writeText(text); - // Could add a toast notification here if desired - } catch (err) { - console.error("Failed to copy to clipboard:", err); - } - }; - - return ( - - {loading && ( -
{t('NERD_LOADING', 'Loading information...')}
- )} - - {error && ( -
Error: {error}
- )} - - {!loading && !error && ( - <> - {/* Launch Script Section */} - {scriptContent && ( - - {!scriptContent.success ? ( -
{t('NERD_SCRIPT_NOT_FOUND_PREFIX', 'Script not found:')} {scriptContent.error}
- ) : ( -
-
- {t('NERD_PATH_PREFIX', 'Path:')} {scriptContent.path} -
- scriptContent.content && copyToClipboard(scriptContent.content)} - onActivate={() => scriptContent.content && copyToClipboard(scriptContent.content)} - > -
-                      {scriptContent.content || t('NERD_NO_CONTENT', 'No content')}
-                    
-
-
- )} -
- )} - - {/* Config File Section */} - {configContent && ( - - {!configContent.success ? ( -
{t('NERD_CONFIG_NOT_FOUND_PREFIX', 'Config not found:')} {configContent.error}
- ) : ( -
-
- {t('NERD_PATH_PREFIX', 'Path:')} {configContent.path} -
- configContent.content && copyToClipboard(configContent.content)} - onActivate={() => configContent.content && copyToClipboard(configContent.content)} - > -
-                      {configContent.content || t('NERD_NO_CONTENT', 'No content')}
-                    
-
-
- )} -
- )} - - {/* Close Button */} - - - - {t('NERD_CLOSE', 'Close')} - - - - - )} -
- ); -} diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx new file mode 100644 index 0000000..34106ed --- /dev/null +++ b/src/components/SetupTab.tsx @@ -0,0 +1,47 @@ +import { PanelSection } from "@decky/ui"; +import type { SteamBranchStatus } from "../api/lsfgApi"; +import { InstallationButton } from "./InstallationButton"; +import { StatusDisplay } from "./StatusDisplay"; + +interface SetupTabProps { + isInstalled: boolean; + installationStatus: string; + losslessScalingInstalled: boolean; + losslessScalingStatus: string; + steamBranchStatus: SteamBranchStatus | null; + isInstalling: boolean; + isUninstalling: boolean; + onInstall: () => void; + onUninstall: () => void; +} + +export function SetupTab({ + isInstalled, + installationStatus, + losslessScalingInstalled, + losslessScalingStatus, + steamBranchStatus, + isInstalling, + isUninstalling, + onInstall, + onUninstall, +}: SetupTabProps) { + return ( + + + + + ); +} diff --git a/src/components/SmartClipboardButton.tsx b/src/components/SmartClipboardButton.tsx deleted file mode 100644 index 8da239a..0000000 --- a/src/components/SmartClipboardButton.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { useState, useEffect } from "react"; -import { PanelSectionRow, ButtonItem } from "@decky/ui"; -import { FaClipboard, FaCheck } from "react-icons/fa"; -import { getLaunchOption } from "../api/lsfgApi"; -import { showClipboardErrorToast } from "../utils/toastUtils"; -import { copyWithVerification } from "../utils/clipboardUtils"; -import t from '../i18n/i18n'; - -export function SmartClipboardButton() { - const [isLoading, setIsLoading] = useState(false); - const [showSuccess, setShowSuccess] = useState(false); - - useEffect(() => { - if (showSuccess) { - const timer = setTimeout(() => { - setShowSuccess(false); - }, 3000); - return () => clearTimeout(timer); - } - return undefined; - }, [showSuccess]); - - const getLaunchOptionText = async (): Promise => { - try { - const result = await getLaunchOption(); - return result.launch_option || "~/lsfg %command%"; - } catch (error) { - return "~/lsfg %command%"; - } - }; - - const copyToClipboard = async () => { - if (isLoading || showSuccess) return; - - setIsLoading(true); - try { - const text = await getLaunchOptionText(); - const { success, verified } = await copyWithVerification(text); - - if (success) { - setShowSuccess(true); - if (!verified) { - console.log('Copy verification failed but copy likely worked'); - } - } else { - showClipboardErrorToast(); - } - - } catch (error) { - showClipboardErrorToast(); - } finally { - setIsLoading(false); - } - }; - - return ( - - -
- {showSuccess ? ( - - ) : isLoading ? ( - - ) : ( - - )} -
- {showSuccess ? t('CLIPBOARD_COPIED', 'Copied to clipboard') : isLoading ? t('CLIPBOARD_COPYING', 'Copying...') : t('CLIPBOARD_COPY_LAUNCH', 'Copy Launch Option')} -
-
-
- -
- ); -} diff --git a/src/components/UsageInstructions.tsx b/src/components/UsageInstructions.tsx deleted file mode 100644 index 36e31cf..0000000 --- a/src/components/UsageInstructions.tsx +++ /dev/null @@ -1,69 +0,0 @@ -import { PanelSectionRow } from "@decky/ui"; -import t from '../i18n/i18n'; - -export function UsageInstructions() { - return ( - <> - -
- {t('USAGE_TITLE', 'Usage Instructions')} -
-
- - -
- {t('USAGE_DESC', 'Click "Copy Launch Option" button, then paste it into your Steam game\'s launch options to enable frame generation.')} -
-
- - -
- ~/lsfg %command% -
-
- - -
- {t('USAGE_CONFIG_NOTE', 'The configuration is stored in ~/.config/lsfg-vk/conf.toml and hot-reloads while games are running.')} -
-
- - ); -} diff --git a/src/components/index.ts b/src/components/index.ts index 4284aee..5089b6f 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -3,9 +3,9 @@ export { StatusDisplay } from "./StatusDisplay"; export { InstallationButton } from "./InstallationButton"; export { ConfigurationSection } from "./ConfigurationSection"; export { FpsMultiplierControl } from "./FpsMultiplierControl"; -export { UsageInstructions } from "./UsageInstructions"; -export { SmartClipboardButton } from "./SmartClipboardButton"; export { FgmodClipboardButton } from "./FgmodClipboardButton"; -export { NerdStuffModal } from "./NerdStuffModal"; -export { FlatpaksModal } from "./FlatpaksModal"; +export { ConfigurationTab } from "./ConfigurationTab"; +export { SetupTab } from "./SetupTab"; +export { ConfigFileTab } from "./ConfigFileTab"; +export { FlatpaksTab } from "./FlatpaksTab"; export { GameConfigurationSelector } from "./GameConfigurationSelector"; diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index e0ba360..b177551 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -3,7 +3,7 @@ import { Router } from "@decky/ui"; import { getGameConfigs, getInstalledGames, updateGameConfig, updateLsfgConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type InstalledGame } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; -export interface GameTarget { appid: string; name: string; configured: boolean; } +export interface GameTarget extends InstalledGame { configured: boolean; } export function useGameConfiguration() { const [defaultConfig, setDefaultConfig] = useState(getDefaults()); @@ -26,13 +26,21 @@ export function useGameConfiguration() { useEffect(() => { const poll = () => { const app = Router.MainRunningApp as any; - if (app?.appid) setRunningGame({ appid: String(app.appid), name: app.display_name || `App ${app.appid}`, configured: games.some((game) => game.appid === String(app.appid)) }); - else setRunningGame(null); + if (!app?.appid) return setRunningGame(null); + const appid = String(app.appid); + const installed = installedGames.find((game) => game.appid === appid); + const name = app.display_name || installed?.name; + if (!name) return setRunningGame(null); + setRunningGame({ + ...(installed || { appid, name, nonSteam: false }), + name, + configured: games.some((game) => game.appid === appid), + }); }; poll(); const interval = window.setInterval(poll, 2000); return () => window.clearInterval(interval); - }, [games]); + }, [games, installedGames]); useEffect(() => { if (!autoSelected.current && runningGame) { autoSelected.current = true; @@ -41,8 +49,8 @@ export function useGameConfiguration() { }, [runningGame]); const targets = useMemo(() => { - const configured = installedGames.map((game) => ({ appid: game.appid, name: game.name, configured: games.some((item) => item.appid === game.appid) })); - for (const game of games) if (!configured.some((item) => item.appid === game.appid)) configured.push({ appid: game.appid, name: `App ${game.appid}`, configured: true }); + const configured = installedGames.map((game) => ({ ...game, configured: games.some((item) => item.appid === game.appid) })); + for (const game of games) if (!configured.some((item) => item.appid === game.appid)) configured.push({ appid: game.appid, name: game.profile, nonSteam: false, configured: true }); if (runningGame && !configured.some((game) => game.appid === runningGame.appid)) configured.unshift(runningGame); return configured; }, [games, installedGames, runningGame]); @@ -55,9 +63,11 @@ export function useGameConfiguration() { if (result.success) setDefaultConfig(next); return; } - const result = await updateGameConfig(selectedAppId, next); + const selectedTarget = targets.find((target) => target.appid === selectedAppId); + if (!selectedTarget?.name) return; + const result = await updateGameConfig(selectedAppId, selectedTarget.name, next); if (result.success) await load(); - }, [load, selectedAppId]); + }, [load, selectedAppId, targets]); const resetSelected = useCallback(async () => { if (selectedAppId) { await resetGameConfig(selectedAppId); setSelectedAppId(""); await load(); } diff --git a/src/i18n/languages.json b/src/i18n/languages.json index 46b4cd9..0528341 100644 --- a/src/i18n/languages.json +++ b/src/i18n/languages.json @@ -58,17 +58,12 @@ "FLATPAK_ERROR": "エラー", "FLATPAK_ERROR_STATUS": "拡張ステータスの確認に失敗しました", "FLATPAK_ERROR_APPS": "Flatpakアプリケーションの読み込みに失敗しました", - "FLATPAK_STEAM_CONFIG_TITLE": "Steam設定", - "FLATPAK_STEAM_CONFIG_HEADER": "Steam Flatpakショートカットの設定", - "FLATPAK_STEAM_CONFIG_DESC": "Steamでflatpakゲームを開き、歯車アイコンをクリックしてください。", - "FLATPAK_STEAM_CONFIG_IMPORTANT": "重要: 起動オプションではなくターゲット(TARGET)に設定してください", - "FLATPAK_STEP_TRY_FIRST": "まず試す:", - "FLATPAK_STEP_TRY_FULL_PATH": "うまくいかない場合、フルパスを試す:", - "FLATPAK_STEP_FINAL": "最終的な結果はこのようになります:", "FLATPAK_CLOSE": "閉じる", "NERD_LOADING": "情報を読み込み中...", - "NERD_LAUNCH_SCRIPT": "起動スクリプト", - "NERD_SCRIPT_NOT_FOUND_PREFIX": "スクリプトが見つかりません:", + "NERD_DLL_PATH": "DLLパス", + "NERD_NOT_AVAILABLE": "利用不可", + "NERD_DLL_HASH": "DLL SHA256ハッシュ", + "NERD_DETECTION_SOURCE": "検出ソース", "NERD_PATH_PREFIX": "パス:", "NERD_NO_CONTENT": "コンテンツなし", "NERD_CONFIG_FILE": "設定ファイル", @@ -94,12 +89,8 @@ "PROFILE_DELETE_BTN": "削除", "PROFILE_CANNOT_RENAME_TITLE": "デフォルトプロファイルの名前は変更できません", "PROFILE_CANNOT_RENAME_MSG": "デフォルトプロファイルの名前は変更できません", - "USAGE_TITLE": "使用方法", - "USAGE_DESC": "「起動オプションをコピー」ボタンをクリックし、Steamゲームの起動オプションに貼り付けてフレーム生成を有効化してください。", - "USAGE_CONFIG_NOTE": "設定は~/.config/lsfg-vk/conf.tomlに保存され、ゲーム実行中もホットリロードされます。", "CLIPBOARD_COPIED": "クリップボードにコピーしました", "CLIPBOARD_COPYING": "コピー中...", - "CLIPBOARD_COPY_LAUNCH": "起動オプションをコピー", "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" }, "ko": { @@ -161,17 +152,12 @@ "FLATPAK_ERROR": "오류", "FLATPAK_ERROR_STATUS": "확장 상태 확인 실패", "FLATPAK_ERROR_APPS": "Flatpak 애플리케이션 로드 실패", - "FLATPAK_STEAM_CONFIG_TITLE": "Steam 설정", - "FLATPAK_STEAM_CONFIG_HEADER": "Steam Flatpak 단축키 설정", - "FLATPAK_STEAM_CONFIG_DESC": "Steam에서 Flatpak 게임을 열고 톱니바퀴를 클릭하세요.", - "FLATPAK_STEAM_CONFIG_IMPORTANT": "중요: 실행 옵션이 아닌 대상(TARGET)에 설정하세요", - "FLATPAK_STEP_TRY_FIRST": "먼저 시도:", - "FLATPAK_STEP_TRY_FULL_PATH": "작동하지 않으면 전체 경로 시도:", - "FLATPAK_STEP_FINAL": "최종 결과는 다음과 같아야 합니다:", "FLATPAK_CLOSE": "닫기", "NERD_LOADING": "정보 불러오는 중...", - "NERD_LAUNCH_SCRIPT": "실행 스크립트", - "NERD_SCRIPT_NOT_FOUND_PREFIX": "스크립트 없음:", + "NERD_DLL_PATH": "DLL 경로", + "NERD_NOT_AVAILABLE": "사용 불가", + "NERD_DLL_HASH": "DLL SHA256 해시", + "NERD_DETECTION_SOURCE": "감지 소스", "NERD_PATH_PREFIX": "경로:", "NERD_NO_CONTENT": "내용 없음", "NERD_CONFIG_FILE": "설정 파일", @@ -197,12 +183,8 @@ "PROFILE_DELETE_BTN": "삭제", "PROFILE_CANNOT_RENAME_TITLE": "기본 프로필 이름 변경 불가", "PROFILE_CANNOT_RENAME_MSG": "기본 프로필의 이름은 변경할 수 없습니다", - "USAGE_TITLE": "사용 방법", - "USAGE_DESC": "\"실행 옵션 복사\" 버튼을 클릭한 후, Steam 게임의 실행 옵션에 붙여넣어 프레임 생성을 활성화하세요.", - "USAGE_CONFIG_NOTE": "설정은 ~/.config/lsfg-vk/conf.toml에 저장되며 게임 실행 중에도 즉시 반영됩니다.", "CLIPBOARD_COPIED": "클립보드에 복사됨", "CLIPBOARD_COPYING": "복사 중...", - "CLIPBOARD_COPY_LAUNCH": "실행 옵션 복사", "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" }, "language_metadata": { @@ -292,17 +274,12 @@ "FLATPAK_ERROR": "Error", "FLATPAK_ERROR_STATUS": "Failed to check extension status", "FLATPAK_ERROR_APPS": "Failed to load Flatpak applications", - "FLATPAK_STEAM_CONFIG_TITLE": "Steam Configuration", - "FLATPAK_STEAM_CONFIG_HEADER": "Configure Steam Flatpak Shortcuts", - "FLATPAK_STEAM_CONFIG_DESC": "In Steam, open your flatpak game and click the cog wheel.", - "FLATPAK_STEAM_CONFIG_IMPORTANT": "IMPORTANT: Set this in TARGET (NOT LAUNCH OPTIONS)", - "FLATPAK_STEP_TRY_FIRST": "Try first:", - "FLATPAK_STEP_TRY_FULL_PATH": "If that doesn't work, try full path:", - "FLATPAK_STEP_FINAL": "Final result should look like:", "FLATPAK_CLOSE": "Close", "NERD_LOADING": "Loading information...", - "NERD_LAUNCH_SCRIPT": "Launch Script", - "NERD_SCRIPT_NOT_FOUND_PREFIX": "Script not found:", + "NERD_DLL_PATH": "DLL Path", + "NERD_NOT_AVAILABLE": "Not available", + "NERD_DLL_HASH": "DLL SHA256 Hash", + "NERD_DETECTION_SOURCE": "Detection Source", "NERD_PATH_PREFIX": "Path:", "NERD_NO_CONTENT": "No content", "NERD_CONFIG_FILE": "Configuration File", @@ -328,12 +305,8 @@ "PROFILE_DELETE_BTN": "Delete", "PROFILE_CANNOT_RENAME_TITLE": "Cannot rename default profile", "PROFILE_CANNOT_RENAME_MSG": "The default profile cannot be renamed", - "USAGE_TITLE": "Usage Instructions", - "USAGE_DESC": "Click \"Copy Launch Option\" button, then paste it into your Steam game's launch options to enable frame generation.", - "USAGE_CONFIG_NOTE": "The configuration is stored in ~/.config/lsfg-vk/conf.toml and hot-reloads while games are running.", "CLIPBOARD_COPIED": "Copied to clipboard", "CLIPBOARD_COPYING": "Copying...", - "CLIPBOARD_COPY_LAUNCH": "Copy Launch Option", "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" } } diff --git a/src/styles.ts b/src/styles.ts new file mode 100644 index 0000000..fe40a59 --- /dev/null +++ b/src/styles.ts @@ -0,0 +1,34 @@ +export const tabStyles = ` + .lsfg-vk-tabs > div > div:first-child::before { + background: #0D141C; + box-shadow: none; + backdrop-filter: none; + } + + .lsfg-vk-tabs [role="tabpanel"] { + padding-left: 8px !important; + padding-right: 8px !important; + } + + .lsfg-vk-tabs [role="tablist"] { + display: flex; + flex-wrap: nowrap; + justify-content: center; + } + + .lsfg-vk-tabs [role="tab"] { + flex: 0 1 auto; + min-width: 0; + box-sizing: border-box; + padding-left: 6px !important; + padding-right: 6px !important; + display: flex !important; + align-items: center; + justify-content: center; + } + + .lsfg-vk-tabs [role="tab"] svg { + display: block; + margin: 0; + } +`; -- cgit v1.2.3