From 4fe21381b6c694d5eb615447c4827e4921593a52 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 5 Sep 2026 15:30:42 -0400 Subject: feat: migrate native runtime to lsfg-vk v2 --- src/components/ConfigurationSection.tsx | 14 +++----------- src/config/configSchema.ts | 2 +- src/config/generatedConfigSchema.ts | 20 +++++--------------- 3 files changed, 9 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationSection.tsx b/src/components/ConfigurationSection.tsx index a10aab2..e83bd58 100644 --- a/src/components/ConfigurationSection.tsx +++ b/src/components/ConfigurationSection.tsx @@ -3,7 +3,7 @@ import { useState, useEffect } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { ConfigurationData } from "../config/configSchema"; import { - FLOW_SCALE, NO_FP16, PERFORMANCE_MODE, HDR_MODE, + FLOW_SCALE, NO_FP16, PERFORMANCE_MODE, EXPERIMENTAL_PRESENT_MODE, DXVK_FRAME_RATE, DISABLE_STEAMDECK_MODE, MANGOHUD_WORKAROUND, DISABLE_VKBASALT, FORCE_ENABLE_VKBASALT, ENABLE_WSI, ENABLE_ZINK } from "../config/generatedConfigSchema"; @@ -149,8 +149,8 @@ export function ConfigurationSection({ onConfigChange(EXPERIMENTAL_PRESENT_MODE, value ? "fifo" : "mailbox")} /> @@ -165,14 +165,6 @@ export function ConfigurationSection({ /> - - onConfigChange(HDR_MODE, value)} - /> - )} diff --git a/src/config/configSchema.ts b/src/config/configSchema.ts index 8b4fc1e..befbd8d 100644 --- a/src/config/configSchema.ts +++ b/src/config/configSchema.ts @@ -6,7 +6,7 @@ export { getFieldNames, getDefaults, getFieldTypes, - DLL, NO_FP16, MULTIPLIER, FLOW_SCALE, PERFORMANCE_MODE, HDR_MODE, + DLL, NO_FP16, MULTIPLIER, FLOW_SCALE, PERFORMANCE_MODE, EXPERIMENTAL_PRESENT_MODE, DXVK_FRAME_RATE, ENABLE_WOW64, DISABLE_STEAMDECK_MODE, MANGOHUD_WORKAROUND, DISABLE_VKBASALT, FORCE_ENABLE_VKBASALT, ENABLE_WSI, ENABLE_ZINK diff --git a/src/config/generatedConfigSchema.ts b/src/config/generatedConfigSchema.ts index 3c5d34e..8fae79a 100644 --- a/src/config/generatedConfigSchema.ts +++ b/src/config/generatedConfigSchema.ts @@ -13,7 +13,6 @@ export const NO_FP16 = "no_fp16" as const; export const MULTIPLIER = "multiplier" as const; export const FLOW_SCALE = "flow_scale" as const; export const PERFORMANCE_MODE = "performance_mode" as const; -export const HDR_MODE = "hdr_mode" as const; export const EXPERIMENTAL_PRESENT_MODE = "experimental_present_mode" as const; export const DXVK_FRAME_RATE = "dxvk_frame_rate" as const; export const ENABLE_WOW64 = "enable_wow64" as const; @@ -37,7 +36,7 @@ export const CONFIG_SCHEMA: Record = { dll: { name: "dll", fieldType: ConfigFieldType.STRING, - default: "/games/Lossless Scaling/Lossless.dll", + default: "", description: "specify where Lossless.dll is stored" }, no_fp16: { @@ -55,8 +54,8 @@ export const CONFIG_SCHEMA: Record = { flow_scale: { name: "flow_scale", fieldType: ConfigFieldType.FLOAT, - default: 0.8, - description: "change the flow scale" + default: 1, + description: "motion estimation resolution scale" }, performance_mode: { name: "performance_mode", @@ -64,12 +63,6 @@ export const CONFIG_SCHEMA: Record = { default: false, description: "use a lighter model for FG (recommended for most games)" }, - hdr_mode: { - name: "hdr_mode", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "enable HDR mode (only for games that support HDR)" - }, experimental_present_mode: { name: "experimental_present_mode", fieldType: ConfigFieldType.STRING, @@ -133,7 +126,6 @@ export interface ConfigurationData { multiplier: number; flow_scale: number; performance_mode: boolean; - hdr_mode: boolean; experimental_present_mode: string; dxvk_frame_rate: number; enable_wow64: boolean; @@ -152,12 +144,11 @@ export function getFieldNames(): string[] { export function getDefaults(): ConfigurationData { return { - dll: "/games/Lossless Scaling/Lossless.dll", + dll: "", no_fp16: false, multiplier: 1, - flow_scale: 0.8, + flow_scale: 1, performance_mode: false, - hdr_mode: false, experimental_present_mode: "fifo", dxvk_frame_rate: 0, enable_wow64: false, @@ -177,7 +168,6 @@ export function getFieldTypes(): Record { multiplier: ConfigFieldType.INTEGER, flow_scale: ConfigFieldType.FLOAT, performance_mode: ConfigFieldType.BOOLEAN, - hdr_mode: ConfigFieldType.BOOLEAN, experimental_present_mode: ConfigFieldType.STRING, dxvk_frame_rate: ConfigFieldType.INTEGER, enable_wow64: ConfigFieldType.BOOLEAN, -- cgit v1.2.3 From e64e87e9eb9e3c183ad7807dffa356f47d14e825 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 5 Sep 2026 15:33:30 -0400 Subject: fix: migrate flatpak integration to v2 --- src/api/lsfgApi.ts | 1 - src/components/FlatpaksModal.tsx | 40 ---------------------------------------- 2 files changed, 41 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 82f37c8..2c9f4a9 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -84,7 +84,6 @@ export interface FlatpakExtensionStatus { success: boolean; message: string; error?: string; - installed_23_08: boolean; installed_24_08: boolean; installed_25_08: boolean; } diff --git a/src/components/FlatpaksModal.tsx b/src/components/FlatpaksModal.tsx index 16d0369..479b919 100644 --- a/src/components/FlatpaksModal.tsx +++ b/src/components/FlatpaksModal.tsx @@ -172,46 +172,6 @@ export const FlatpaksModal: FC = ({ closeModal }) => { {extensionStatus && extensionStatus.success ? ( <> - {/* 23.08 Runtime */} - - : } - > - { - 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 */} Date: Sat, 5 Sep 2026 17:55:31 -0400 Subject: chore: sync generated v2 schema --- src/config/generatedConfigSchema.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/config/generatedConfigSchema.ts b/src/config/generatedConfigSchema.ts index 8fae79a..20aa0e6 100644 --- a/src/config/generatedConfigSchema.ts +++ b/src/config/generatedConfigSchema.ts @@ -37,19 +37,19 @@ export const CONFIG_SCHEMA: Record = { name: "dll", fieldType: ConfigFieldType.STRING, default: "", - description: "specify where Lossless.dll is stored" + description: "override the lsfg-vk.dll path" }, no_fp16: { name: "no_fp16", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "force-disable fp16 (use on older nvidia cards)" + description: "disable FP16 acceleration" }, multiplier: { name: "multiplier", fieldType: ConfigFieldType.INTEGER, default: 1, - description: "change the fps multiplier" + description: "frame generation multiplier" }, flow_scale: { name: "flow_scale", @@ -61,13 +61,13 @@ export const CONFIG_SCHEMA: Record = { name: "performance_mode", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "use a lighter model for FG (recommended for most games)" + description: "use the lighter frame generation model" }, experimental_present_mode: { name: "experimental_present_mode", fieldType: ConfigFieldType.STRING, default: "fifo", - description: "override Vulkan present mode (may cause crashes)" + description: "control the v2 present mode override" }, dxvk_frame_rate: { name: "dxvk_frame_rate", @@ -85,13 +85,13 @@ export const CONFIG_SCHEMA: Record = { name: "disable_steamdeck_mode", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "disable Steam Deck mode (unlocks hidden settings in some games)" + description: "disable Steam Deck mode" }, mangohud_workaround: { name: "mangohud_workaround", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "Enables a transparent mangohud overlay, sometimes fixes issues with 2X multiplier in game mode" + description: "enable a transparent MangoHud overlay workaround" }, disable_vkbasalt: { name: "disable_vkbasalt", @@ -103,19 +103,19 @@ export const CONFIG_SCHEMA: Record = { name: "force_enable_vkbasalt", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "Force vkBasalt to engage to fix framepacing issues in gamemode" + description: "force-enable vkBasalt" }, enable_wsi: { name: "enable_wsi", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "Enable Gamescope WSI Layer, disable if frame generation isn't applying or isn't feeling smooth (use with HDR off)" + description: "enable the Gamescope WSI layer" }, enable_zink: { name: "enable_zink", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "Enable Zink (Vulkan-based OpenGL implementation) for OpenGL games" + description: "enable Zink for OpenGL games" }, }; -- cgit v1.2.3 From 77656ad88655effe0411808baf2fb90c629a24f8 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sat, 5 Sep 2026 18:00:50 -0400 Subject: chore: regenerate config schema --- src/config/generatedConfigSchema.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/config/generatedConfigSchema.ts b/src/config/generatedConfigSchema.ts index 20aa0e6..edbde88 100644 --- a/src/config/generatedConfigSchema.ts +++ b/src/config/generatedConfigSchema.ts @@ -79,7 +79,7 @@ export const CONFIG_SCHEMA: Record = { name: "enable_wow64", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "enable PROTON_USE_WOW64=1 for 32-bit games (use with ProtonGE to fix crashing)" + description: "enable PROTON_USE_WOW64=1 for 32-bit games" }, disable_steamdeck_mode: { name: "disable_steamdeck_mode", @@ -97,7 +97,7 @@ export const CONFIG_SCHEMA: Record = { name: "disable_vkbasalt", fieldType: ConfigFieldType.BOOLEAN, default: false, - description: "Disables vkBasalt layer which can conflict with LSFG (Reshade, some Decky plugins)" + description: "disable vkBasalt for games where it conflicts with lsfg-vk" }, force_enable_vkbasalt: { name: "force_enable_vkbasalt", -- cgit v1.2.3 From e8e469f99078858dc953663cba6f3428e80b1c5d Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sat, 5 Sep 2026 23:44:37 -0400 Subject: refactor: delegate runtime checks to lsfg-vk --- src/api/lsfgApi.ts | 27 ++------------- src/components/Content.tsx | 21 ++++++------ src/components/FlatpaksModal.tsx | 67 +++++++++++++++++++++++++++++++++++++ src/components/NerdStuffModal.tsx | 55 +++++------------------------- src/components/StatusDisplay.tsx | 21 +++++++----- src/hooks/useInstallationActions.ts | 12 +++++-- src/hooks/useLsfgHooks.ts | 37 +++++--------------- src/i18n/languages.json | 12 ------- 8 files changed, 120 insertions(+), 132 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 2c9f4a9..68cf6bf 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -11,28 +11,8 @@ export interface InstallationResult { export interface InstallationStatus { installed: boolean; - lib_exists: boolean; - json_exists: boolean; - script_exists: boolean; - lib_path: string; - json_path: string; - script_path: string; - error?: string; -} - -export interface DllDetectionResult { - detected: boolean; - path?: string; - source?: string; - message?: string; - error?: string; -} - -export interface DllStatsResult { - success: boolean; - dll_path?: string; - dll_sha256?: string; - dll_source?: string; + lossless_scaling_installed: boolean; + lossless_scaling_status: string; error?: string; } @@ -84,6 +64,7 @@ export interface FlatpakExtensionStatus { success: boolean; message: string; error?: string; + installed_23_08: boolean; installed_24_08: boolean; installed_25_08: boolean; } @@ -131,8 +112,6 @@ export interface ProfileResult { export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); -export const checkLosslessScalingDll = callable<[], DllDetectionResult>("check_lossless_scaling_dll"); -export const getDllStats = callable<[], DllStatsResult>("get_dll_stats"); export const getLsfgConfig = callable<[], ConfigResult>("get_lsfg_config"); export const getConfigSchema = callable<[], ConfigSchemaResult>("get_config_schema"); export const getLaunchOption = callable<[], LaunchOptionResult>("get_launch_option"); diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 5988e79..aab2fb8 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,6 +1,6 @@ import { useEffect } from "react"; import { PanelSection, showModal, ButtonItem, PanelSectionRow } from "@decky/ui"; -import { useInstallationStatus, useDllDetection, useLsfgConfig } from "../hooks/useLsfgHooks"; +import { useInstallationStatus, useLsfgConfig } from "../hooks/useLsfgHooks"; import { useProfileManagement } from "../hooks/useProfileManagement"; import { useInstallationActions } from "../hooks/useInstallationActions"; import { StatusDisplay } from "./StatusDisplay"; @@ -21,11 +21,12 @@ export function Content() { isInstalled, installationStatus, setIsInstalled, - setInstallationStatus + setInstallationStatus, + losslessScalingInstalled, + losslessScalingStatus, + checkInstallation } = useInstallationStatus(); - const { dllDetected, dllDetectionStatus } = useDllDetection(); - const { config, loadLsfgConfig, @@ -59,11 +60,11 @@ export function Content() { }; const onInstall = () => { - handleInstall(setIsInstalled, setInstallationStatus, loadLsfgConfig); + handleInstall(setIsInstalled, setInstallationStatus, loadLsfgConfig, checkInstallation); }; const onUninstall = () => { - handleUninstall(setIsInstalled, setInstallationStatus); + handleUninstall(setIsInstalled, setInstallationStatus, checkInstallation); }; const handleShowNerdStuff = () => { @@ -87,10 +88,10 @@ export function Content() { /> )} @@ -167,10 +168,10 @@ export function Content() { {isInstalled && ( <> void; @@ -38,6 +39,7 @@ export const FlatpaksModal: FC = ({ closeModal }) => { 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); @@ -63,6 +65,7 @@ export const FlatpaksModal: FC = ({ closeModal }) => { const handleExtensionOperation = async (operation: 'install' | 'uninstall', version: string) => { const operationId = `${operation}-${version}`; setOperationInProgress(operationId); + setOperationError(null); try { const result = operation === 'install' @@ -73,9 +76,16 @@ export const FlatpaksModal: FC = ({ closeModal }) => { // 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); } @@ -85,6 +95,7 @@ export const FlatpaksModal: FC = ({ closeModal }) => { const hasOverrides = app.has_filesystem_override && app.has_env_override; const operationId = `app-${app.app_id}`; setOperationInProgress(operationId); + setOperationError(null); try { const result = hasOverrides @@ -95,9 +106,16 @@ export const FlatpaksModal: FC = ({ closeModal }) => { // 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); } @@ -170,8 +188,57 @@ export const FlatpaksModal: FC = ({ closeModal }) => { {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 */} (null); const [configContent, setConfigContent] = useState(null); const [scriptContent, setScriptContent] = useState(null); const [loading, setLoading] = useState(true); @@ -28,13 +31,11 @@ export function NerdStuffModal({ closeModal }: NerdStuffModalProps) { setError(null); // Load all data in parallel - const [dllResult, configResult, scriptResult] = await Promise.all([ - getDllStats(), + const [configResult, scriptResult] = await Promise.all([ getConfigFileContent(), - getLaunchScriptContent() + getLaunchScriptContent(), ]); - setDllStats(dllResult); setConfigContent(configResult); setScriptContent(scriptResult); } catch (err) { @@ -47,11 +48,6 @@ export function NerdStuffModal({ closeModal }: NerdStuffModalProps) { loadData(); }, []); - const formatSHA256 = (hash: string) => { - // Format SHA256 hash for better readability (add spaces every 8 characters) - return hash.replace(/(.{8})/g, '$1 ').trim(); - }; - const copyToClipboard = async (text: string) => { try { await navigator.clipboard.writeText(text); @@ -73,41 +69,6 @@ export function NerdStuffModal({ closeModal }: NerdStuffModalProps) { {!loading && !error && ( <> - {/* DLL Stats Section */} - {dllStats && ( - <> - {!dllStats.success ? ( -
{dllStats.error || "Failed to get DLL stats"}
- ) : ( -
- - dllStats.dll_path && copyToClipboard(dllStats.dll_path)} - onActivate={() => dllStats.dll_path && copyToClipboard(dllStats.dll_path)} - > - {dllStats.dll_path || t('NERD_NOT_AVAILABLE', 'Not available')} - - - - - dllStats.dll_sha256 && copyToClipboard(dllStats.dll_sha256)} - onActivate={() => dllStats.dll_sha256 && copyToClipboard(dllStats.dll_sha256)} - > - {dllStats.dll_sha256 ? formatSHA256(dllStats.dll_sha256) : t('NERD_NOT_AVAILABLE', 'Not available')} - - - - {dllStats.dll_source && ( - -
{dllStats.dll_source}
-
- )} -
- )} - - )} - {/* Launch Script Section */} {scriptContent && ( @@ -168,7 +129,7 @@ export function NerdStuffModal({ closeModal }: NerdStuffModalProps) { )} )} - + {/* Close Button */} diff --git a/src/components/StatusDisplay.tsx b/src/components/StatusDisplay.tsx index 3a48a15..31584eb 100644 --- a/src/components/StatusDisplay.tsx +++ b/src/components/StatusDisplay.tsx @@ -1,24 +1,24 @@ import { PanelSectionRow } from "@decky/ui"; interface StatusDisplayProps { - dllDetected: boolean; - dllDetectionStatus: string; isInstalled: boolean; installationStatus: string; + losslessScalingInstalled: boolean; + losslessScalingStatus: string; } export function StatusDisplay({ - dllDetected, - dllDetectionStatus, isInstalled, - installationStatus + installationStatus, + losslessScalingInstalled, + losslessScalingStatus }: StatusDisplayProps) { return (
- {dllDetected ? "✅" : "❌"} + {losslessScalingInstalled ? "✅" : "❌"} - {dllDetectionStatus} + {losslessScalingInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"}
+ {!losslessScalingInstalled && losslessScalingStatus && ( +
+ {losslessScalingStatus} +
+ )}
void, setInstallationStatus: (value: string) => void, - reloadConfig?: () => Promise + reloadConfig?: () => Promise, + reloadStatus?: () => Promise ) => { setIsInstalling(true); setInstallationStatus("Installing lsfg-vk..."); @@ -30,6 +31,9 @@ export function useInstallationActions() { if (reloadConfig) { await reloadConfig(); } + if (reloadStatus) { + await reloadStatus(); + } } else { setInstallationStatus(`Installation failed: ${result.error}`); showInstallErrorToast(result.error); @@ -44,7 +48,8 @@ export function useInstallationActions() { const handleUninstall = async ( setIsInstalled: (value: boolean) => void, - setInstallationStatus: (value: string) => void + setInstallationStatus: (value: string) => void, + reloadStatus?: () => Promise ) => { setIsUninstalling(true); setInstallationStatus("Uninstalling lsfg-vk..."); @@ -54,6 +59,9 @@ export function useInstallationActions() { if (result.success) { setIsInstalled(false); setInstallationStatus("lsfg-vk uninstalled successfully!"); + if (reloadStatus) { + await reloadStatus(); + } showUninstallSuccessToast(); } else { setInstallationStatus(`Uninstallation failed: ${result.error}`); diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index d9bbe3e..597110e 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -1,7 +1,6 @@ import { useState, useEffect, useCallback } from "react"; import { checkLsfgVkInstalled, - checkLosslessScalingDll, getLsfgConfig, updateLsfgConfigFromObject, type ConfigUpdateResult @@ -12,11 +11,15 @@ import { showErrorToast, ToastMessages } from "../utils/toastUtils"; export function useInstallationStatus() { const [isInstalled, setIsInstalled] = useState(false); const [installationStatus, setInstallationStatus] = useState(""); + const [losslessScalingInstalled, setLosslessScalingInstalled] = useState(false); + const [losslessScalingStatus, setLosslessScalingStatus] = useState(""); const checkInstallation = async () => { try { const status = await checkLsfgVkInstalled(); setIsInstalled(status.installed); + setLosslessScalingInstalled(status.lossless_scaling_installed); + setLosslessScalingStatus(status.lossless_scaling_status || "Lossless Scaling Not Installed"); if (status.installed) { setInstallationStatus("lsfg-vk Installed"); } else { @@ -24,6 +27,8 @@ export function useInstallationStatus() { } return status.installed; } catch (error) { + setLosslessScalingInstalled(false); + setLosslessScalingStatus("Lossless Scaling Not Installed"); setInstallationStatus("lsfg-vk Not Installed"); return false; } @@ -38,38 +43,12 @@ export function useInstallationStatus() { installationStatus, setIsInstalled, setInstallationStatus, + losslessScalingInstalled, + losslessScalingStatus, checkInstallation }; } -export function useDllDetection() { - const [dllDetected, setDllDetected] = useState(false); - const [dllDetectionStatus, setDllDetectionStatus] = useState(""); - - const checkDllDetection = async () => { - try { - const result = await checkLosslessScalingDll(); - setDllDetected(result.detected); - if (result.detected) { - setDllDetectionStatus("Lossless Scaling Installed"); - } else { - setDllDetectionStatus("Lossless Scaling Not Installed"); - } - } catch (error) { - setDllDetectionStatus("Lossless Scaling Not Installed"); - } - }; - - useEffect(() => { - checkDllDetection(); - }, []); - - return { - dllDetected, - dllDetectionStatus - }; -} - export function useLsfgConfig() { const [config, setConfig] = useState(() => getDefaults()); diff --git a/src/i18n/languages.json b/src/i18n/languages.json index c1a49b8..46b4cd9 100644 --- a/src/i18n/languages.json +++ b/src/i18n/languages.json @@ -67,10 +67,6 @@ "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": "パス:", @@ -174,10 +170,6 @@ "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": "경로:", @@ -309,10 +301,6 @@ "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:", -- cgit v1.2.3 From 89e64a7dbddb8f713dd2ca37131924e8bd8ab51f Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sat, 5 Sep 2026 23:58:16 -0400 Subject: feat: select Lossless Scaling lsfg-vk branch --- src/api/lsfgApi.ts | 19 +++++++ src/components/Content.tsx | 22 ++++++++ src/components/StatusDisplay.tsx | 115 ++++++++++++++++++++++++++------------- src/hooks/useLsfgHooks.ts | 46 +++++++++++++++- 4 files changed, 163 insertions(+), 39 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 68cf6bf..64d43cb 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -16,6 +16,23 @@ export interface InstallationStatus { error?: string; } +export interface SteamBranchStatus { + success: boolean; + message: string; + error?: string; + installed: boolean; + manifest_path?: string; + selected_branch?: string; + current_branch?: string; + target_branch: string; + needs_switch: boolean; + restart_required: boolean; +} + +export interface SteamBranchOperationResult extends SteamBranchStatus { + changed: boolean; +} + // Use centralized configuration data type export type LsfgConfig = ConfigurationData; @@ -112,6 +129,8 @@ export interface ProfileResult { export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); +export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); +export const selectLosslessScalingBranch = callable<[], SteamBranchOperationResult>("select_lossless_scaling_branch"); export const getLsfgConfig = callable<[], ConfigResult>("get_lsfg_config"); export const getConfigSchema = callable<[], ConfigSchemaResult>("get_config_schema"); export const getLaunchOption = callable<[], LaunchOptionResult>("get_launch_option"); diff --git a/src/components/Content.tsx b/src/components/Content.tsx index aab2fb8..4e4e33a 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -15,6 +15,7 @@ import { NerdStuffModal } from "./NerdStuffModal"; import { FlatpaksModal } from "./FlatpaksModal"; import { ConfigurationData } from "../config/configSchema"; import t from '../i18n/i18n'; +import { showErrorToast, showSuccessToast } from "../utils/toastUtils"; export function Content() { const { @@ -24,6 +25,9 @@ export function Content() { setInstallationStatus, losslessScalingInstalled, losslessScalingStatus, + steamBranchStatus, + isSwitchingSteamBranch, + selectLosslessScalingBranch, checkInstallation } = useInstallationStatus(); @@ -67,6 +71,18 @@ export function Content() { handleUninstall(setIsInstalled, setInstallationStatus, checkInstallation); }; + const onSelectLosslessScalingBranch = async () => { + const result = await selectLosslessScalingBranch(); + if (result.success) { + showSuccessToast("Steam branch selected", result.message); + } else { + showErrorToast( + "Steam branch selection failed", + result.error || "Unable to select the lsfg-vk Steam branch" + ); + } + }; + const handleShowNerdStuff = () => { showModal(); }; @@ -92,6 +108,9 @@ export function Content() { installationStatus={installationStatus} losslessScalingInstalled={losslessScalingInstalled} losslessScalingStatus={losslessScalingStatus} + steamBranchStatus={steamBranchStatus} + isSwitchingSteamBranch={isSwitchingSteamBranch} + onSelectLosslessScalingBranch={onSelectLosslessScalingBranch} /> )} @@ -172,6 +191,9 @@ export function Content() { installationStatus={installationStatus} losslessScalingInstalled={losslessScalingInstalled} losslessScalingStatus={losslessScalingStatus} + steamBranchStatus={steamBranchStatus} + isSwitchingSteamBranch={isSwitchingSteamBranch} + onSelectLosslessScalingBranch={onSelectLosslessScalingBranch} /> void; } export function StatusDisplay({ isInstalled, installationStatus, losslessScalingInstalled, - losslessScalingStatus + losslessScalingStatus, + steamBranchStatus, + isSwitchingSteamBranch, + onSelectLosslessScalingBranch }: StatusDisplayProps) { return ( - -
-
- - {losslessScalingInstalled ? "✅" : "❌"} - - {losslessScalingInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"} -
- {!losslessScalingInstalled && losslessScalingStatus && ( -
- {losslessScalingStatus} + <> + +
+
+ + {losslessScalingInstalled ? "✅" : "❌"} + + {losslessScalingInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"} +
+ {!losslessScalingInstalled && losslessScalingStatus && ( +
+ {losslessScalingStatus} +
+ )} +
+ + {isInstalled ? "✅" : "❌"} + + {installationStatus}
- )} -
- - {isInstalled ? "✅" : "❌"} - - {installationStatus}
-
-
+ + + {losslessScalingInstalled && steamBranchStatus?.installed && ( + +
+
+ Steam branch: {steamBranchStatus.current_branch || "public"} + {steamBranchStatus.needs_switch && ( +
+ {steamBranchStatus.message} +
+ )} +
+ {steamBranchStatus.needs_switch && ( + + {isSwitchingSteamBranch ? "Selecting lsfg-vk..." : "Use lsfg-vk Steam branch"} + + )} +
+
+ )} + ); } diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index 597110e..dfbf2cd 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -2,8 +2,12 @@ import { useState, useEffect, useCallback } from "react"; import { checkLsfgVkInstalled, getLsfgConfig, + getLosslessScalingBranchStatus, + selectLosslessScalingBranch, updateLsfgConfigFromObject, - type ConfigUpdateResult + type ConfigUpdateResult, + type SteamBranchOperationResult, + type SteamBranchStatus } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; import { showErrorToast, ToastMessages } from "../utils/toastUtils"; @@ -13,8 +17,17 @@ export function useInstallationStatus() { const [installationStatus, setInstallationStatus] = useState(""); const [losslessScalingInstalled, setLosslessScalingInstalled] = useState(false); const [losslessScalingStatus, setLosslessScalingStatus] = useState(""); + const [steamBranchStatus, setSteamBranchStatus] = useState(null); + const [isSwitchingSteamBranch, setIsSwitchingSteamBranch] = useState(false); const checkInstallation = async () => { + try { + setSteamBranchStatus(await getLosslessScalingBranchStatus()); + } catch (error) { + console.error("Error checking Lossless Scaling Steam branch:", error); + setSteamBranchStatus(null); + } + try { const status = await checkLsfgVkInstalled(); setIsInstalled(status.installed); @@ -27,6 +40,7 @@ export function useInstallationStatus() { } return status.installed; } catch (error) { + setSteamBranchStatus(null); setLosslessScalingInstalled(false); setLosslessScalingStatus("Lossless Scaling Not Installed"); setInstallationStatus("lsfg-vk Not Installed"); @@ -34,6 +48,33 @@ export function useInstallationStatus() { } }; + const selectLosslessScalingBranchForUser = async (): Promise => { + setIsSwitchingSteamBranch(true); + try { + const result = await selectLosslessScalingBranch(); + setSteamBranchStatus(result); + return result; + } catch (error) { + const result: SteamBranchOperationResult = { + success: false, + message: "", + error: String(error), + installed: false, + manifest_path: undefined, + selected_branch: undefined, + current_branch: undefined, + target_branch: "lsfg-vk", + needs_switch: false, + restart_required: false, + changed: false + }; + setSteamBranchStatus(result); + return result; + } finally { + setIsSwitchingSteamBranch(false); + } + }; + useEffect(() => { checkInstallation(); }, []); @@ -45,6 +86,9 @@ export function useInstallationStatus() { setInstallationStatus, losslessScalingInstalled, losslessScalingStatus, + steamBranchStatus, + isSwitchingSteamBranch, + selectLosslessScalingBranch: selectLosslessScalingBranchForUser, checkInstallation }; } -- cgit v1.2.3 From f9352694a78a2bcfd00d237398a2b30de14c70be Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sun, 6 Sep 2026 00:06:58 -0400 Subject: fix: show Steam branch recovery action --- src/components/StatusDisplay.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/components/StatusDisplay.tsx b/src/components/StatusDisplay.tsx index b6290b0..5eb1823 100644 --- a/src/components/StatusDisplay.tsx +++ b/src/components/StatusDisplay.tsx @@ -20,13 +20,15 @@ export function StatusDisplay({ isSwitchingSteamBranch, onSelectLosslessScalingBranch }: StatusDisplayProps) { + const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; + return ( <>
- {losslessScalingInstalled ? "✅" : "❌"} + {losslessScalingAppInstalled ? "✅" : "❌"} - {losslessScalingInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"} + {losslessScalingAppInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"}
- {!losslessScalingInstalled && losslessScalingStatus && ( + {!losslessScalingAppInstalled && losslessScalingStatus && (
{losslessScalingStatus}
@@ -61,7 +63,7 @@ export function StatusDisplay({
- {losslessScalingInstalled && steamBranchStatus?.installed && ( + {steamBranchStatus?.installed && (
Date: Sun, 6 Sep 2026 00:16:19 -0400 Subject: refactor: make Steam branch integration read-only --- src/api/lsfgApi.ts | 5 ----- src/components/Content.tsx | 19 ------------------- src/components/StatusDisplay.tsx | 23 ++--------------------- src/hooks/useLsfgHooks.ts | 32 -------------------------------- 4 files changed, 2 insertions(+), 77 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 64d43cb..c0d6528 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -29,10 +29,6 @@ export interface SteamBranchStatus { restart_required: boolean; } -export interface SteamBranchOperationResult extends SteamBranchStatus { - changed: boolean; -} - // Use centralized configuration data type export type LsfgConfig = ConfigurationData; @@ -130,7 +126,6 @@ export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk") export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); -export const selectLosslessScalingBranch = callable<[], SteamBranchOperationResult>("select_lossless_scaling_branch"); export const getLsfgConfig = callable<[], ConfigResult>("get_lsfg_config"); export const getConfigSchema = callable<[], ConfigSchemaResult>("get_config_schema"); export const getLaunchOption = callable<[], LaunchOptionResult>("get_launch_option"); diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 4e4e33a..01f94c9 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -15,7 +15,6 @@ import { NerdStuffModal } from "./NerdStuffModal"; import { FlatpaksModal } from "./FlatpaksModal"; import { ConfigurationData } from "../config/configSchema"; import t from '../i18n/i18n'; -import { showErrorToast, showSuccessToast } from "../utils/toastUtils"; export function Content() { const { @@ -26,8 +25,6 @@ export function Content() { losslessScalingInstalled, losslessScalingStatus, steamBranchStatus, - isSwitchingSteamBranch, - selectLosslessScalingBranch, checkInstallation } = useInstallationStatus(); @@ -71,18 +68,6 @@ export function Content() { handleUninstall(setIsInstalled, setInstallationStatus, checkInstallation); }; - const onSelectLosslessScalingBranch = async () => { - const result = await selectLosslessScalingBranch(); - if (result.success) { - showSuccessToast("Steam branch selected", result.message); - } else { - showErrorToast( - "Steam branch selection failed", - result.error || "Unable to select the lsfg-vk Steam branch" - ); - } - }; - const handleShowNerdStuff = () => { showModal(); }; @@ -109,8 +94,6 @@ export function Content() { losslessScalingInstalled={losslessScalingInstalled} losslessScalingStatus={losslessScalingStatus} steamBranchStatus={steamBranchStatus} - isSwitchingSteamBranch={isSwitchingSteamBranch} - onSelectLosslessScalingBranch={onSelectLosslessScalingBranch} /> )} @@ -192,8 +175,6 @@ export function Content() { losslessScalingInstalled={losslessScalingInstalled} losslessScalingStatus={losslessScalingStatus} steamBranchStatus={steamBranchStatus} - isSwitchingSteamBranch={isSwitchingSteamBranch} - onSelectLosslessScalingBranch={onSelectLosslessScalingBranch} /> void; } export function StatusDisplay({ @@ -16,9 +14,7 @@ export function StatusDisplay({ installationStatus, losslessScalingInstalled, losslessScalingStatus, - steamBranchStatus, - isSwitchingSteamBranch, - onSelectLosslessScalingBranch + steamBranchStatus }: StatusDisplayProps) { const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; @@ -36,9 +32,6 @@ export function StatusDisplay({ gap: "6px" }} > - - {losslessScalingAppInstalled ? "✅" : "❌"} - {losslessScalingAppInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"}
{!losslessScalingAppInstalled && losslessScalingStatus && ( @@ -55,9 +48,6 @@ export function StatusDisplay({ gap: "6px" }} > - - {isInstalled ? "✅" : "❌"} - {installationStatus}
@@ -80,15 +70,6 @@ export function StatusDisplay({
)}
- {steamBranchStatus.needs_switch && ( - - {isSwitchingSteamBranch ? "Selecting lsfg-vk..." : "Use lsfg-vk Steam branch"} - - )}
)} diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index dfbf2cd..ea8b3d0 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -3,10 +3,8 @@ import { checkLsfgVkInstalled, getLsfgConfig, getLosslessScalingBranchStatus, - selectLosslessScalingBranch, updateLsfgConfigFromObject, type ConfigUpdateResult, - type SteamBranchOperationResult, type SteamBranchStatus } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; @@ -18,7 +16,6 @@ export function useInstallationStatus() { const [losslessScalingInstalled, setLosslessScalingInstalled] = useState(false); const [losslessScalingStatus, setLosslessScalingStatus] = useState(""); const [steamBranchStatus, setSteamBranchStatus] = useState(null); - const [isSwitchingSteamBranch, setIsSwitchingSteamBranch] = useState(false); const checkInstallation = async () => { try { @@ -48,33 +45,6 @@ export function useInstallationStatus() { } }; - const selectLosslessScalingBranchForUser = async (): Promise => { - setIsSwitchingSteamBranch(true); - try { - const result = await selectLosslessScalingBranch(); - setSteamBranchStatus(result); - return result; - } catch (error) { - const result: SteamBranchOperationResult = { - success: false, - message: "", - error: String(error), - installed: false, - manifest_path: undefined, - selected_branch: undefined, - current_branch: undefined, - target_branch: "lsfg-vk", - needs_switch: false, - restart_required: false, - changed: false - }; - setSteamBranchStatus(result); - return result; - } finally { - setIsSwitchingSteamBranch(false); - } - }; - useEffect(() => { checkInstallation(); }, []); @@ -87,8 +57,6 @@ export function useInstallationStatus() { losslessScalingInstalled, losslessScalingStatus, steamBranchStatus, - isSwitchingSteamBranch, - selectLosslessScalingBranch: selectLosslessScalingBranchForUser, checkInstallation }; } -- cgit v1.2.3 From ad2b182777bfd0a5ceef6e654df75ff13eb8b503 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sun, 6 Sep 2026 15:08:45 -0400 Subject: refactor: offload configuration to lsfg-vk --- src/api/lsfgApi.ts | 54 +-- src/components/ConfigurationSection.tsx | 307 ++--------------- src/components/Content.tsx | 48 +-- src/components/FpsMultiplierControl.tsx | 6 +- src/components/GameConfigurationSelector.tsx | 29 ++ src/components/ProfileManagement.tsx | 477 --------------------------- src/components/index.ts | 2 +- src/config/configSchema.ts | 6 +- src/config/generatedConfigSchema.ts | 193 ++--------- src/hooks/useGameConfiguration.ts | 68 ++++ src/hooks/useProfileManagement.ts | 194 ----------- 11 files changed, 183 insertions(+), 1201 deletions(-) create mode 100644 src/components/GameConfigurationSelector.tsx delete mode 100644 src/components/ProfileManagement.tsx create mode 100644 src/hooks/useGameConfiguration.ts delete mode 100644 src/hooks/useProfileManagement.ts (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index c0d6528..b38fa3b 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -44,12 +44,31 @@ export interface ConfigUpdateResult { error?: string; } +export interface GameConfigEntry { + appid: string; + profile: string; + config: LsfgConfig; +} +export interface InstalledGame { appid: string; name: string; } +export interface InstalledGamesResult { success: boolean; games?: InstalledGame[]; error?: string; } + +export interface GameConfigsResult { + success: boolean; + default?: LsfgConfig; + games?: GameConfigEntry[]; + error?: string; +} + +export interface GameConfigResult extends ConfigUpdateResult { + appid?: string; + exists?: boolean; + config?: LsfgConfig; +} + export interface ConfigSchemaResult { field_names: string[]; field_types: Record; defaults: ConfigurationData; - profiles?: string[]; - current_profile?: string; } export interface LaunchOptionResult { @@ -105,22 +124,6 @@ export interface FlatpakOperationResult { operation?: string; } -// Profile management interfaces -export interface ProfilesResult { - success: boolean; - profiles?: string[]; - current_profile?: string; - message?: string; - error?: string; -} - -export interface ProfileResult { - success: boolean; - profile_name?: string; - message?: string; - error?: string; -} - // API functions export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); @@ -146,17 +149,14 @@ export const updateLsfgConfig = callable< [ConfigurationData], ConfigUpdateResult >("update_lsfg_config"); +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 resetGameConfig = callable<[string], GameConfigResult>("reset_game_config"); +export const resetAllGameConfigs = callable<[], GameConfigsResult>("reset_all_game_configs"); // Legacy helper function for backward compatibility export const updateLsfgConfigFromObject = async (config: ConfigurationData): Promise => { return updateLsfgConfig(config); }; - -// Self-updater API functions -// Profile management API functions -export const getProfiles = callable<[], ProfilesResult>("get_profiles"); -export const createProfile = callable<[string, string?], ProfileResult>("create_profile"); -export const deleteProfile = callable<[string], ProfileResult>("delete_profile"); -export const renameProfile = callable<[string, string], ProfileResult>("rename_profile"); -export const setCurrentProfile = callable<[string], ProfileResult>("set_current_profile"); -export const updateProfileConfig = callable<[string, ConfigurationData], ConfigUpdateResult>("update_profile_config"); diff --git a/src/components/ConfigurationSection.tsx b/src/components/ConfigurationSection.tsx index e83bd58..c2bba7e 100644 --- a/src/components/ConfigurationSection.tsx +++ b/src/components/ConfigurationSection.tsx @@ -1,293 +1,28 @@ -import { PanelSectionRow, ToggleField, SliderField, ButtonItem } from "@decky/ui"; -import { useState, useEffect } from "react"; -import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; +import { PanelSectionRow, ToggleField, SliderField } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; -import { - FLOW_SCALE, NO_FP16, PERFORMANCE_MODE, - EXPERIMENTAL_PRESENT_MODE, DXVK_FRAME_RATE, DISABLE_STEAMDECK_MODE, - MANGOHUD_WORKAROUND, DISABLE_VKBASALT, FORCE_ENABLE_VKBASALT, ENABLE_WSI, ENABLE_ZINK -} from "../config/generatedConfigSchema"; -import t from '../i18n/i18n'; +import { FLOW_SCALE, PERFORMANCE_MODE, OVERRIDE_PRESENT_MODE, PRESERVE_SWAPCHAIN_IMAGE_COUNT, NO_FP16 } from "../config/configSchema"; interface ConfigurationSectionProps { config: ConfigurationData; - onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string) => Promise; + onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; } -const WORKAROUNDS_COLLAPSED_KEY = "lsfg-workarounds-collapsed"; -const CONFIG_COLLAPSED_KEY = "lsfg-config-collapsed"; - -export function ConfigurationSection({ - config, - onConfigChange -}: ConfigurationSectionProps) { - // Initialize with localStorage value, fallback to true if not found - const [configCollapsed, setConfigCollapsed] = useState(() => { - try { - const saved = localStorage.getItem(CONFIG_COLLAPSED_KEY); - return saved !== null ? JSON.parse(saved) : false; - } catch { - return false; - } - }); - - const [workaroundsCollapsed, setWorkaroundsCollapsed] = useState(() => { - try { - const saved = localStorage.getItem(WORKAROUNDS_COLLAPSED_KEY); - return saved !== null ? JSON.parse(saved) : true; - } catch { - return true; - } - }); - - // Persist workarounds collapse state to localStorage - useEffect(() => { - try { - localStorage.setItem(CONFIG_COLLAPSED_KEY, JSON.stringify(configCollapsed)); - } catch (error) { - console.warn("Failed to save config collapse state:", error); - } - }, [configCollapsed]); - - useEffect(() => { - try { - localStorage.setItem(WORKAROUNDS_COLLAPSED_KEY, JSON.stringify(workaroundsCollapsed)); - } catch (error) { - console.warn("Failed to save workarounds collapse state:", error); - } - }, [workaroundsCollapsed]); - - return ( - <> - - - {/* Config Section */} - -
- {t('CONFIG_SECTION_TITLE', 'Config')} -
-
- - -
- setConfigCollapsed(!configCollapsed)} - > - {configCollapsed ? ( - - ) : ( - - )} - -
-
- - {!configCollapsed && ( - <> - - onConfigChange(FLOW_SCALE, value)} - /> - - - - onConfigChange(NO_FP16, !value)} - /> - - - - 0 ? ` (${config.dxvk_frame_rate} FPS)` : ` (${t('CONFIG_BASE_FPS_CAP_OFF', 'Off')})`}`} - description={t('CONFIG_BASE_FPS_CAP_DESC', 'Base framerate cap for DirectX games, before frame multiplier. (Requires game restart to apply)')} - value={config.dxvk_frame_rate} - min={0} - max={60} - step={1} - onChange={(value) => onConfigChange(DXVK_FRAME_RATE, value)} - /> - - - - onConfigChange(EXPERIMENTAL_PRESENT_MODE, value ? "fifo" : "mailbox")} - /> - - - - onConfigChange(PERFORMANCE_MODE, value)} - /> - - - - )} - - {/* Workarounds Section */} - -
- {t('CONFIG_WORKAROUNDS_TITLE', 'Workarounds')} -
-
- - -
- setWorkaroundsCollapsed(!workaroundsCollapsed)} - > - {workaroundsCollapsed ? ( - - ) : ( - - )} - -
-
- - {!workaroundsCollapsed && ( - <> - - onConfigChange(ENABLE_WSI, value)} - /> - - - - onConfigChange('enable_wow64', value)} - /> - - - - - - - onConfigChange(MANGOHUD_WORKAROUND, value)} - /> - - - - { - if (value && config.force_enable_vkbasalt) { - // Turn off force enable when enabling disable - onConfigChange(FORCE_ENABLE_VKBASALT, false); - } - onConfigChange(DISABLE_VKBASALT, value); - }} - /> - - - - { - if (value && config.disable_vkbasalt) { - // Turn off disable when enabling force enable - onConfigChange(DISABLE_VKBASALT, false); - } - onConfigChange(FORCE_ENABLE_VKBASALT, value); - }} - /> - - - - onConfigChange(ENABLE_ZINK, value)} - /> - - - )} - - ); +export function ConfigurationSection({ config, onConfigChange }: ConfigurationSectionProps) { + return <> + + onConfigChange(FLOW_SCALE, value)} /> + + + onConfigChange(NO_FP16, !value)} /> + + + onConfigChange(PERFORMANCE_MODE, value)} /> + + + onConfigChange(OVERRIDE_PRESENT_MODE, value)} /> + + + onConfigChange(PRESERVE_SWAPCHAIN_IMAGE_COUNT, value)} /> + + ; } diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 01f94c9..bdb3a04 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,12 +1,12 @@ import { useEffect } from "react"; import { PanelSection, showModal, ButtonItem, PanelSectionRow } from "@decky/ui"; -import { useInstallationStatus, useLsfgConfig } from "../hooks/useLsfgHooks"; -import { useProfileManagement } from "../hooks/useProfileManagement"; +import { useInstallationStatus } from "../hooks/useLsfgHooks"; +import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallationActions } from "../hooks/useInstallationActions"; import { StatusDisplay } from "./StatusDisplay"; import { InstallationButton } from "./InstallationButton"; import { ConfigurationSection } from "./ConfigurationSection"; -import { ProfileManagement } from "./ProfileManagement"; +import { GameConfigurationSelector } from "./GameConfigurationSelector"; import { UsageInstructions } from "./UsageInstructions"; import { SmartClipboardButton } from "./SmartClipboardButton"; import { FgmodClipboardButton } from "./FgmodClipboardButton"; @@ -28,40 +28,20 @@ export function Content() { checkInstallation } = useInstallationStatus(); - const { - config, - loadLsfgConfig, - updateField - } = useLsfgConfig(); - - const { - currentProfile, - updateProfileConfig, - loadProfiles - } = useProfileManagement(); + const { config, targets, runningGame, selectedAppId, setSelectedAppId, save, resetSelected, resetAll, reload } = useGameConfiguration(); const { isInstalling, isUninstalling, handleInstall, handleUninstall } = useInstallationActions(); useEffect(() => { - if (isInstalled) { - loadLsfgConfig(); - } - }, [isInstalled, loadLsfgConfig]); - - const handleConfigChange = async (fieldName: keyof ConfigurationData, value: boolean | number | string) => { - if (currentProfile) { - const newConfig = { ...config, [fieldName]: value }; - const result = await updateProfileConfig(currentProfile, newConfig); - if (result.success) { - await loadLsfgConfig(); - } - } else { - await updateField(fieldName, value); - } + if (isInstalled) void reload(); + }, [isInstalled, reload]); + + const handleConfigChange = async (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => { + await save({ ...config, [fieldName]: value }); }; const onInstall = () => { - handleInstall(setIsInstalled, setInstallationStatus, loadLsfgConfig, checkInstallation); + handleInstall(setIsInstalled, setInstallationStatus, reload, checkInstallation); }; const onUninstall = () => { @@ -124,13 +104,7 @@ export function Content() { )} {isInstalled && ( - { - await loadProfiles(); - await loadLsfgConfig(); - }} - /> + )} {isInstalled && ( diff --git a/src/components/FpsMultiplierControl.tsx b/src/components/FpsMultiplierControl.tsx index 206643e..5069c9a 100644 --- a/src/components/FpsMultiplierControl.tsx +++ b/src/components/FpsMultiplierControl.tsx @@ -1,11 +1,11 @@ import { PanelSectionRow, DialogButton, Focusable } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; import { MULTIPLIER } from "../config/generatedConfigSchema"; -import t from '../i18n/i18n'; +import t from "../i18n/i18n"; interface FpsMultiplierControlProps { config: ConfigurationData; - onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string) => Promise; + onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; } export function FpsMultiplierControl({ @@ -50,7 +50,7 @@ export function FpsMultiplierControl({ textAlign: "center" }} > - {config.multiplier < 2 ? t('MULTIPLIER_OFF', 'OFF') : `${config.multiplier}X`} + {config.multiplier === 1 ? t('MULTIPLIER_OFF', 'OFF') : `${config.multiplier}X`} void; + onReset: () => Promise; + onResetAll: () => Promise; +} + +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}` })), + ]; + return <> + + onSelect(String(option.data))} /> + + + void onReset()} disabled={!selectedAppId}>Reset selected game + + + void onResetAll()} disabled={!targets.some((target) => target.configured)}>Reset all game profiles + + ; +} diff --git a/src/components/ProfileManagement.tsx b/src/components/ProfileManagement.tsx deleted file mode 100644 index 626d54c..0000000 --- a/src/components/ProfileManagement.tsx +++ /dev/null @@ -1,477 +0,0 @@ -import { useState, useEffect } from "react"; -import { - PanelSectionRow, - Dropdown, - DropdownOption, - showModal, - ConfirmModal, - Field, - DialogButton, - ButtonItem, - ModalRoot, - TextField, - Focusable, - AppOverview, - Router -} from "@decky/ui"; -import { RiArrowDownSFill, RiArrowUpSFill, RiEditLine, RiDeleteBinLine } from "react-icons/ri"; -import { - getProfiles, - createProfile, - deleteProfile, - renameProfile, - setCurrentProfile, - ProfilesResult, - ProfileResult -} from "../api/lsfgApi"; -import { showSuccessToast, showErrorToast } from "../utils/toastUtils"; -import t from '../i18n/i18n'; - -const PROFILES_COLLAPSED_KEY = 'lsfg-profiles-collapsed'; - -interface TextInputModalProps { - title: string; - description: string; - defaultValue?: string; - okText?: string; - cancelText?: string; - onOK: (value: string) => void; - closeModal?: () => void; -} - -function TextInputModal({ - title, - description, - defaultValue = "", - okText = "OK", - cancelText = "Cancel", - onOK, - closeModal -}: TextInputModalProps) { - const [value, setValue] = useState(defaultValue); - - const handleOK = () => { - if (value.trim()) { - onOK(value); - closeModal?.(); - } - }; - - return ( - -
-

{title}

-

{description}

- -
- - setValue(e?.target?.value || "")} - style={{ width: "100%" }} - /> - -
- - - - {cancelText} - - - {okText} - - -
-
- ); -} - -interface ProfileManagementProps { - currentProfile?: string; - onProfileChange?: (profileName: string) => void; -} - -export function ProfileManagement({ currentProfile, onProfileChange }: ProfileManagementProps) { - const [profiles, setProfiles] = useState([]); - const [selectedProfile, setSelectedProfile] = useState(currentProfile || "decky-lsfg-vk"); - const [isLoading, setIsLoading] = useState(false); - const [mainRunningApp, setMainRunningApp] = useState(undefined); - - // Initialize with localStorage value, fallback to false (expanded) if not found - const [profilesCollapsed, setProfilesCollapsed] = useState(() => { - try { - const saved = localStorage.getItem(PROFILES_COLLAPSED_KEY); - return saved !== null ? JSON.parse(saved) : false; - } catch { - return false; - } - }); - - // Persist profiles collapse state to localStorage - useEffect(() => { - try { - localStorage.setItem(PROFILES_COLLAPSED_KEY, JSON.stringify(profilesCollapsed)); - } catch (error) { - console.warn('Failed to save profiles collapse state:', error); - } - }, [profilesCollapsed]); - - // Load profiles on component mount - useEffect(() => { - loadProfiles(); - }, []); - - // Update selected profile when prop changes - useEffect(() => { - if (currentProfile) { - setSelectedProfile(currentProfile); - } - }, [currentProfile]); - - // Poll for running app every 2 seconds - useEffect(() => { - const checkRunningApp = () => { - setMainRunningApp(Router.MainRunningApp); - }; - - // Check immediately - checkRunningApp(); - - // Set up polling interval - const interval = setInterval(checkRunningApp, 2000); - - // Cleanup interval on unmount - return () => clearInterval(interval); - }, []); - - const loadProfiles = async () => { - try { - const result: ProfilesResult = await getProfiles(); - if (result.success && result.profiles) { - setProfiles(result.profiles); - if (result.current_profile) { - setSelectedProfile(result.current_profile); - } - } else { - console.error("Failed to load profiles:", result.error); - showErrorToast("Failed to load profiles", result.error || "Unknown error"); - } - } catch (error) { - console.error("Error loading profiles:", error); - showErrorToast("Error loading profiles", String(error)); - } - }; - - const handleProfileChange = async (profileName: string) => { - setIsLoading(true); - try { - const result: ProfileResult = await setCurrentProfile(profileName); - if (result.success) { - setSelectedProfile(profileName); - showSuccessToast("Profile switched", `Switched to profile: ${profileName}`); - onProfileChange?.(profileName); - } else { - console.error("Failed to switch profile:", result.error); - showErrorToast("Failed to switch profile", result.error || "Unknown error"); - } - } catch (error) { - console.error("Error switching profile:", error); - showErrorToast("Error switching profile", String(error)); - } finally { - setIsLoading(false); - } - }; - - const handleCreateProfile = () => { - showModal( - { - if (name.trim()) { - createNewProfile(name.trim()); - } - }} - /> - ); - }; - - const createNewProfile = async (profileName: string) => { - setIsLoading(true); - try { - const result: ProfileResult = await createProfile(profileName, selectedProfile); - if (result.success) { - // Use the normalized name returned from backend (spaces converted to dashes) - const actualProfileName = result.profile_name || profileName; - showSuccessToast("Profile created", `Created profile: ${actualProfileName}`); - await loadProfiles(); - // Automatically switch to the newly created profile using the normalized name - await handleProfileChange(actualProfileName); - } else { - console.error("Failed to create profile:", result.error); - showErrorToast("Failed to create profile", result.error || "Unknown error"); - } - } catch (error) { - console.error("Error creating profile:", error); - showErrorToast("Error creating profile", String(error)); - } finally { - setIsLoading(false); - } - }; - - const handleDeleteProfile = () => { - if (selectedProfile === "decky-lsfg-vk") { - showErrorToast(t('PROFILE_CANNOT_DELETE_TITLE', 'Cannot delete default profile'), t('PROFILE_CANNOT_DELETE_MSG', 'The default profile cannot be deleted')); - return; - } - - showModal( - deleteSelectedProfile()} - /> - ); - }; - - const deleteSelectedProfile = async () => { - setIsLoading(true); - try { - const result: ProfileResult = await deleteProfile(selectedProfile); - if (result.success) { - showSuccessToast("Profile deleted", `Deleted profile: ${selectedProfile}`); - await loadProfiles(); - // If we deleted the current profile, it should have switched to default - setSelectedProfile("decky-lsfg-vk"); - onProfileChange?.("decky-lsfg-vk"); - } else { - console.error("Failed to delete profile:", result.error); - showErrorToast("Failed to delete profile", result.error || "Unknown error"); - } - } catch (error) { - console.error("Error deleting profile:", error); - showErrorToast("Error deleting profile", String(error)); - } finally { - setIsLoading(false); - } - }; - - const handleDropdownChange = (option: DropdownOption) => { - if (option.data === "__NEW_PROFILE__") { - handleCreateProfile(); - } else { - handleProfileChange(option.data); - } - }; - - const handleRenameProfile = () => { - if (selectedProfile === "decky-lsfg-vk") { - showErrorToast(t('PROFILE_CANNOT_RENAME_TITLE', 'Cannot rename default profile'), t('PROFILE_CANNOT_RENAME_MSG', 'The default profile cannot be renamed')); - return; - } - - showModal( - { - if (newName.trim() && newName.trim() !== selectedProfile) { - renameSelectedProfile(newName.trim()); - } - }} - /> - ); - }; - - const renameSelectedProfile = async (newName: string) => { - setIsLoading(true); - try { - const result: ProfileResult = await renameProfile(selectedProfile, newName); - if (result.success) { - // Use the normalized name returned from backend (spaces converted to dashes) - const actualNewName = result.profile_name || newName; - showSuccessToast("Profile renamed", `Renamed profile to: ${actualNewName}`); - await loadProfiles(); - setSelectedProfile(actualNewName); - onProfileChange?.(actualNewName); - } else { - console.error("Failed to rename profile:", result.error); - showErrorToast("Failed to rename profile", result.error || "Unknown error"); - } - } catch (error) { - console.error("Error renaming profile:", error); - showErrorToast("Error renaming profile", String(error)); - } finally { - setIsLoading(false); - } - }; - - const profileOptions: DropdownOption[] = [ - ...profiles.map((profile: string) => ({ - data: profile, - label: profile === "decky-lsfg-vk" ? t('PROFILE_DEFAULT', 'Default') : profile - })), - { - data: "__NEW_PROFILE__", - label: t('PROFILE_NEW', 'New Profile') - } - ]; - - return ( - <> - - - {/* Display currently running game info - always visible */} - {mainRunningApp && ( - -
- {mainRunningApp.display_name} running. {t('PROFILE_CLOSE_GAME', 'Close game to change profile.')} -
-
- )} - - -
- {t('PROFILE_SECTION_TITLE', 'Profile:')} {selectedProfile === "decky-lsfg-vk" ? t('PROFILE_DEFAULT', 'Default') : selectedProfile} -
-
- - -
- setProfilesCollapsed(!profilesCollapsed)} - > - {profilesCollapsed ? ( - - ) : ( - - )} - -
-
- - {!profilesCollapsed && ( - <> - - - - - - - - - - - - - - - - - - - )} - - ); -} diff --git a/src/components/index.ts b/src/components/index.ts index bec45ae..4284aee 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -8,4 +8,4 @@ export { SmartClipboardButton } from "./SmartClipboardButton"; export { FgmodClipboardButton } from "./FgmodClipboardButton"; export { NerdStuffModal } from "./NerdStuffModal"; export { FlatpaksModal } from "./FlatpaksModal"; -export { ProfileManagement } from "./ProfileManagement"; +export { GameConfigurationSelector } from "./GameConfigurationSelector"; diff --git a/src/config/configSchema.ts b/src/config/configSchema.ts index befbd8d..bd72e8c 100644 --- a/src/config/configSchema.ts +++ b/src/config/configSchema.ts @@ -6,8 +6,6 @@ export { getFieldNames, getDefaults, getFieldTypes, - DLL, NO_FP16, MULTIPLIER, FLOW_SCALE, PERFORMANCE_MODE, - EXPERIMENTAL_PRESENT_MODE, DXVK_FRAME_RATE, ENABLE_WOW64, - DISABLE_STEAMDECK_MODE, MANGOHUD_WORKAROUND, DISABLE_VKBASALT, - FORCE_ENABLE_VKBASALT, ENABLE_WSI, ENABLE_ZINK + DLL, NO_FP16, ACTIVE_IN, PACING_MODE, MULTIPLIER, FLOW_SCALE, + PERFORMANCE_MODE, OVERRIDE_PRESENT_MODE, PRESERVE_SWAPCHAIN_IMAGE_COUNT } from './generatedConfigSchema'; diff --git a/src/config/generatedConfigSchema.ts b/src/config/generatedConfigSchema.ts index edbde88..71459eb 100644 --- a/src/config/generatedConfigSchema.ts +++ b/src/config/generatedConfigSchema.ts @@ -1,182 +1,31 @@ -// src/config/generatedConfigSchema.ts -// Configuration field type enum - matches Python -export enum ConfigFieldType { - BOOLEAN = "boolean", - INTEGER = "integer", - FLOAT = "float", - STRING = "string" -} +export enum ConfigFieldType { BOOLEAN = "boolean", INTEGER = "integer", FLOAT = "float", STRING = "string", ARRAY = "array" } -// Field name constants for type-safe access export const DLL = "dll" as const; export const NO_FP16 = "no_fp16" as const; +export const ACTIVE_IN = "active_in" as const; +export const PACING_MODE = "pacing_mode" as const; export const MULTIPLIER = "multiplier" as const; export const FLOW_SCALE = "flow_scale" as const; export const PERFORMANCE_MODE = "performance_mode" as const; -export const EXPERIMENTAL_PRESENT_MODE = "experimental_present_mode" as const; -export const DXVK_FRAME_RATE = "dxvk_frame_rate" as const; -export const ENABLE_WOW64 = "enable_wow64" as const; -export const DISABLE_STEAMDECK_MODE = "disable_steamdeck_mode" as const; -export const MANGOHUD_WORKAROUND = "mangohud_workaround" as const; -export const DISABLE_VKBASALT = "disable_vkbasalt" as const; -export const FORCE_ENABLE_VKBASALT = "force_enable_vkbasalt" as const; -export const ENABLE_WSI = "enable_wsi" as const; -export const ENABLE_ZINK = "enable_zink" as const; +export const OVERRIDE_PRESENT_MODE = "override_present_mode" as const; +export const PRESERVE_SWAPCHAIN_IMAGE_COUNT = "preserve_swapchain_image_count" as const; -// Configuration field definition -export interface ConfigField { - name: string; - fieldType: ConfigFieldType; - default: boolean | number | string; - description: string; +export interface ConfigField { name: string; fieldType: ConfigFieldType; default: boolean | number | string | string[]; description: string; } +export interface ConfigurationData { + dll: string; no_fp16: boolean; active_in: string[]; pacing_mode: string; multiplier: number; + flow_scale: number; performance_mode: boolean; override_present_mode: boolean; preserve_swapchain_image_count: boolean; } - -// Configuration schema - auto-generated from Python export const CONFIG_SCHEMA: Record = { - dll: { - name: "dll", - fieldType: ConfigFieldType.STRING, - default: "", - description: "override the lsfg-vk.dll path" - }, - no_fp16: { - name: "no_fp16", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "disable FP16 acceleration" - }, - multiplier: { - name: "multiplier", - fieldType: ConfigFieldType.INTEGER, - default: 1, - description: "frame generation multiplier" - }, - flow_scale: { - name: "flow_scale", - fieldType: ConfigFieldType.FLOAT, - default: 1, - description: "motion estimation resolution scale" - }, - performance_mode: { - name: "performance_mode", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "use the lighter frame generation model" - }, - experimental_present_mode: { - name: "experimental_present_mode", - fieldType: ConfigFieldType.STRING, - default: "fifo", - description: "control the v2 present mode override" - }, - dxvk_frame_rate: { - name: "dxvk_frame_rate", - fieldType: ConfigFieldType.INTEGER, - default: 0, - description: "base framerate cap for DirectX games before frame multiplier" - }, - enable_wow64: { - name: "enable_wow64", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "enable PROTON_USE_WOW64=1 for 32-bit games" - }, - disable_steamdeck_mode: { - name: "disable_steamdeck_mode", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "disable Steam Deck mode" - }, - mangohud_workaround: { - name: "mangohud_workaround", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "enable a transparent MangoHud overlay workaround" - }, - disable_vkbasalt: { - name: "disable_vkbasalt", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "disable vkBasalt for games where it conflicts with lsfg-vk" - }, - force_enable_vkbasalt: { - name: "force_enable_vkbasalt", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "force-enable vkBasalt" - }, - enable_wsi: { - name: "enable_wsi", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "enable the Gamescope WSI layer" - }, - enable_zink: { - name: "enable_zink", - fieldType: ConfigFieldType.BOOLEAN, - default: false, - description: "enable Zink for OpenGL games" - }, + dll: { name: "dll", fieldType: ConfigFieldType.STRING, default: "", description: "Override the lsfg-vk.dll path" }, + no_fp16: { name: "no_fp16", fieldType: ConfigFieldType.BOOLEAN, default: false, description: "Disable FP16 acceleration" }, + active_in: { name: "active_in", fieldType: ConfigFieldType.ARRAY, default: [], description: "Steam AppID or executable identifiers" }, + pacing_mode: { name: "pacing_mode", fieldType: ConfigFieldType.STRING, default: "vsync", description: "Frame pacing mode" }, + multiplier: { name: "multiplier", fieldType: ConfigFieldType.INTEGER, default: 2, description: "Frame generation multiplier" }, + flow_scale: { name: "flow_scale", fieldType: ConfigFieldType.FLOAT, default: 1, description: "Motion estimation resolution scale" }, + performance_mode: { name: "performance_mode", fieldType: ConfigFieldType.BOOLEAN, default: false, description: "Use the lighter frame generation model" }, + override_present_mode: { name: "override_present_mode", fieldType: ConfigFieldType.BOOLEAN, default: true, description: "Override present mode" }, + preserve_swapchain_image_count: { name: "preserve_swapchain_image_count", fieldType: ConfigFieldType.BOOLEAN, default: false, description: "Preserve the swapchain image count" }, }; - -// Type-safe configuration data structure -export interface ConfigurationData { - dll: string; - no_fp16: boolean; - multiplier: number; - flow_scale: number; - performance_mode: boolean; - experimental_present_mode: string; - dxvk_frame_rate: number; - enable_wow64: boolean; - disable_steamdeck_mode: boolean; - mangohud_workaround: boolean; - disable_vkbasalt: boolean; - force_enable_vkbasalt: boolean; - enable_wsi: boolean; - enable_zink: boolean; -} - -// Helper functions -export function getFieldNames(): string[] { - return Object.keys(CONFIG_SCHEMA); -} - -export function getDefaults(): ConfigurationData { - return { - dll: "", - no_fp16: false, - multiplier: 1, - flow_scale: 1, - performance_mode: false, - experimental_present_mode: "fifo", - dxvk_frame_rate: 0, - enable_wow64: false, - disable_steamdeck_mode: false, - mangohud_workaround: false, - disable_vkbasalt: false, - force_enable_vkbasalt: false, - enable_wsi: false, - enable_zink: false, - }; -} - -export function getFieldTypes(): Record { - return { - dll: ConfigFieldType.STRING, - no_fp16: ConfigFieldType.BOOLEAN, - multiplier: ConfigFieldType.INTEGER, - flow_scale: ConfigFieldType.FLOAT, - performance_mode: ConfigFieldType.BOOLEAN, - experimental_present_mode: ConfigFieldType.STRING, - dxvk_frame_rate: ConfigFieldType.INTEGER, - enable_wow64: ConfigFieldType.BOOLEAN, - disable_steamdeck_mode: ConfigFieldType.BOOLEAN, - mangohud_workaround: ConfigFieldType.BOOLEAN, - disable_vkbasalt: ConfigFieldType.BOOLEAN, - force_enable_vkbasalt: ConfigFieldType.BOOLEAN, - enable_wsi: ConfigFieldType.BOOLEAN, - enable_zink: ConfigFieldType.BOOLEAN, - }; -} - +export function getFieldNames(): string[] { return Object.keys(CONFIG_SCHEMA); } +export function getDefaults(): ConfigurationData { return { dll: "", no_fp16: false, active_in: [], pacing_mode: "vsync", multiplier: 2, flow_scale: 1, performance_mode: false, override_present_mode: true, preserve_swapchain_image_count: false }; } +export function getFieldTypes(): Record { return Object.fromEntries(Object.entries(CONFIG_SCHEMA).map(([key, value]) => [key, value.fieldType])); } diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts new file mode 100644 index 0000000..e0ba360 --- /dev/null +++ b/src/hooks/useGameConfiguration.ts @@ -0,0 +1,68 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +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 function useGameConfiguration() { + const [defaultConfig, setDefaultConfig] = useState(getDefaults()); + const [games, setGames] = useState([]); + const [installedGames, setInstalledGames] = useState([]); + const [selectedAppId, setSelectedAppId] = useState(""); + const [runningGame, setRunningGame] = useState(null); + const autoSelected = useRef(false); + + const load = useCallback(async () => { + const [result, installed] = await Promise.all([getGameConfigs(), getInstalledGames()]); + if (result.success) { + setDefaultConfig(result.default || getDefaults()); + setGames(result.games || []); + } + if (installed.success) setInstalledGames(installed.games || []); + }, []); + + useEffect(() => { load(); }, [load]); + 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); + }; + poll(); + const interval = window.setInterval(poll, 2000); + return () => window.clearInterval(interval); + }, [games]); + useEffect(() => { + if (!autoSelected.current && runningGame) { + autoSelected.current = true; + setSelectedAppId(runningGame.appid); + } + }, [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 }); + if (runningGame && !configured.some((game) => game.appid === runningGame.appid)) configured.unshift(runningGame); + return configured; + }, [games, installedGames, runningGame]); + const selected = selectedAppId ? games.find((game) => game.appid === selectedAppId)?.config : defaultConfig; + const config = selected || defaultConfig; + + const save = useCallback(async (next: ConfigurationData) => { + if (!selectedAppId) { + const result = await updateLsfgConfig(next); + if (result.success) setDefaultConfig(next); + return; + } + const result = await updateGameConfig(selectedAppId, next); + if (result.success) await load(); + }, [load, selectedAppId]); + + const resetSelected = useCallback(async () => { + if (selectedAppId) { await resetGameConfig(selectedAppId); setSelectedAppId(""); await load(); } + }, [load, selectedAppId]); + const resetAll = useCallback(async () => { await resetAllGameConfigs(); setSelectedAppId(""); await load(); }, [load]); + + return { config, defaultConfig, games, targets, runningGame, selectedAppId, setSelectedAppId, save, resetSelected, resetAll, reload: load }; +} diff --git a/src/hooks/useProfileManagement.ts b/src/hooks/useProfileManagement.ts deleted file mode 100644 index a5f2a07..0000000 --- a/src/hooks/useProfileManagement.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { useState, useEffect, useCallback } from "react"; -import { - getProfiles, - createProfile, - deleteProfile, - renameProfile, - setCurrentProfile, - updateProfileConfig, - type ProfilesResult, - type ProfileResult, - type ConfigUpdateResult -} from "../api/lsfgApi"; -import { ConfigurationData } from "../config/configSchema"; -import { showSuccessToast, showErrorToast } from "../utils/toastUtils"; - -export function useProfileManagement() { - const [profiles, setProfiles] = useState([]); - const [currentProfile, setCurrentProfileState] = useState("decky-lsfg-vk"); - const [isLoading, setIsLoading] = useState(false); - - // Load profiles on hook initialization - const loadProfiles = useCallback(async () => { - try { - const result: ProfilesResult = await getProfiles(); - if (result.success && result.profiles) { - setProfiles(result.profiles); - if (result.current_profile) { - setCurrentProfileState(result.current_profile); - } - return result; - } else { - console.error("Failed to load profiles:", result.error); - showErrorToast("Failed to load profiles", result.error || "Unknown error"); - return result; - } - } catch (error) { - console.error("Error loading profiles:", error); - showErrorToast("Error loading profiles", String(error)); - return { success: false, error: String(error) }; - } - }, []); - - // Create a new profile - const handleCreateProfile = useCallback(async (profileName: string, sourceProfile?: string) => { - setIsLoading(true); - try { - const result: ProfileResult = await createProfile(profileName, sourceProfile || currentProfile); - if (result.success) { - // Use the normalized name returned from backend (spaces converted to dashes) - const actualProfileName = result.profile_name || profileName; - showSuccessToast("Profile created", `Created profile: ${actualProfileName}`); - await loadProfiles(); - return result; - } else { - console.error("Failed to create profile:", result.error); - showErrorToast("Failed to create profile", result.error || "Unknown error"); - return result; - } - } catch (error) { - console.error("Error creating profile:", error); - showErrorToast("Error creating profile", String(error)); - return { success: false, error: String(error) }; - } finally { - setIsLoading(false); - } - }, [currentProfile, loadProfiles]); - - // Delete a profile - const handleDeleteProfile = useCallback(async (profileName: string) => { - if (profileName === "decky-lsfg-vk") { - showErrorToast("Cannot delete default profile", "The default profile cannot be deleted"); - return { success: false, error: "Cannot delete default profile" }; - } - - setIsLoading(true); - try { - const result: ProfileResult = await deleteProfile(profileName); - if (result.success) { - showSuccessToast("Profile deleted", `Deleted profile: ${profileName}`); - await loadProfiles(); - // If we deleted the current profile, it should have switched to default - if (currentProfile === profileName) { - setCurrentProfileState("decky-lsfg-vk"); - } - return result; - } else { - console.error("Failed to delete profile:", result.error); - showErrorToast("Failed to delete profile", result.error || "Unknown error"); - return result; - } - } catch (error) { - console.error("Error deleting profile:", error); - showErrorToast("Error deleting profile", String(error)); - return { success: false, error: String(error) }; - } finally { - setIsLoading(false); - } - }, [currentProfile, loadProfiles]); - - // Rename a profile - const handleRenameProfile = useCallback(async (oldName: string, newName: string) => { - if (oldName === "decky-lsfg-vk") { - showErrorToast("Cannot rename default profile", "The default profile cannot be renamed"); - return { success: false, error: "Cannot rename default profile" }; - } - - setIsLoading(true); - try { - const result: ProfileResult = await renameProfile(oldName, newName); - if (result.success) { - // Use the normalized name returned from backend (spaces converted to dashes) - const actualNewName = result.profile_name || newName; - showSuccessToast("Profile renamed", `Renamed profile to: ${actualNewName}`); - await loadProfiles(); - // Update current profile if it was renamed - if (currentProfile === oldName) { - setCurrentProfileState(actualNewName); - } - return result; - } else { - console.error("Failed to rename profile:", result.error); - showErrorToast("Failed to rename profile", result.error || "Unknown error"); - return result; - } - } catch (error) { - console.error("Error renaming profile:", error); - showErrorToast("Error renaming profile", String(error)); - return { success: false, error: String(error) }; - } finally { - setIsLoading(false); - } - }, [currentProfile, loadProfiles]); - - // Set the current active profile - const handleSetCurrentProfile = useCallback(async (profileName: string) => { - setIsLoading(true); - try { - const result: ProfileResult = await setCurrentProfile(profileName); - if (result.success) { - setCurrentProfileState(profileName); - showSuccessToast("Profile switched", `Switched to profile: ${profileName}`); - return result; - } else { - console.error("Failed to switch profile:", result.error); - showErrorToast("Failed to switch profile", result.error || "Unknown error"); - return result; - } - } catch (error) { - console.error("Error switching profile:", error); - showErrorToast("Error switching profile", String(error)); - return { success: false, error: String(error) }; - } finally { - setIsLoading(false); - } - }, []); - - // Update configuration for a specific profile - const handleUpdateProfileConfig = useCallback(async (profileName: string, config: ConfigurationData) => { - setIsLoading(true); - try { - const result: ConfigUpdateResult = await updateProfileConfig(profileName, config); - if (result.success) { - return result; - } else { - console.error("Failed to update profile config:", result.error); - showErrorToast("Failed to update profile config", result.error || "Unknown error"); - return result; - } - } catch (error) { - console.error("Error updating profile config:", error); - showErrorToast("Error updating profile config", String(error)); - return { success: false, error: String(error) }; - } finally { - setIsLoading(false); - } - }, [currentProfile]); - - // Initialize profiles on mount - useEffect(() => { - loadProfiles(); - }, [loadProfiles]); - - return { - profiles, - currentProfile, - isLoading, - loadProfiles, - createProfile: handleCreateProfile, - deleteProfile: handleDeleteProfile, - renameProfile: handleRenameProfile, - setCurrentProfile: handleSetCurrentProfile, - updateProfileConfig: handleUpdateProfileConfig - }; -} -- cgit v1.2.3 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 --- 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 ++ 15 files changed, 504 insertions(+), 962 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 (limited to 'src') 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 From 170d183fdafc1ec1a686c006fd6a2431c1f30c71 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sun, 6 Sep 2026 19:06:52 -0400 Subject: refactor: align secondary tabs with Decky UI --- src/components/ConfigFileTab.tsx | 42 ++++++++++++------------ src/components/FlatpaksTab.tsx | 37 +++++++++------------ src/components/InstallationButton.tsx | 43 +++++------------------- src/components/SetupTab.tsx | 1 - src/components/StatusDisplay.tsx | 61 +++++++---------------------------- 5 files changed, 57 insertions(+), 127 deletions(-) (limited to 'src') diff --git a/src/components/ConfigFileTab.tsx b/src/components/ConfigFileTab.tsx index 60c5c7e..e3cc09d 100644 --- a/src/components/ConfigFileTab.tsx +++ b/src/components/ConfigFileTab.tsx @@ -1,19 +1,11 @@ import { useEffect, useState } from "react"; -import { Field, Focusable, PanelSection, PanelSectionRow, Spinner } from "@decky/ui"; +import { Field, 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) }); @@ -23,24 +15,32 @@ export function ConfigFileTab() { if (!result) { return ( - + + + ); } return ( - - - {result.success && result.content && ( - void copy(result.content || "")}> -
-                {result.content}
-              
-
- )} -
-
+ {result.error && ( + + + + )} + {result.success && result.content && ( + <> + + + + +
+              {result.content}
+            
+
+ + )}
); } diff --git a/src/components/FlatpaksTab.tsx b/src/components/FlatpaksTab.tsx index dc73858..b4d5e4d 100644 --- a/src/components/FlatpaksTab.tsx +++ b/src/components/FlatpaksTab.tsx @@ -1,15 +1,12 @@ import { useEffect, useState } from "react"; import { - ButtonItem, ConfirmModal, Field, PanelSection, PanelSectionRow, - Spinner, - Toggle, + ToggleField, showModal, } from "@decky/ui"; -import { FaCheck, FaCog, FaDownload, FaTimes, FaTrash } from "react-icons/fa"; import { checkFlatpakExtensionStatus, FlatpakApp, @@ -40,15 +37,13 @@ interface RuntimeRowProps { function RuntimeRow({ version, installed, busy, onAction }: RuntimeRowProps) { return ( - : } - > - - {busy ? : installed ? <> {t("FLATPAK_UNINSTALL_BTN", "Uninstall")} : <> {t("FLATPAK_INSTALL_BTN", "Install")}} - - + description={busy ? "Updating..." : installed ? t("FLATPAK_INSTALLED", "Installed") : t("FLATPAK_NOT_INSTALLED", "Not installed")} + checked={installed} + onChange={() => onAction()} + disabled={busy} + /> ); } @@ -70,13 +65,13 @@ function AppRow({ app, busy, onToggle }: AppRowProps) { return ( - } - > - - + checked={configured} + onChange={onToggle} + disabled={busy} + /> ); } @@ -162,13 +157,13 @@ export function FlatpaksTab() { }; if (loading) { - return ; + return ; } return ( <> - - {error && } />} + + {error && } {extensionStatus?.success ? runtimeVersions.map(({ version, key }) => (
} - + {apps?.success ? apps.apps.length ? apps.apps.map((app) => ( { - if (isInstalling) { - return ( -
-
{t('INSTALL_INSTALLING', 'Installing...')}
-
- ); - } - - if (isUninstalling) { - return ( -
-
{t('INSTALL_UNINSTALLING', 'Uninstalling...')}
-
- ); - } - - if (isInstalled) { - return ( -
- -
{t('INSTALL_UNINSTALL_BTN', 'Uninstall LSFG-VK')}
-
- ); - } - - return ( -
- -
{t('INSTALL_INSTALL_BTN', 'Install LSFG-VK')}
-
- ); - }; + const label = isInstalling + ? t('INSTALL_INSTALLING', 'Installing...') + : isUninstalling + ? t('INSTALL_UNINSTALLING', 'Uninstalling...') + : isInstalled + ? t('INSTALL_UNINSTALL_BTN', 'Uninstall LSFG-VK') + : t('INSTALL_INSTALL_BTN', 'Install LSFG-VK'); return ( @@ -58,7 +31,7 @@ export function InstallationButton({ onClick={isInstalled ? onUninstall : onInstall} disabled={isInstalling || isUninstalling} > - {renderButtonContent()} + {label} ); diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index 34106ed..98d6e78 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -29,7 +29,6 @@ export function SetupTab({ return ( -
-
- {losslessScalingAppInstalled ? "Lossless Scaling Installed" : "Lossless Scaling Not Installed"} -
- {!losslessScalingAppInstalled && losslessScalingStatus && ( -
- {losslessScalingStatus} -
- )} -
- {installationStatus} -
-
+ +
+ + {steamBranchStatus?.installed && ( -
-
- Steam branch: {steamBranchStatus.current_branch || "public"} - {steamBranchStatus.needs_switch && ( -
- {steamBranchStatus.message} -
- )} -
-
+
)} -- cgit v1.2.3 From 7bc5f685186b1ff03ce0f7c99e7bec411beabaeb Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sun, 6 Sep 2026 22:04:54 -0400 Subject: feat: make ui suck less, frfr --- src/api/lsfgApi.ts | 36 +-------- src/components/ConfigurationSection.tsx | 10 +-- src/components/ConfigurationTab.tsx | 86 +++++++++++++++------ src/components/Content.tsx | 45 +++++++++-- src/components/FgmodClipboardButton.tsx | 110 --------------------------- src/components/FpsMultiplierControl.tsx | 70 ++++------------- src/components/GameConfigurationControls.tsx | 17 +++++ src/components/GameConfigurationSelector.tsx | 67 +++++++++++----- src/components/NowPlayingTab.tsx | 32 ++++++++ src/components/index.ts | 3 +- src/hooks/useGameConfiguration.ts | 61 ++++++++++----- src/hooks/useLsfgHooks.ts | 61 +-------------- src/i18n/languages.json | 15 +--- src/styles.ts | 2 +- src/utils/clipboardUtils.ts | 64 ---------------- src/utils/toastUtils.ts | 22 ------ 16 files changed, 269 insertions(+), 432 deletions(-) delete mode 100644 src/components/FgmodClipboardButton.tsx create mode 100644 src/components/GameConfigurationControls.tsx create mode 100644 src/components/NowPlayingTab.tsx delete mode 100644 src/utils/clipboardUtils.ts (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 04d1309..8eaad98 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -32,12 +32,6 @@ export interface SteamBranchStatus { // Use centralized configuration data type export type LsfgConfig = ConfigurationData; -export interface ConfigResult { - success: boolean; - config?: LsfgConfig; - error?: string; -} - export interface ConfigUpdateResult { success: boolean; message?: string; @@ -51,10 +45,11 @@ export interface GameConfigEntry { } export interface InstalledGame { appid: string; name: string; nonSteam: boolean; } export interface InstalledGamesResult { success: boolean; games?: InstalledGame[]; error?: string; } +export interface GlobalConfig { dll: string; no_fp16: boolean; } export interface GameConfigsResult { success: boolean; - default?: LsfgConfig; + global_config?: GlobalConfig; games?: GameConfigEntry[]; error?: string; } @@ -65,12 +60,6 @@ export interface GameConfigResult extends ConfigUpdateResult { config?: LsfgConfig; } -export interface ConfigSchemaResult { - field_names: string[]; - field_types: Record; - defaults: ConfigurationData; -} - export interface FileContentResult { success: boolean; content?: string; @@ -78,13 +67,6 @@ export interface FileContentResult { error?: string; } -export interface FgmodCheckResult { - success: boolean; - exists: boolean; - path?: string; - error?: string; -} - // Flatpak management interfaces export interface FlatpakExtensionStatus { success: boolean; @@ -123,10 +105,7 @@ export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk") export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); 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 getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); -export const checkFgmodDirectory = callable<[], FgmodCheckResult>("check_fgmod_directory"); // Flatpak management API functions export const checkFlatpakExtensionStatus = callable<[], FlatpakExtensionStatus>("check_flatpak_extension_status"); @@ -136,19 +115,8 @@ export const getFlatpakApps = callable<[], FlatpakAppInfo>("get_flatpak_apps"); export const setFlatpakAppOverride = callable<[string], FlatpakOperationResult>("set_flatpak_app_override"); export const removeFlatpakAppOverride = callable<[string], FlatpakOperationResult>("remove_flatpak_app_override"); -// Updated config function using object-based configuration (single source of truth) -export const updateLsfgConfig = callable< - [ConfigurationData], - ConfigUpdateResult ->("update_lsfg_config"); 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, string, LsfgConfig], GameConfigResult>("update_game_config"); export const resetGameConfig = callable<[string], GameConfigResult>("reset_game_config"); export const resetAllGameConfigs = callable<[], GameConfigsResult>("reset_all_game_configs"); - -// Legacy helper function for backward compatibility -export const updateLsfgConfigFromObject = async (config: ConfigurationData): Promise => { - return updateLsfgConfig(config); -}; diff --git a/src/components/ConfigurationSection.tsx b/src/components/ConfigurationSection.tsx index c2bba7e..1f17264 100644 --- a/src/components/ConfigurationSection.tsx +++ b/src/components/ConfigurationSection.tsx @@ -10,19 +10,19 @@ interface ConfigurationSectionProps { export function ConfigurationSection({ config, onConfigChange }: ConfigurationSectionProps) { return <> - onConfigChange(FLOW_SCALE, value)} /> + onConfigChange(FLOW_SCALE, value)} /> - onConfigChange(NO_FP16, !value)} /> + onConfigChange(NO_FP16, !value)} /> - onConfigChange(PERFORMANCE_MODE, value)} /> + onConfigChange(PERFORMANCE_MODE, value)} /> - onConfigChange(OVERRIDE_PRESENT_MODE, value)} /> + onConfigChange(OVERRIDE_PRESENT_MODE, value)} /> - onConfigChange(PRESERVE_SWAPCHAIN_IMAGE_COUNT, value)} /> + onConfigChange(PRESERVE_SWAPCHAIN_IMAGE_COUNT, value)} /> ; } diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 6f3f474..dab6f19 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,19 +1,17 @@ -import { PanelSection } from "@decky/ui"; +import { ButtonItem, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import { useEffect, useRef, useState } from "react"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; -import { ConfigurationSection } from "./ConfigurationSection"; -import { FgmodClipboardButton } from "./FgmodClipboardButton"; -import { FpsMultiplierControl } from "./FpsMultiplierControl"; +import { GameConfigurationControls } from "./GameConfigurationControls"; 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; + onEnable: (appid: string) => Promise; onReset: () => Promise; onResetAll: () => Promise; } @@ -22,33 +20,77 @@ export function ConfigurationTab({ config, targets, runningGame, - selectedAppId, onSelect, onConfigChange, + onEnable, onReset, onResetAll, }: ConfigurationTabProps) { - return ( - <> - - - - + const [detailAppId, setDetailAppId] = useState(null); + const promptedRunningAppId = useRef(null); + + useEffect(() => { + if (!runningGame || runningGame.configured) { + promptedRunningAppId.current = null; + return; + } + if (promptedRunningAppId.current !== runningGame.appid && detailAppId === null) { + promptedRunningAppId.current = runningGame.appid; + setDetailAppId(runningGame.appid); + } + }, [detailAppId, runningGame?.appid, runningGame?.configured]); + + const selectedTarget = detailAppId ? targets.find((target) => target.appid === detailAppId) : null; + + if (detailAppId === null) { + return ( + { + onSelect(appid); + setDetailAppId(appid); + }} onResetAll={onResetAll} /> - - - - - + ); + } + + const profileLabel = selectedTarget?.name || "Game profile"; + const running = selectedTarget?.appid === runningGame?.appid; + const profileDescription = selectedTarget + ? `${selectedTarget.nonSteam ? "Non-Steam" : "Steam"} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? running && !runningGame?.configured ? "Profile saved · applies next launch" : "Profile active" : "Not configured · changes apply next launch"}` + : "Game is no longer available"; + + return ( + setDetailAppId(null)}> + + + + + + setDetailAppId(null)}>Back to games + - + + + { + if (selectedTarget?.configured) { + promptedRunningAppId.current = detailAppId; + await onReset(); + setDetailAppId(null); + } else if (detailAppId) { + await onEnable(detailAppId); + } + }} + > + {selectedTarget?.configured ? "Remove profile" : "Enable for next launch"} + + + ); } diff --git a/src/components/Content.tsx b/src/components/Content.tsx index de8f996..9281d39 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,6 +1,6 @@ import { Tabs } from "@decky/ui"; -import { useEffect, useState } from "react"; -import { FaFileAlt, FaGamepad, FaLayerGroup, FaTools } from "react-icons/fa"; +import { useEffect, useRef, useState } from "react"; +import { FaFileAlt, FaGamepad, FaLayerGroup, FaList, FaTools } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; import { tabStyles } from "../styles"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; @@ -9,10 +9,12 @@ import { useInstallationStatus } from "../hooks/useLsfgHooks"; import { ConfigFileTab } from "./ConfigFileTab"; import { ConfigurationTab } from "./ConfigurationTab"; import { FlatpaksTab } from "./FlatpaksTab"; +import { NowPlayingTab } from "./NowPlayingTab"; import { SetupTab } from "./SetupTab"; const tabIcons = { - configuration: , + nowPlaying: , + configuration: , flatpak: , configFile: , setup: , @@ -33,9 +35,9 @@ export function Content() { config, targets, runningGame, - selectedAppId, setSelectedAppId, save, + enable, resetSelected, resetAll, reload, @@ -48,10 +50,27 @@ export function Content() { steamBranchStatus?.success === true && steamBranchStatus.installed && !steamBranchStatus.needs_switch; + const previousRunningState = useRef<{ appid: string; configured: boolean } | null>(null); useEffect(() => { - setTab(setupComplete ? "Configuration" : "Setup"); - }, [setupComplete]); + if (!setupComplete) { + setTab("Setup"); + return; + } + setTab((current) => current === "Setup" ? (runningGame?.configured ? "NowPlaying" : "Configuration") : current); + }, [runningGame?.configured, setupComplete]); + + useEffect(() => { + if (!setupComplete) return; + const current = runningGame ? { appid: runningGame.appid, configured: runningGame.configured } : null; + const previous = previousRunningState.current; + previousRunningState.current = current; + if (current?.appid && (current.appid !== previous?.appid || current.configured !== previous?.configured)) { + setTab(current.configured ? "NowPlaying" : "Configuration"); + } else if (!current && previous) { + setTab((currentTab) => currentTab === "NowPlaying" ? "Configuration" : currentTab); + } + }, [runningGame?.appid, runningGame?.configured, setupComplete]); useEffect(() => { if (isInstalled) void reload(); @@ -88,6 +107,18 @@ export function Content() { const tabs = setupComplete ? [ + ...(runningGame?.configured ? [{ + id: "NowPlaying", + title: tabIcons.nowPlaying, + content: ( + + ), + }] : []), { id: "Configuration", title: tabIcons.configuration, @@ -96,9 +127,9 @@ export function Content() { config={config} targets={targets} runningGame={runningGame} - selectedAppId={selectedAppId} onSelect={setSelectedAppId} onConfigChange={handleConfigChange} + onEnable={enable} onReset={resetSelected} onResetAll={resetAll} /> diff --git a/src/components/FgmodClipboardButton.tsx b/src/components/FgmodClipboardButton.tsx deleted file mode 100644 index efc5490..0000000 --- a/src/components/FgmodClipboardButton.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import { useState, useEffect } from "react"; -import { PanelSectionRow, ButtonItem } from "@decky/ui"; -import { FaClipboard, FaCheck } from "react-icons/fa"; -import { checkFgmodDirectory } from "../api/lsfgApi"; -import { showClipboardErrorToast } from "../utils/toastUtils"; -import { copyWithVerification } from "../utils/clipboardUtils"; -import t from '../i18n/i18n'; - -export function FgmodClipboardButton() { - const [isLoading, setIsLoading] = useState(false); - const [showSuccess, setShowSuccess] = useState(false); - const [fgmodExists, setFgmodExists] = useState(false); - const [checkingFgmod, setCheckingFgmod] = useState(true); - - // Check for fgmod directory on component mount - useEffect(() => { - const checkFgmod = async () => { - try { - const result = await checkFgmodDirectory(); - setFgmodExists(result.exists); - } catch (error) { - console.error("Error checking fgmod directory:", error); - setFgmodExists(false); - } finally { - setCheckingFgmod(false); - } - }; - - checkFgmod(); - }, []); - - // Reset success state after 3 seconds - useEffect(() => { - if (showSuccess) { - const timer = setTimeout(() => { - setShowSuccess(false); - }, 3000); - return () => clearTimeout(timer); - } - return undefined; - }, [showSuccess]); - - const copyToClipboard = async () => { - if (isLoading || showSuccess) return; - - setIsLoading(true); - try { - const text = "~/fgmod/fgmod ~/lsfg %command%"; - const { success, verified } = await copyWithVerification(text); - - if (success) { - // Show success feedback in the button instead of toast - setShowSuccess(true); - if (!verified) { - // Copy worked but verification failed - still show success - console.log('Copy verification failed but copy likely worked'); - } - } else { - showClipboardErrorToast(); - } - } catch (error) { - showClipboardErrorToast(); - } finally { - setIsLoading(false); - } - }; - - // Don't render if fgmod directory doesn't exist or we're still checking - if (checkingFgmod || !fgmodExists) { - return null; - } - - return ( - - -
- {showSuccess ? ( - - ) : isLoading ? ( - - ) : ( - - )} -
- {showSuccess ? t('CLIPBOARD_COPIED', 'Copied to clipboard') : isLoading ? t('CLIPBOARD_COPYING', 'Copying...') : t('CLIPBOARD_LSFG_FGMOD', 'LSFG + DeckyFG')} -
-
-
- -
- ); -} diff --git a/src/components/FpsMultiplierControl.tsx b/src/components/FpsMultiplierControl.tsx index 5069c9a..e197dc3 100644 --- a/src/components/FpsMultiplierControl.tsx +++ b/src/components/FpsMultiplierControl.tsx @@ -1,4 +1,4 @@ -import { PanelSectionRow, DialogButton, Focusable } from "@decky/ui"; +import { PanelSectionRow, SliderField } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; import { MULTIPLIER } from "../config/generatedConfigSchema"; import t from "../i18n/i18n"; @@ -12,62 +12,22 @@ export function FpsMultiplierControl({ config, onConfigChange }: FpsMultiplierControlProps) { + const multiplierLabel = config.multiplier === 1 + ? t("MULTIPLIER_OFF", "Off") + : `${config.multiplier}x`; + return ( - - onConfigChange(MULTIPLIER, Math.max(1, config.multiplier - 1))} - disabled={config.multiplier <= 1} - > - − - -
4 ? "red" : "white", - minWidth: "60px", - textAlign: "center" - }} - > - {config.multiplier === 1 ? t('MULTIPLIER_OFF', 'OFF') : `${config.multiplier}X`} -
- onConfigChange(MULTIPLIER, Math.min(4, config.multiplier + 1))} - disabled={config.multiplier >= 4} - > - + - -
+ void onConfigChange(MULTIPLIER, value)} + />
); } diff --git a/src/components/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx new file mode 100644 index 0000000..bdf9985 --- /dev/null +++ b/src/components/GameConfigurationControls.tsx @@ -0,0 +1,17 @@ +import { ConfigurationData } from "../config/configSchema"; +import { ConfigurationSection } from "./ConfigurationSection"; +import { FpsMultiplierControl } from "./FpsMultiplierControl"; + +interface Props { + config: ConfigurationData; + onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; +} + +export function GameConfigurationControls({ config, onConfigChange }: Props) { + return ( + <> + + + + ); +} diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index a231477..fcdd0aa 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -1,29 +1,58 @@ -import { Dropdown, DropdownOption, PanelSectionRow, ButtonItem } from "@decky/ui"; +import { ButtonItem, Field, PanelSectionRow } from "@decky/ui"; import { GameTarget } from "../hooks/useGameConfiguration"; interface Props { targets: GameTarget[]; runningGame: GameTarget | null; - selectedAppId: string; onSelect: (appid: string) => void; - onReset: () => Promise; onResetAll: () => Promise; } -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.nonSteam ? "Non-Steam · " : ""}${target.name} · ${target.appid}` })), - ]; - return <> - - onSelect(String(option.data))} /> - - - void onReset()} disabled={!selectedAppId}>Reset selected game - - - void onResetAll()} disabled={!targets.some((target) => target.configured)}>Reset all game profiles - - ; +const profileDescription = (target: GameTarget, running: boolean, active: boolean) => [ + running ? "Now playing" : "", + target.nonSteam ? "Non-Steam" : "Steam", + target.configured + ? active ? "Profile active" : "Profile saved · applies next launch" + : "Not configured · changes apply next launch", +].filter(Boolean).join(" · "); + +export function GameConfigurationSelector({ targets, runningGame, onSelect, onResetAll }: Props) { + const games = [...targets].sort((a, b) => { + if (a.appid === runningGame?.appid) return -1; + if (b.appid === runningGame?.appid) return 1; + return a.name.localeCompare(b.name); + }); + + return ( + <> + {games.length === 0 && ( + + + + )} + {games.map((game) => ( + + onSelect(game.appid)} + highlightOnFocus + /> + + ))} + + void onResetAll()} + disabled={!targets.some((target) => target.configured)} + > + Remove all profiles + + + + ); } diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx new file mode 100644 index 0000000..956db4a --- /dev/null +++ b/src/components/NowPlayingTab.tsx @@ -0,0 +1,32 @@ +import { ButtonItem, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import { ConfigurationData } from "../config/configSchema"; +import { GameTarget } from "../hooks/useGameConfiguration"; +import { GameConfigurationControls } from "./GameConfigurationControls"; + +interface Props { + game: GameTarget; + config: ConfigurationData; + onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; + onRemove: () => Promise; +} + +export function NowPlayingTab({ game, config, onConfigChange, onRemove }: Props) { + return ( + + + + + + + + + void onRemove()}> + Remove profile + + + + ); +} diff --git a/src/components/index.ts b/src/components/index.ts index 5089b6f..424a360 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -3,9 +3,10 @@ export { StatusDisplay } from "./StatusDisplay"; export { InstallationButton } from "./InstallationButton"; export { ConfigurationSection } from "./ConfigurationSection"; export { FpsMultiplierControl } from "./FpsMultiplierControl"; -export { FgmodClipboardButton } from "./FgmodClipboardButton"; export { ConfigurationTab } from "./ConfigurationTab"; export { SetupTab } from "./SetupTab"; export { ConfigFileTab } from "./ConfigFileTab"; export { FlatpaksTab } from "./FlatpaksTab"; export { GameConfigurationSelector } from "./GameConfigurationSelector"; +export { GameConfigurationControls } from "./GameConfigurationControls"; +export { NowPlayingTab } from "./NowPlayingTab"; diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index b177551..d279a8c 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,37 +1,40 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Router } from "@decky/ui"; -import { getGameConfigs, getInstalledGames, updateGameConfig, updateLsfgConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type InstalledGame } from "../api/lsfgApi"; +import { getGameConfigs, getInstalledGames, updateGameConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type GlobalConfig, type InstalledGame } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; export interface GameTarget extends InstalledGame { configured: boolean; } export function useGameConfiguration() { - const [defaultConfig, setDefaultConfig] = useState(getDefaults()); const [games, setGames] = useState([]); + const [globalConfig, setGlobalConfig] = useState({ dll: "", no_fp16: false }); const [installedGames, setInstalledGames] = useState([]); + const [configsLoaded, setConfigsLoaded] = useState(false); const [selectedAppId, setSelectedAppId] = useState(""); const [runningGame, setRunningGame] = useState(null); - const autoSelected = useRef(false); + const previousRunningAppId = useRef(null); const load = useCallback(async () => { const [result, installed] = await Promise.all([getGameConfigs(), getInstalledGames()]); if (result.success) { - setDefaultConfig(result.default || getDefaults()); + setGlobalConfig(result.global_config || { dll: "", no_fp16: false }); setGames(result.games || []); } if (installed.success) setInstalledGames(installed.games || []); + setConfigsLoaded(true); }, []); useEffect(() => { load(); }, [load]); useEffect(() => { const poll = () => { + if (!configsLoaded) return; const app = Router.MainRunningApp as any; 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({ + setRunningGame((current) => current?.appid === appid ? current : { ...(installed || { appid, name, nonSteam: false }), name, configured: games.some((game) => game.appid === appid), @@ -40,13 +43,14 @@ export function useGameConfiguration() { poll(); const interval = window.setInterval(poll, 2000); return () => window.clearInterval(interval); - }, [games, installedGames]); + }, [configsLoaded, games, installedGames]); useEffect(() => { - if (!autoSelected.current && runningGame) { - autoSelected.current = true; - setSelectedAppId(runningGame.appid); + const appid = runningGame?.appid || null; + if (appid !== previousRunningAppId.current) { + previousRunningAppId.current = appid; + setSelectedAppId(appid || ""); } - }, [runningGame]); + }, [runningGame?.appid]); const targets = useMemo(() => { const configured = installedGames.map((game) => ({ ...game, configured: games.some((item) => item.appid === game.appid) })); @@ -54,25 +58,42 @@ export function useGameConfiguration() { if (runningGame && !configured.some((game) => game.appid === runningGame.appid)) configured.unshift(runningGame); return configured; }, [games, installedGames, runningGame]); - const selected = selectedAppId ? games.find((game) => game.appid === selectedAppId)?.config : defaultConfig; - const config = selected || defaultConfig; + const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); + const config = games.find((game) => game.appid === selectedAppId)?.config || template; const save = useCallback(async (next: ConfigurationData) => { - if (!selectedAppId) { - const result = await updateLsfgConfig(next); - if (result.success) setDefaultConfig(next); - return; - } 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, targets]); + const enable = useCallback(async (appid: string) => { + const target = targets.find((item) => item.appid === appid); + if (!target?.name) return false; + const result = await updateGameConfig(appid, target.name, template); + if (result.success) await load(); + return result.success; + }, [load, targets, template]); + const resetSelected = useCallback(async () => { - if (selectedAppId) { await resetGameConfig(selectedAppId); setSelectedAppId(""); await load(); } + if (selectedAppId) { + const result = await resetGameConfig(selectedAppId); + if (result.success) { + setRunningGame((current) => current?.appid === selectedAppId ? { ...current, configured: false } : current); + setSelectedAppId(""); + await load(); + } + } }, [load, selectedAppId]); - const resetAll = useCallback(async () => { await resetAllGameConfigs(); setSelectedAppId(""); await load(); }, [load]); + const resetAll = useCallback(async () => { + const result = await resetAllGameConfigs(); + if (result.success) { + setRunningGame((current) => current ? { ...current, configured: false } : current); + setSelectedAppId(""); + await load(); + } + }, [load]); - return { config, defaultConfig, games, targets, runningGame, selectedAppId, setSelectedAppId, save, resetSelected, resetAll, reload: load }; + return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, resetSelected, resetAll, reload: load }; } diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index ea8b3d0..0b71ee9 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -1,14 +1,9 @@ -import { useState, useEffect, useCallback } from "react"; +import { useState, useEffect } from "react"; import { checkLsfgVkInstalled, - getLsfgConfig, getLosslessScalingBranchStatus, - updateLsfgConfigFromObject, - type ConfigUpdateResult, type SteamBranchStatus } from "../api/lsfgApi"; -import { ConfigurationData, getDefaults } from "../config/configSchema"; -import { showErrorToast, ToastMessages } from "../utils/toastUtils"; export function useInstallationStatus() { const [isInstalled, setIsInstalled] = useState(false); @@ -60,57 +55,3 @@ export function useInstallationStatus() { checkInstallation }; } - -export function useLsfgConfig() { - const [config, setConfig] = useState(() => getDefaults()); - - const loadLsfgConfig = useCallback(async () => { - try { - const result = await getLsfgConfig(); - if (result.success && result.config) { - setConfig(result.config); - } else { - console.log("lsfg config not available, using defaults:", result.error); - setConfig(getDefaults()); - } - } catch (error) { - console.error("Error loading lsfg config:", error); - setConfig(getDefaults()); - } - }, []); - - const updateConfig = useCallback(async (newConfig: ConfigurationData): Promise => { - try { - const result = await updateLsfgConfigFromObject(newConfig); - if (result.success) { - setConfig(newConfig); - } else { - showErrorToast( - ToastMessages.CONFIG_UPDATE_ERROR.title, - result.error || ToastMessages.CONFIG_UPDATE_ERROR.body - ); - } - return result; - } catch (error) { - showErrorToast(ToastMessages.CONFIG_UPDATE_ERROR.title, String(error)); - return { success: false, error: String(error) }; - } - }, []); - - const updateField = useCallback(async (fieldName: keyof ConfigurationData, value: boolean | number | string): Promise => { - const newConfig = { ...config, [fieldName]: value }; - return updateConfig(newConfig); - }, [config, updateConfig]); - - useEffect(() => { - loadLsfgConfig(); - }, []); - - return { - config, - setConfig, - loadLsfgConfig, - updateConfig, - updateField - }; -} diff --git a/src/i18n/languages.json b/src/i18n/languages.json index 0528341..3132083 100644 --- a/src/i18n/languages.json +++ b/src/i18n/languages.json @@ -88,10 +88,7 @@ "PROFILE_DELETE_DESC_SUFFIX": "この操作は取り消せません。", "PROFILE_DELETE_BTN": "削除", "PROFILE_CANNOT_RENAME_TITLE": "デフォルトプロファイルの名前は変更できません", - "PROFILE_CANNOT_RENAME_MSG": "デフォルトプロファイルの名前は変更できません", - "CLIPBOARD_COPIED": "クリップボードにコピーしました", - "CLIPBOARD_COPYING": "コピー中...", - "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" + "PROFILE_CANNOT_RENAME_MSG": "デフォルトプロファイルの名前は変更できません" }, "ko": { "CONTENT_FPS_MULTIPLIER": "FPS 배율", @@ -182,10 +179,7 @@ "PROFILE_DELETE_DESC_SUFFIX": "이 작업은 취소할 수 없습니다.", "PROFILE_DELETE_BTN": "삭제", "PROFILE_CANNOT_RENAME_TITLE": "기본 프로필 이름 변경 불가", - "PROFILE_CANNOT_RENAME_MSG": "기본 프로필의 이름은 변경할 수 없습니다", - "CLIPBOARD_COPIED": "클립보드에 복사됨", - "CLIPBOARD_COPYING": "복사 중...", - "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" + "PROFILE_CANNOT_RENAME_MSG": "기본 프로필의 이름은 변경할 수 없습니다" }, "language_metadata": { "ko": { @@ -304,9 +298,6 @@ "PROFILE_DELETE_DESC_SUFFIX": "? This action cannot be undone.", "PROFILE_DELETE_BTN": "Delete", "PROFILE_CANNOT_RENAME_TITLE": "Cannot rename default profile", - "PROFILE_CANNOT_RENAME_MSG": "The default profile cannot be renamed", - "CLIPBOARD_COPIED": "Copied to clipboard", - "CLIPBOARD_COPYING": "Copying...", - "CLIPBOARD_LSFG_FGMOD": "LSFG + DeckyFG" + "PROFILE_CANNOT_RENAME_MSG": "The default profile cannot be renamed" } } diff --git a/src/styles.ts b/src/styles.ts index fe40a59..1bc089b 100644 --- a/src/styles.ts +++ b/src/styles.ts @@ -1,5 +1,5 @@ export const tabStyles = ` - .lsfg-vk-tabs > div > div:first-child::before { + .lsfg-vk-tabs > div > div:first-child { background: #0D141C; box-shadow: none; backdrop-filter: none; diff --git a/src/utils/clipboardUtils.ts b/src/utils/clipboardUtils.ts deleted file mode 100644 index 8a04caa..0000000 --- a/src/utils/clipboardUtils.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Clipboard utilities for reliable copy operations across different environments - */ - -/** - * Reliably copy text to clipboard using multiple fallback methods - * This is especially important in gaming mode where clipboard APIs may behave differently - */ -export async function copyToClipboard(text: string): Promise { - const tempInput = document.createElement('input'); - tempInput.value = text; - tempInput.style.position = 'absolute'; - tempInput.style.left = '-9999px'; - document.body.appendChild(tempInput); - - try { - tempInput.focus(); - tempInput.select(); - - let copySuccess = false; - try { - if (document.execCommand('copy')) { - copySuccess = true; - } - } catch (e) { - try { - await navigator.clipboard.writeText(text); - copySuccess = true; - } catch (clipboardError) { - console.error('Both copy methods failed:', e, clipboardError); - } - } - - return copySuccess; - } finally { - document.body.removeChild(tempInput); - } -} - -/** - * Verify that text was successfully copied to clipboard - */ -export async function verifyCopy(expectedText: string): Promise { - try { - const readBack = await navigator.clipboard.readText(); - return readBack === expectedText; - } catch (e) { - return true; - } -} - -/** - * Copy text with verification and return success status - */ -export async function copyWithVerification(text: string): Promise<{ success: boolean; verified: boolean }> { - const copySuccess = await copyToClipboard(text); - - if (!copySuccess) { - return { success: false, verified: false }; - } - - const verified = await verifyCopy(text); - return { success: true, verified }; -} diff --git a/src/utils/toastUtils.ts b/src/utils/toastUtils.ts index dce0a59..cbbbc55 100644 --- a/src/utils/toastUtils.ts +++ b/src/utils/toastUtils.ts @@ -53,14 +53,6 @@ export const ToastMessages = { CONFIG_UPDATE_ERROR: { title: "Update Failed", body: "Failed to update configuration" - }, - CLIPBOARD_SUCCESS: { - title: "Copied to Clipboard!", - body: "Launch option ready to paste" - }, - CLIPBOARD_ERROR: { - title: "Copy Failed", - body: "Unable to copy to clipboard" } } as const; @@ -99,17 +91,3 @@ export function showUninstallSuccessToast(): void { export function showUninstallErrorToast(error?: string): void { showErrorToast(ToastMessages.UNINSTALL_ERROR.title, error || ToastMessages.UNINSTALL_ERROR.body); } - -/** - * Show clipboard success toast - */ -export function showClipboardSuccessToast(): void { - showSuccessToast(ToastMessages.CLIPBOARD_SUCCESS.title, ToastMessages.CLIPBOARD_SUCCESS.body); -} - -/** - * Show clipboard error toast - */ -export function showClipboardErrorToast(): void { - showErrorToast(ToastMessages.CLIPBOARD_ERROR.title, ToastMessages.CLIPBOARD_ERROR.body); -} -- cgit v1.2.3 From d1f8263bf9f22753ad53e1b0105172a3bd0faf5f Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Sun, 6 Sep 2026 23:12:28 -0400 Subject: feat: organize game profiles and focus enabled settings --- src/components/ConfigurationTab.tsx | 28 +++++-- src/components/FpsMultiplierControl.tsx | 45 ++++++++--- src/components/GameConfigurationControls.tsx | 16 +++- src/components/GameConfigurationSelector.tsx | 107 +++++++++++++++++++++------ src/components/NowPlayingTab.tsx | 2 +- 5 files changed, 152 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index dab6f19..6c4a99a 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,5 +1,5 @@ import { ButtonItem, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; import { GameConfigurationControls } from "./GameConfigurationControls"; @@ -27,7 +27,13 @@ export function ConfigurationTab({ onResetAll, }: ConfigurationTabProps) { const [detailAppId, setDetailAppId] = useState(null); + const [focusFpsMultiplier, setFocusFpsMultiplier] = useState(false); const promptedRunningAppId = useRef(null); + const closeDetails = useCallback(() => { + setFocusFpsMultiplier(false); + setDetailAppId(null); + }, []); + const clearFpsFocusRequest = useCallback(() => setFocusFpsMultiplier(false), []); useEffect(() => { if (!runningGame || runningGame.configured) { @@ -59,22 +65,28 @@ export function ConfigurationTab({ } const profileLabel = selectedTarget?.name || "Game profile"; - const running = selectedTarget?.appid === runningGame?.appid; const profileDescription = selectedTarget - ? `${selectedTarget.nonSteam ? "Non-Steam" : "Steam"} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? running && !runningGame?.configured ? "Profile saved · applies next launch" : "Profile active" : "Not configured · changes apply next launch"}` + ? `${selectedTarget.nonSteam ? "Non-Steam" : "Steam"} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "Configured" : "Not configured"}` : "Game is no longer available"; return ( - setDetailAppId(null)}> + - setDetailAppId(null)}>Back to games + Back to games - + {selectedTarget?.configured && ( + + )} diff --git a/src/components/FpsMultiplierControl.tsx b/src/components/FpsMultiplierControl.tsx index e197dc3..1fd0e78 100644 --- a/src/components/FpsMultiplierControl.tsx +++ b/src/components/FpsMultiplierControl.tsx @@ -1,4 +1,5 @@ -import { PanelSectionRow, SliderField } from "@decky/ui"; +import { Focusable, PanelSectionRow, SliderField } from "@decky/ui"; +import { useEffect, useRef } from "react"; import { ConfigurationData } from "../config/configSchema"; import { MULTIPLIER } from "../config/generatedConfigSchema"; import t from "../i18n/i18n"; @@ -6,28 +7,48 @@ import t from "../i18n/i18n"; interface FpsMultiplierControlProps { config: ConfigurationData; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; + autoFocus?: boolean; + onAutoFocus?: () => void; } export function FpsMultiplierControl({ config, - onConfigChange + onConfigChange, + autoFocus = false, + onAutoFocus, }: FpsMultiplierControlProps) { + const focusableRef = useRef(null); + + useEffect(() => { + if (!autoFocus) return; + const frame = requestAnimationFrame(() => { + const target = focusableRef.current?.querySelector( + '[role="button"], [role="slider"]', + ); + target?.focus(); + onAutoFocus?.(); + }); + return () => cancelAnimationFrame(frame); + }, [autoFocus, onAutoFocus]); + const multiplierLabel = config.multiplier === 1 ? t("MULTIPLIER_OFF", "Off") : `${config.multiplier}x`; return ( - void onConfigChange(MULTIPLIER, value)} - /> + + void onConfigChange(MULTIPLIER, value)} + /> + ); } diff --git a/src/components/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx index bdf9985..34b82c5 100644 --- a/src/components/GameConfigurationControls.tsx +++ b/src/components/GameConfigurationControls.tsx @@ -5,12 +5,24 @@ import { FpsMultiplierControl } from "./FpsMultiplierControl"; interface Props { config: ConfigurationData; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; + autoFocusFpsMultiplier?: boolean; + onFpsMultiplierFocused?: () => void; } -export function GameConfigurationControls({ config, onConfigChange }: Props) { +export function GameConfigurationControls({ + config, + onConfigChange, + autoFocusFpsMultiplier, + onFpsMultiplierFocused, +}: Props) { return ( <> - + ); diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index fcdd0aa..982fcef 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -1,4 +1,6 @@ import { ButtonItem, Field, PanelSectionRow } from "@decky/ui"; +import { useEffect, useState } from "react"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { GameTarget } from "../hooks/useGameConfiguration"; interface Props { @@ -8,42 +10,101 @@ interface Props { onResetAll: () => Promise; } -const profileDescription = (target: GameTarget, running: boolean, active: boolean) => [ - running ? "Now playing" : "", - target.nonSteam ? "Non-Steam" : "Steam", - target.configured - ? active ? "Profile active" : "Profile saved · applies next launch" - : "Not configured · changes apply next launch", -].filter(Boolean).join(" · "); +const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed"; +const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed"; -export function GameConfigurationSelector({ targets, runningGame, onSelect, onResetAll }: Props) { - const games = [...targets].sort((a, b) => { - if (a.appid === runningGame?.appid) return -1; - if (b.appid === runningGame?.appid) return 1; - return a.name.localeCompare(b.name); +function usePersistentCollapsed(key: string) { + const [collapsed, setCollapsed] = useState(() => { + try { + return localStorage.getItem(key) === "true"; + } catch { + return false; + } }); + useEffect(() => { + try { + localStorage.setItem(key, String(collapsed)); + } catch { + // Persisting the view preference is optional. + } + }, [collapsed, key]); + + return [collapsed, () => setCollapsed((value) => !value)] as const; +} + +function GameGroup({ + title, + games, + collapsed, + onToggle, + onSelect, +}: { + title: string; + games: GameTarget[]; + collapsed: boolean; + onToggle: () => void; + onSelect: (appid: string) => void; +}) { + if (games.length === 0) return null; + return ( <> - {games.length === 0 && ( - - - - )} - {games.map((game) => ( + + + {collapsed ? : } {title} ({games.length}) + + + {!collapsed && games.map((game) => ( onSelect(game.appid)} highlightOnFocus /> ))} + + ); +} + +export function GameConfigurationSelector({ targets, runningGame, onSelect, onResetAll }: Props) { + const sortGames = (games: GameTarget[]) => [...games].sort((a, b) => { + if (a.appid === runningGame?.appid) return -1; + if (b.appid === runningGame?.appid) return 1; + return a.name.localeCompare(b.name); + }); + const configuredGames = sortGames(targets.filter((game) => game.configured)); + const availableGames = sortGames(targets.filter((game) => !game.configured)); + const [configuredCollapsed, toggleConfigured] = usePersistentCollapsed(CONFIGURED_COLLAPSED_KEY); + const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); + + return ( + <> + {targets.length === 0 && ( + + + + )} + +
-- cgit v1.2.3 From 50810a08e5a767ec6d774996ce13244121b9f3c3 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 00:39:16 -0400 Subject: fix: improve profile management focus and reset confirmation --- src/components/ConfigurationTab.tsx | 17 ++++++++++++++++- src/components/GameConfigurationSelector.tsx | 15 +++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 6c4a99a..0d8553c 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -28,13 +28,25 @@ export function ConfigurationTab({ }: ConfigurationTabProps) { const [detailAppId, setDetailAppId] = useState(null); const [focusFpsMultiplier, setFocusFpsMultiplier] = useState(false); + const [focusBackToGames, setFocusBackToGames] = useState(false); + const backToGamesRef = useRef(null); const promptedRunningAppId = useRef(null); const closeDetails = useCallback(() => { setFocusFpsMultiplier(false); + setFocusBackToGames(false); setDetailAppId(null); }, []); const clearFpsFocusRequest = useCallback(() => setFocusFpsMultiplier(false), []); + useEffect(() => { + if (!focusBackToGames) return; + const frame = requestAnimationFrame(() => { + backToGamesRef.current?.querySelector('[role="button"]')?.focus(); + setFocusBackToGames(false); + }); + return () => cancelAnimationFrame(frame); + }, [focusBackToGames]); + useEffect(() => { if (!runningGame || runningGame.configured) { promptedRunningAppId.current = null; @@ -55,6 +67,7 @@ export function ConfigurationTab({ targets={targets} runningGame={runningGame} onSelect={(appid) => { + setFocusBackToGames(true); onSelect(appid); setDetailAppId(appid); }} @@ -76,7 +89,9 @@ export function ConfigurationTab({
- Back to games + + Back to games + {selectedTarget?.configured && ( diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 982fcef..91fdc39 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -1,4 +1,4 @@ -import { ButtonItem, Field, PanelSectionRow } from "@decky/ui"; +import { ButtonItem, ConfirmModal, Field, PanelSectionRow, showModal } from "@decky/ui"; import { useEffect, useState } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { GameTarget } from "../hooks/useGameConfiguration"; @@ -83,6 +83,17 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onRe const availableGames = sortGames(targets.filter((game) => !game.configured)); const [configuredCollapsed, toggleConfigured] = usePersistentCollapsed(CONFIGURED_COLLAPSED_KEY); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); + const confirmResetAll = () => { + showModal( + void onResetAll()} + onCancel={() => {}} + />, + ); + }; return ( <> @@ -108,7 +119,7 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onRe void onResetAll()} + onClick={confirmResetAll} disabled={!targets.some((target) => target.configured)} > Remove all profiles -- cgit v1.2.3 From 62531dd08e5f12f1f0533ccf8fa6b84c81eb63d4 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 00:50:43 -0400 Subject: chore: hide config file tab and clarify flatpak runtimes --- src/components/Content.tsx | 5 +++-- src/components/FlatpaksTab.tsx | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 9281d39..1bc6e95 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -6,7 +6,7 @@ import { tabStyles } from "../styles"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallationActions } from "../hooks/useInstallationActions"; import { useInstallationStatus } from "../hooks/useLsfgHooks"; -import { ConfigFileTab } from "./ConfigFileTab"; +// import { ConfigFileTab } from "./ConfigFileTab"; import { ConfigurationTab } from "./ConfigurationTab"; import { FlatpaksTab } from "./FlatpaksTab"; import { NowPlayingTab } from "./NowPlayingTab"; @@ -136,7 +136,8 @@ export function Content() { ), }, { id: "Flatpak", title: tabIcons.flatpak, content: }, - { id: "ConfigFile", title: tabIcons.configFile, content: }, + // Keep the configuration-file view available for future use without exposing it in the UI. + // { id: "ConfigFile", title: tabIcons.configFile, content: }, { id: "Setup", title: tabIcons.setup, content: setupContent }, ] : [ diff --git a/src/components/FlatpaksTab.tsx b/src/components/FlatpaksTab.tsx index b4d5e4d..27204f4 100644 --- a/src/components/FlatpaksTab.tsx +++ b/src/components/FlatpaksTab.tsx @@ -157,12 +157,12 @@ export function FlatpaksTab() { }; if (loading) { - return ; + return ; } return ( <> - + {error && } {extensionStatus?.success ? runtimeVersions.map(({ version, key }) => ( Date: Mon, 7 Sep 2026 09:30:54 -0400 Subject: feat: restore multiplier buttons --- src/components/FpsMultiplierControl.tsx | 72 +++++++++++++++++++++++++-------- 1 file changed, 56 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/components/FpsMultiplierControl.tsx b/src/components/FpsMultiplierControl.tsx index 1fd0e78..2c50be1 100644 --- a/src/components/FpsMultiplierControl.tsx +++ b/src/components/FpsMultiplierControl.tsx @@ -1,4 +1,4 @@ -import { Focusable, PanelSectionRow, SliderField } from "@decky/ui"; +import { DialogButton, Focusable, PanelSectionRow } from "@decky/ui"; import { useEffect, useRef } from "react"; import { ConfigurationData } from "../config/configSchema"; import { MULTIPLIER } from "../config/generatedConfigSchema"; @@ -31,23 +31,63 @@ export function FpsMultiplierControl({ return () => cancelAnimationFrame(frame); }, [autoFocus, onAutoFocus]); - const multiplierLabel = config.multiplier === 1 - ? t("MULTIPLIER_OFF", "Off") - : `${config.multiplier}x`; - return ( - - void onConfigChange(MULTIPLIER, value)} - /> + + void onConfigChange(MULTIPLIER, Math.max(1, config.multiplier - 1))} + disabled={config.multiplier <= 1} + > + − + +
4 ? "red" : "white", + minWidth: "60px", + textAlign: "center", + }} + > + {config.multiplier < 2 ? t("MULTIPLIER_OFF", "OFF") : `${config.multiplier}X`} +
+ void onConfigChange(MULTIPLIER, Math.min(4, config.multiplier + 1))} + disabled={config.multiplier >= 4} + > + + +
); -- cgit v1.2.3 From 22db1125238e54b29538102727c36284e122e703 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 16:02:26 -0400 Subject: feat: refine game discovery and profile UX --- src/components/ConfigurationTab.tsx | 59 +++++++++++++++++----------- src/components/Content.tsx | 8 ++-- src/components/GameConfigurationSelector.tsx | 50 ++++++++++++++++++++--- src/components/NowPlayingTab.tsx | 14 ++----- src/config/generatedConfigSchema.ts | 4 +- src/hooks/useGameConfiguration.ts | 53 +++++++++++++++++++++++-- 6 files changed, 139 insertions(+), 49 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 0d8553c..83f46c1 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -12,6 +12,7 @@ interface ConfigurationTabProps { onSelect: (appid: string) => void; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; onEnable: (appid: string) => Promise; + onEnableAll: () => Promise; onReset: () => Promise; onResetAll: () => Promise; } @@ -23,29 +24,32 @@ export function ConfigurationTab({ onSelect, onConfigChange, onEnable, + onEnableAll, onReset, onResetAll, }: ConfigurationTabProps) { const [detailAppId, setDetailAppId] = useState(null); const [focusFpsMultiplier, setFocusFpsMultiplier] = useState(false); - const [focusBackToGames, setFocusBackToGames] = useState(false); + const [focusDetailAction, setFocusDetailAction] = useState<"enable" | "back" | null>(null); const backToGamesRef = useRef(null); + const enableRef = useRef(null); const promptedRunningAppId = useRef(null); const closeDetails = useCallback(() => { setFocusFpsMultiplier(false); - setFocusBackToGames(false); + setFocusDetailAction(null); setDetailAppId(null); }, []); const clearFpsFocusRequest = useCallback(() => setFocusFpsMultiplier(false), []); useEffect(() => { - if (!focusBackToGames) return; + if (!focusDetailAction) return; const frame = requestAnimationFrame(() => { - backToGamesRef.current?.querySelector('[role="button"]')?.focus(); - setFocusBackToGames(false); + const ref = focusDetailAction === "enable" ? enableRef : backToGamesRef; + ref.current?.querySelector('[role="button"]')?.focus(); + setFocusDetailAction(null); }); return () => cancelAnimationFrame(frame); - }, [focusBackToGames]); + }, [focusDetailAction]); useEffect(() => { if (!runningGame || runningGame.configured) { @@ -54,6 +58,7 @@ export function ConfigurationTab({ } if (promptedRunningAppId.current !== runningGame.appid && detailAppId === null) { promptedRunningAppId.current = runningGame.appid; + setFocusDetailAction(runningGame.configured ? "back" : "enable"); setDetailAppId(runningGame.appid); } }, [detailAppId, runningGame?.appid, runningGame?.configured]); @@ -67,10 +72,11 @@ export function ConfigurationTab({ targets={targets} runningGame={runningGame} onSelect={(appid) => { - setFocusBackToGames(true); + setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "back" : "enable"); onSelect(appid); setDetailAppId(appid); }} + onEnableAll={onEnableAll} onResetAll={onResetAll} />
@@ -79,8 +85,17 @@ export function ConfigurationTab({ const profileLabel = selectedTarget?.name || "Game profile"; const profileDescription = selectedTarget - ? `${selectedTarget.nonSteam ? "Non-Steam" : "Steam"} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "Configured" : "Not configured"}` + ? `${selectedTarget.nonSteam ? "Non-Steam" : "Steam"} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}` : "Game is no longer available"; + const handleProfileAction = async () => { + if (selectedTarget?.configured) { + promptedRunningAppId.current = detailAppId; + await onReset(); + closeDetails(); + } else if (detailAppId && await onEnable(detailAppId)) { + setFocusFpsMultiplier(true); + } + }; return ( @@ -88,6 +103,13 @@ export function ConfigurationTab({ + {!selectedTarget?.configured && selectedTarget && ( + + + Enable for next launch + + + )} Back to games @@ -102,22 +124,11 @@ export function ConfigurationTab({ onFpsMultiplierFocused={clearFpsFocusRequest} /> )} - - { - if (selectedTarget?.configured) { - promptedRunningAppId.current = detailAppId; - await onReset(); - closeDetails(); - } else if (detailAppId) { - if (await onEnable(detailAppId)) setFocusFpsMultiplier(true); - } - }} - > - {selectedTarget?.configured ? "Remove profile" : "Enable for next launch"} - - + {selectedTarget?.configured && ( + + Remove profile + + )} ); } diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 1bc6e95..f1c8c11 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -6,7 +6,7 @@ import { tabStyles } from "../styles"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallationActions } from "../hooks/useInstallationActions"; import { useInstallationStatus } from "../hooks/useLsfgHooks"; -// import { ConfigFileTab } from "./ConfigFileTab"; +import { ConfigFileTab } from "./ConfigFileTab"; import { ConfigurationTab } from "./ConfigurationTab"; import { FlatpaksTab } from "./FlatpaksTab"; import { NowPlayingTab } from "./NowPlayingTab"; @@ -38,6 +38,7 @@ export function Content() { setSelectedAppId, save, enable, + enableAll, resetSelected, resetAll, reload, @@ -115,7 +116,6 @@ export function Content() { game={runningGame} config={config} onConfigChange={handleConfigChange} - onRemove={resetSelected} /> ), }] : []), @@ -130,14 +130,14 @@ export function Content() { onSelect={setSelectedAppId} onConfigChange={handleConfigChange} onEnable={enable} + onEnableAll={enableAll} onReset={resetSelected} onResetAll={resetAll} /> ), }, { id: "Flatpak", title: tabIcons.flatpak, content: }, - // Keep the configuration-file view available for future use without exposing it in the UI. - // { id: "ConfigFile", title: tabIcons.configFile, content: }, + { id: "ConfigFile", title: tabIcons.configFile, content: }, // comment out for prod { id: "Setup", title: tabIcons.setup, content: setupContent }, ] : [ diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 91fdc39..a046594 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -7,10 +7,11 @@ interface Props { targets: GameTarget[]; runningGame: GameTarget | null; onSelect: (appid: string) => void; + onEnableAll: () => Promise; onResetAll: () => Promise; } -const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed"; +const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed-v2"; const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed"; function usePersistentCollapsed(key: string) { @@ -73,7 +74,7 @@ function GameGroup({ ); } -export function GameConfigurationSelector({ targets, runningGame, onSelect, onResetAll }: Props) { +export function GameConfigurationSelector({ targets, runningGame, onSelect, onEnableAll, onResetAll }: Props) { const sortGames = (games: GameTarget[]) => [...games].sort((a, b) => { if (a.appid === runningGame?.appid) return -1; if (b.appid === runningGame?.appid) return 1; @@ -81,8 +82,14 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onRe }); const configuredGames = sortGames(targets.filter((game) => game.configured)); const availableGames = sortGames(targets.filter((game) => !game.configured)); + const configuredSteamGames = configuredGames.filter((game) => !game.nonSteam); + const configuredNonSteamGames = configuredGames.filter((game) => game.nonSteam); + const availableSteamGames = availableGames.filter((game) => !game.nonSteam); + const availableNonSteamGames = availableGames.filter((game) => game.nonSteam); const [configuredCollapsed, toggleConfigured] = usePersistentCollapsed(CONFIGURED_COLLAPSED_KEY); + const [configuredNonSteamCollapsed, toggleConfiguredNonSteam] = usePersistentCollapsed(`${CONFIGURED_COLLAPSED_KEY}-non-steam`); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); + const [availableNonSteamCollapsed, toggleAvailableNonSteam] = usePersistentCollapsed(`${AVAILABLE_COLLAPSED_KEY}-non-steam`); const confirmResetAll = () => { showModal( , ); }; + const confirmEnableAll = () => { + showModal( + void onEnableAll()} + onCancel={() => {}} + />, + ); + }; return ( <> @@ -102,20 +121,41 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onRe )} + {availableGames.length > 0 && ( + + + Enable all available games + + + )} + + Promise; - onRemove: () => Promise; } -export function NowPlayingTab({ game, config, onConfigChange, onRemove }: Props) { +export function NowPlayingTab({ game, config, onConfigChange }: Props) { return ( - + - - void onRemove()}> - Remove profile - - ); } diff --git a/src/config/generatedConfigSchema.ts b/src/config/generatedConfigSchema.ts index 71459eb..3668b5b 100644 --- a/src/config/generatedConfigSchema.ts +++ b/src/config/generatedConfigSchema.ts @@ -21,11 +21,11 @@ export const CONFIG_SCHEMA: Record = { active_in: { name: "active_in", fieldType: ConfigFieldType.ARRAY, default: [], description: "Steam AppID or executable identifiers" }, pacing_mode: { name: "pacing_mode", fieldType: ConfigFieldType.STRING, default: "vsync", description: "Frame pacing mode" }, multiplier: { name: "multiplier", fieldType: ConfigFieldType.INTEGER, default: 2, description: "Frame generation multiplier" }, - flow_scale: { name: "flow_scale", fieldType: ConfigFieldType.FLOAT, default: 1, description: "Motion estimation resolution scale" }, + flow_scale: { name: "flow_scale", fieldType: ConfigFieldType.FLOAT, default: 0.8, description: "Motion estimation resolution scale" }, performance_mode: { name: "performance_mode", fieldType: ConfigFieldType.BOOLEAN, default: false, description: "Use the lighter frame generation model" }, override_present_mode: { name: "override_present_mode", fieldType: ConfigFieldType.BOOLEAN, default: true, description: "Override present mode" }, preserve_swapchain_image_count: { name: "preserve_swapchain_image_count", fieldType: ConfigFieldType.BOOLEAN, default: false, description: "Preserve the swapchain image count" }, }; export function getFieldNames(): string[] { return Object.keys(CONFIG_SCHEMA); } -export function getDefaults(): ConfigurationData { return { dll: "", no_fp16: false, active_in: [], pacing_mode: "vsync", multiplier: 2, flow_scale: 1, performance_mode: false, override_present_mode: true, preserve_swapchain_image_count: false }; } +export function getDefaults(): ConfigurationData { return { dll: "", no_fp16: false, active_in: [], pacing_mode: "vsync", multiplier: 2, flow_scale: 0.8, performance_mode: false, override_present_mode: true, preserve_swapchain_image_count: false }; } export function getFieldTypes(): Record { return Object.fromEntries(Object.entries(CONFIG_SCHEMA).map(([key, value]) => [key, value.fieldType])); } diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index d279a8c..597edca 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,10 +1,36 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; import { getGameConfigs, getInstalledGames, updateGameConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type GlobalConfig, type InstalledGame } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; +import { showErrorToast } from "../utils/toastUtils"; export interface GameTarget extends InstalledGame { configured: boolean; } +async function getSteamShortcuts(): Promise { + const apps = (globalThis as any).SteamClient?.Apps; + if (typeof apps?.GetAllShortcuts !== "function") return []; + + try { + const shortcuts = await apps.GetAllShortcuts(); + if (!Array.isArray(shortcuts)) return []; + return shortcuts.flatMap((shortcut: any) => { + const appid = Number(shortcut?.appid); + const name = shortcut?.data?.strAppName; + if (!Number.isInteger(appid) || appid === 0 || typeof name !== "string" || !name) return []; + return [{ appid: String(appid >>> 0), name, nonSteam: true }]; + }); + } catch { + return []; + } +} + +function mergeInstalledGames(backendGames: InstalledGame[], shortcutGames: InstalledGame[]) { + const games = new Map(backendGames.map((game) => [game.appid, game])); + for (const game of shortcutGames) games.set(game.appid, game); + return Array.from(games.values()); +} + export function useGameConfiguration() { const [games, setGames] = useState([]); const [globalConfig, setGlobalConfig] = useState({ dll: "", no_fp16: false }); @@ -13,18 +39,25 @@ export function useGameConfiguration() { const [selectedAppId, setSelectedAppId] = useState(""); const [runningGame, setRunningGame] = useState(null); const previousRunningAppId = useRef(null); + const previousQuickAccessVisible = useRef(null); + const quickAccessVisible = useQuickAccessVisible(); const load = useCallback(async () => { - const [result, installed] = await Promise.all([getGameConfigs(), getInstalledGames()]); + const [result, installed, shortcuts] = await Promise.all([getGameConfigs(), getInstalledGames(), getSteamShortcuts()]); if (result.success) { setGlobalConfig(result.global_config || { dll: "", no_fp16: false }); setGames(result.games || []); } - if (installed.success) setInstalledGames(installed.games || []); + setInstalledGames(mergeInstalledGames(installed.success ? installed.games || [] : [], shortcuts)); setConfigsLoaded(true); }, []); - useEffect(() => { load(); }, [load]); + useEffect(() => { + const initialLoad = previousQuickAccessVisible.current === null; + const becameVisible = quickAccessVisible && previousQuickAccessVisible.current === false; + previousQuickAccessVisible.current = quickAccessVisible; + if (initialLoad || becameVisible) void load(); + }, [load, quickAccessVisible]); useEffect(() => { const poll = () => { if (!configsLoaded) return; @@ -75,6 +108,18 @@ export function useGameConfiguration() { if (result.success) await load(); return result.success; }, [load, targets, template]); + const enableAll = useCallback(async (): Promise => { + const available = targets.filter((target) => !target.configured && target.name); + if (available.length === 0) return; + for (const target of available) { + const result = await updateGameConfig(target.appid, target.name, template); + if (!result.success) { + showErrorToast("Could not enable all games", result.error || "A game profile could not be created"); + return; + } + } + await load(); + }, [load, targets, template]); const resetSelected = useCallback(async () => { if (selectedAppId) { @@ -95,5 +140,5 @@ export function useGameConfiguration() { } }, [load]); - return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, resetSelected, resetAll, reload: load }; + return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, resetSelected, resetAll, reload: load }; } -- cgit v1.2.3 From e21eee83fc58fee3481aa0e17feb7cd9a8d8750e Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 20:16:09 -0400 Subject: Support lowercase Steam shortcut names and collapsible profile details --- src/components/ConfigurationTab.tsx | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 83f46c1..2175eb9 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,5 +1,6 @@ import { ButtonItem, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; import { GameConfigurationControls } from "./GameConfigurationControls"; @@ -29,6 +30,7 @@ export function ConfigurationTab({ onResetAll, }: ConfigurationTabProps) { const [detailAppId, setDetailAppId] = useState(null); + const [detailsExpanded, setDetailsExpanded] = useState(false); const [focusFpsMultiplier, setFocusFpsMultiplier] = useState(false); const [focusDetailAction, setFocusDetailAction] = useState<"enable" | "back" | null>(null); const backToGamesRef = useRef(null); @@ -41,6 +43,8 @@ export function ConfigurationTab({ }, []); const clearFpsFocusRequest = useCallback(() => setFocusFpsMultiplier(false), []); + useEffect(() => setDetailsExpanded(false), [detailAppId]); + useEffect(() => { if (!focusDetailAction) return; const frame = requestAnimationFrame(() => { @@ -101,7 +105,7 @@ export function ConfigurationTab({ - + {!selectedTarget?.configured && selectedTarget && ( @@ -129,6 +133,20 @@ export function ConfigurationTab({ Remove profile )} + + setDetailsExpanded((expanded) => !expanded)} + > + {detailsExpanded ? : } Details + + + {detailsExpanded && ( + + + + )} ); } -- cgit v1.2.3 From 54acc36f16e1336772354f979a618cce65061f82 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 20:57:26 -0400 Subject: refactor: make runtime installation explicit --- src/components/ConfigurationTab.tsx | 11 +++++++++-- src/i18n/i18n.ts | 25 ++++++++++++++----------- 2 files changed, 23 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 2175eb9..b3c0281 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,5 +1,6 @@ -import { ButtonItem, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; +import { FaArrowLeft } from "react-icons/fa"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; @@ -116,7 +117,13 @@ export function ConfigurationTab({ )} - Back to games + + +
diff --git a/src/i18n/i18n.ts b/src/i18n/i18n.ts index dc8de8b..31a55cb 100644 --- a/src/i18n/i18n.ts +++ b/src/i18n/i18n.ts @@ -2,8 +2,16 @@ // to generate for localhost/dev, run `build_i18n_json.sh` script import * as languages from "./languages.json"; -const steamLanguageMap: Record = - languages.steam_language_map as Record; +type LanguageStrings = Record; +type Language = { name: string; strings?: LanguageStrings }; +type LanguageData = { + language_metadata: Record; + steam_language_map: Record; + [language: string]: LanguageStrings | Record | Record; +}; + +const languageData = languages as unknown as LanguageData; +const steamLanguageMap = languageData.steam_language_map; const normalizeLanguage = (language: string): string => { const normalized = language.trim().toLowerCase(); @@ -11,13 +19,13 @@ const normalizeLanguage = (language: string): string => { }; function getLangs() { - const langs = languages.language_metadata; + const langs = languageData.language_metadata; - Object.keys(languages).map((lang) => { + Object.keys(languageData).forEach((lang) => { if (lang === "language_metadata" || lang == "steam_language_map") { return; } - const strs = languages[lang]; + const strs = languageData[lang] as LanguageStrings; if (lang && strs && langs[lang]?.name) { langs[lang].strings = strs; } @@ -27,12 +35,7 @@ function getLangs() { } export const LANGS: { - [key: string]: { - name: string; - strings: { - [key: string]: string; - }; - }; + [key: string]: Language; } = getLangs(); let cachedLang: string | undefined; -- cgit v1.2.3 From 5b84a7ab2782ce672b51dc9d608c63c9ac8ff3ab Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 21:04:26 -0400 Subject: feat: show Flatpak runtime readiness --- src/components/FlatpaksTab.tsx | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/components/FlatpaksTab.tsx b/src/components/FlatpaksTab.tsx index 27204f4..8aab940 100644 --- a/src/components/FlatpaksTab.tsx +++ b/src/components/FlatpaksTab.tsx @@ -50,18 +50,21 @@ function RuntimeRow({ version, installed, busy, onAction }: RuntimeRowProps) { interface AppRowProps { app: FlatpakApp; + runtimeReady: boolean; busy: boolean; onToggle: () => void; } -function AppRow({ app, busy, onToggle }: AppRowProps) { +function AppRow({ app, runtimeReady, 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") + ? runtimeReady + ? t("FLATPAK_STATUS_READY", "Ready") + : t("FLATPAK_STATUS_RUNTIME_MISSING", "Runtime missing") : partial ? t("FLATPAK_STATUS_PARTIAL", "Partial") - : t("FLATPAK_STATUS_NO_OVERRIDES", "No overrides"); + : t("FLATPAK_STATUS_NOT_ENABLED", "Not enabled"); return ( @@ -82,6 +85,8 @@ export function FlatpaksTab() { const [loading, setLoading] = useState(true); const [operation, setOperation] = useState(null); const [error, setError] = useState(null); + const runtimeReady = extensionStatus?.success === true + && runtimeVersions.some(({ key }) => extensionStatus[key]); const load = async () => { setLoading(true); @@ -180,6 +185,7 @@ export function FlatpaksTab() { void toggleApp(app)} /> -- cgit v1.2.3 From 85bb5c9da5bb5ea64ddca1aeca1dc6ba656bb86c Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Mon, 7 Sep 2026 23:40:11 -0400 Subject: fix: focus configured game controls --- src/components/ConfigurationTab.tsx | 58 +++++++++++++++---------------------- 1 file changed, 24 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index b3c0281..b94522a 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,7 +1,6 @@ import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; -import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; import { GameConfigurationControls } from "./GameConfigurationControls"; @@ -31,10 +30,8 @@ export function ConfigurationTab({ onResetAll, }: ConfigurationTabProps) { const [detailAppId, setDetailAppId] = useState(null); - const [detailsExpanded, setDetailsExpanded] = useState(false); const [focusFpsMultiplier, setFocusFpsMultiplier] = useState(false); - const [focusDetailAction, setFocusDetailAction] = useState<"enable" | "back" | null>(null); - const backToGamesRef = useRef(null); + const [focusDetailAction, setFocusDetailAction] = useState<"enable" | "fps" | null>(null); const enableRef = useRef(null); const promptedRunningAppId = useRef(null); const closeDetails = useCallback(() => { @@ -44,13 +41,15 @@ export function ConfigurationTab({ }, []); const clearFpsFocusRequest = useCallback(() => setFocusFpsMultiplier(false), []); - useEffect(() => setDetailsExpanded(false), [detailAppId]); - useEffect(() => { if (!focusDetailAction) return; + if (focusDetailAction === "fps") { + setFocusFpsMultiplier(true); + setFocusDetailAction(null); + return; + } const frame = requestAnimationFrame(() => { - const ref = focusDetailAction === "enable" ? enableRef : backToGamesRef; - ref.current?.querySelector('[role="button"]')?.focus(); + enableRef.current?.querySelector('[role="button"]')?.focus(); setFocusDetailAction(null); }); return () => cancelAnimationFrame(frame); @@ -63,7 +62,7 @@ export function ConfigurationTab({ } if (promptedRunningAppId.current !== runningGame.appid && detailAppId === null) { promptedRunningAppId.current = runningGame.appid; - setFocusDetailAction(runningGame.configured ? "back" : "enable"); + setFocusDetailAction("enable"); setDetailAppId(runningGame.appid); } }, [detailAppId, runningGame?.appid, runningGame?.configured]); @@ -77,7 +76,7 @@ export function ConfigurationTab({ targets={targets} runningGame={runningGame} onSelect={(appid) => { - setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "back" : "enable"); + setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "fps" : "enable"); onSelect(appid); setDetailAppId(appid); }} @@ -104,7 +103,20 @@ export function ConfigurationTab({ return ( - + + + + + + + + + + @@ -115,17 +127,6 @@ export function ConfigurationTab({ )} - - - - - - -
{selectedTarget?.configured && ( )} - setDetailsExpanded((expanded) => !expanded)} - > - {detailsExpanded ? : } Details - + - {detailsExpanded && ( - - - - )} ); } -- cgit v1.2.3 From c6c24524b46e237bee796cb57b9a27c437c458ae Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Tue, 8 Sep 2026 09:07:51 -0400 Subject: fix: make game group collapse controls compact --- src/components/GameConfigurationSelector.tsx | 32 ++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index a046594..15f2465 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -52,13 +52,25 @@ function GameGroup({ return ( <> - + + +
- {collapsed ? : } {title} ({games.length}) - + + {collapsed ? ( + + ) : ( + + )} + +
{!collapsed && games.map((game) => ( @@ -116,6 +128,14 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onEn return ( <> + {targets.length === 0 && ( -- cgit v1.2.3 From b3749ecc4b094a46d2ab9f638ee810f70840f67a Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Tue, 8 Sep 2026 11:31:46 -0400 Subject: update layout and config and hash --- src/components/ConfigurationTab.tsx | 33 +++++++++++++++++-------- src/components/GameConfigurationSelector.tsx | 23 +++++++++++------ src/components/NowPlayingTab.tsx | 1 - src/components/ProfileDetails.tsx | 37 ++++++++++++++++++++++++++++ 4 files changed, 76 insertions(+), 18 deletions(-) create mode 100644 src/components/ProfileDetails.tsx (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index b94522a..6ba8f5d 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,10 +1,11 @@ -import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import { ButtonItem, DialogButton, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; import { GameConfigurationControls } from "./GameConfigurationControls"; import { GameConfigurationSelector } from "./GameConfigurationSelector"; +import { ProfileDetails } from "./ProfileDetails"; interface ConfigurationTabProps { config: ConfigurationData; @@ -105,21 +106,35 @@ export function ConfigurationTab({ - +
+ - + +
+ {profileLabel} +
+
- - - {!selectedTarget?.configured && selectedTarget && ( @@ -141,9 +156,7 @@ export function ConfigurationTab({ Remove profile )} - - - +
); } diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 15f2465..5f23b91 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -11,15 +11,15 @@ interface Props { onResetAll: () => Promise; } -const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed-v2"; -const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed"; +const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed-v3"; +const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed-v2"; function usePersistentCollapsed(key: string) { const [collapsed, setCollapsed] = useState(() => { try { - return localStorage.getItem(key) === "true"; + return localStorage.getItem(key) !== "false"; } catch { - return false; + return true; } }); @@ -65,9 +65,9 @@ function GameGroup({ onClick={onToggle} > {collapsed ? ( - + ) : ( - + )}
@@ -132,7 +132,16 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onEn {` .LSFG_GameGroupCollapseButton_Container > div > div > div > button, .LSFG_GameGroupCollapseButton_Container > div > div > div > div > button { - height: 10px !important; + height: 24px !important; + padding: 0 !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + } + + .LSFG_GameGroupCollapseButton_Container svg { + display: block; + margin: 0; } `} diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index 8d2d779..2ec12ca 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -16,7 +16,6 @@ export function NowPlayingTab({ game, config, onConfigChange }: Props) { diff --git a/src/components/ProfileDetails.tsx b/src/components/ProfileDetails.tsx new file mode 100644 index 0000000..056abbb --- /dev/null +++ b/src/components/ProfileDetails.tsx @@ -0,0 +1,37 @@ +import { ButtonItem, Field, Focusable, PanelSectionRow } from "@decky/ui"; +import { useEffect, useRef, useState } from "react"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; + +interface ProfileDetailsProps { + description: string; +} + +export function ProfileDetails({ description }: ProfileDetailsProps) { + const [expanded, setExpanded] = useState(false); + const detailsRef = useRef(null); + + useEffect(() => { + if (!expanded) return; + const frame = requestAnimationFrame(() => detailsRef.current?.scrollIntoView({ block: "nearest" })); + return () => cancelAnimationFrame(frame); + }, [expanded]); + + return ( + + + setExpanded((value) => !value)} + > + {expanded ? : } Details + + + {expanded && ( + + + + )} + + ); +} -- cgit v1.2.3 From 8352ee74e8a437c1f4a4dadb75d63049f45b164b Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Tue, 8 Sep 2026 16:25:11 -0400 Subject: add back workarounds sections, scope out of now playing --- src/components/ConfigurationTab.tsx | 2 + src/components/GameConfigurationControls.tsx | 9 + src/components/NowPlayingTab.tsx | 2 +- src/components/WorkaroundsSection.tsx | 190 +++++++++++ src/components/index.ts | 1 + src/hooks/useGameConfiguration.ts | 27 +- src/hooks/usePerAppWorkarounds.ts | 173 ++++++++++ src/i18n/languages.json | 48 +-- src/types.d.ts | 24 ++ src/utils/steamLaunchOptionParser.ts | 489 +++++++++++++++++++++++++++ src/utils/steamLaunchOptions.ts | 211 ++++++++++++ 11 files changed, 1141 insertions(+), 35 deletions(-) create mode 100644 src/components/WorkaroundsSection.tsx create mode 100644 src/hooks/usePerAppWorkarounds.ts create mode 100644 src/utils/steamLaunchOptionParser.ts create mode 100644 src/utils/steamLaunchOptions.ts (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 6ba8f5d..2bb0f26 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -149,6 +149,8 @@ export function ConfigurationTab({ onConfigChange={onConfigChange} autoFocusFpsMultiplier={focusFpsMultiplier} onFpsMultiplierFocused={clearFpsFocusRequest} + showWorkarounds + workaroundTarget={selectedTarget || undefined} /> )} {selectedTarget?.configured && ( diff --git a/src/components/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx index 34b82c5..58ccd02 100644 --- a/src/components/GameConfigurationControls.tsx +++ b/src/components/GameConfigurationControls.tsx @@ -1,12 +1,16 @@ import { ConfigurationData } from "../config/configSchema"; +import type { GameTarget } from "../hooks/useGameConfiguration"; import { ConfigurationSection } from "./ConfigurationSection"; import { FpsMultiplierControl } from "./FpsMultiplierControl"; +import { WorkaroundsSection } from "./WorkaroundsSection"; interface Props { config: ConfigurationData; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; autoFocusFpsMultiplier?: boolean; onFpsMultiplierFocused?: () => void; + showWorkarounds?: boolean; + workaroundTarget?: Pick; } export function GameConfigurationControls({ @@ -14,6 +18,8 @@ export function GameConfigurationControls({ onConfigChange, autoFocusFpsMultiplier, onFpsMultiplierFocused, + showWorkarounds = false, + workaroundTarget, }: Props) { return ( <> @@ -24,6 +30,9 @@ export function GameConfigurationControls({ onAutoFocus={onFpsMultiplierFocused} /> + {showWorkarounds && workaroundTarget && ( + + )} ); } diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index 2ec12ca..188c56a 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -19,7 +19,7 @@ export function NowPlayingTab({ game, config, onConfigChange }: Props) { />
- + ); } diff --git a/src/components/WorkaroundsSection.tsx b/src/components/WorkaroundsSection.tsx new file mode 100644 index 0000000..e990784 --- /dev/null +++ b/src/components/WorkaroundsSection.tsx @@ -0,0 +1,190 @@ +import { ButtonItem, Field, PanelSectionRow, SliderField, ToggleField } from "@decky/ui"; +import { useEffect, useState } from "react"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; +import { usePerAppWorkarounds } from "../hooks/usePerAppWorkarounds"; +import t from "../i18n/i18n"; +import type { WorkaroundField } from "../utils/steamLaunchOptions"; + +interface WorkaroundsSectionProps { + appId: string; + nonSteam: boolean; +} + +const WORKAROUNDS_COLLAPSED_KEY = "lsfg-workarounds-collapsed"; +type ToggleWorkaroundField = Exclude; + +const TOGGLE_ROWS: readonly { + field: ToggleWorkaroundField; + labelKey: string; + label: string; + descriptionKey: string; + description: string; +}[] = [ + { + field: "disableGamescopeWsi", + labelKey: "CONFIG_DISABLE_GAMESCOPE_WSI", + label: "Disable Gamescope WSI", + descriptionKey: "CONFIG_DISABLE_GAMESCOPE_WSI_DESC", + description: "Adds ENABLE_GAMESCOPE_WSI=0 without changing HDR. Requires game restart to apply.", + }, + { + field: "disableSteamdeckMode", + labelKey: "CONFIG_DISABLE_STEAMDECK_MODE", + label: "Disable Steam Deck Mode", + descriptionKey: "CONFIG_DISABLE_STEAMDECK_MODE_DESC", + description: "Disables a game-specific Steam Deck compatibility switch. Requires game restart to apply.", + }, + { + field: "disableVkbasalt", + labelKey: "CONFIG_DISABLE_VKBASALT", + label: "Disable vkBasalt", + descriptionKey: "CONFIG_DISABLE_VKBASALT_DESC", + description: "Disables vkBasalt layer which can conflict with LSFG (Reshade, some Decky plugins)", + }, + { + field: "enableZink", + labelKey: "CONFIG_ENABLE_ZINK", + label: "Force Zink for OpenGL Games", + descriptionKey: "CONFIG_ENABLE_ZINK_DESC", + description: "Uses Mesa's Zink OpenGL-to-Vulkan driver. May cause crashes or freezes with some games. Requires game restart to apply.", + }, +]; + +function usePersistentCollapsed() { + const [collapsed, setCollapsed] = useState(() => { + try { + const saved = localStorage.getItem(WORKAROUNDS_COLLAPSED_KEY); + return saved !== null ? JSON.parse(saved) === true : true; + } catch { + return true; + } + }); + + useEffect(() => { + try { + localStorage.setItem(WORKAROUNDS_COLLAPSED_KEY, JSON.stringify(collapsed)); + } catch { + // Persisting the view preference is optional. + } + }, [collapsed]); + + return [collapsed, () => setCollapsed((value) => !value)] as const; +} + +export function WorkaroundsSection({ appId, nonSteam }: WorkaroundsSectionProps) { + const [collapsed, toggleCollapsed] = usePersistentCollapsed(); + const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam); + const state = snapshot?.parsed.state; + const issues = snapshot?.parsed.issues || []; + const controlsDisabled = status !== "ready" || state === undefined; + const [fpsValue, setFpsValue] = useState(null); + const effectiveFpsValue = fpsValue ?? state?.dxvkFrameRate ?? 0; + const fpsLabel = effectiveFpsValue > 0 + ? `${effectiveFpsValue} FPS` + : t("CONFIG_BASE_FPS_CAP_OFF", "Off"); + + useEffect(() => { + setFpsValue(state?.dxvkFrameRate ?? null); + }, [state?.dxvkFrameRate, status]); + + return ( + <> + + +
+ {t("CONFIG_WORKAROUNDS_TITLE", "Workarounds")} +
+
+ +
+ + {collapsed ? : } + +
+
+ + {!collapsed && ( + <> + {status === "loading" && ( + + + + )} + {status === "error" && ( + <> + + + + + void refresh()}>Retry + + + )} + {status === "ready" && issues.length > 0 && ( + + + + )} + + + { + setFpsValue(value); + void update("dxvkFrameRate", value); + }} + disabled={controlsDisabled} + /> + + {TOGGLE_ROWS.map((row) => ( + + void update(row.field, value)} + disabled={controlsDisabled} + /> + + ))} + + )} + + ); +} diff --git a/src/components/index.ts b/src/components/index.ts index 424a360..37a8edb 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -10,3 +10,4 @@ export { FlatpaksTab } from "./FlatpaksTab"; export { GameConfigurationSelector } from "./GameConfigurationSelector"; export { GameConfigurationControls } from "./GameConfigurationControls"; export { NowPlayingTab } from "./NowPlayingTab"; +export { WorkaroundsSection } from "./WorkaroundsSection"; diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 597edca..7a572f9 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -3,6 +3,7 @@ import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; import { getGameConfigs, getInstalledGames, updateGameConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type GlobalConfig, type InstalledGame } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; +import { cleanupSteamLaunchOptions } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; export interface GameTarget extends InstalledGame { configured: boolean; } @@ -94,6 +95,17 @@ export function useGameConfiguration() { const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); const config = games.find((game) => game.appid === selectedAppId)?.config || template; + const cleanupTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { + if (!installedGames.some((game) => game.appid === target.appid)) return true; + try { + await cleanupSteamLaunchOptions(Number(target.appid), target.nonSteam); + return true; + } catch (error) { + showErrorToast("Could not update Steam launch options", error instanceof Error ? error.message : String(error)); + return false; + } + }, [installedGames]); + const save = useCallback(async (next: ConfigurationData) => { const selectedTarget = targets.find((target) => target.appid === selectedAppId); if (!selectedTarget?.name) return; @@ -104,14 +116,16 @@ export function useGameConfiguration() { const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; + if (!(await cleanupTargetLaunchOptions(target))) return false; const result = await updateGameConfig(appid, target.name, template); if (result.success) await load(); return result.success; - }, [load, targets, template]); + }, [cleanupTargetLaunchOptions, load, targets, template]); const enableAll = useCallback(async (): Promise => { const available = targets.filter((target) => !target.configured && target.name); if (available.length === 0) return; for (const target of available) { + if (!(await cleanupTargetLaunchOptions(target))) return; const result = await updateGameConfig(target.appid, target.name, template); if (!result.success) { showErrorToast("Could not enable all games", result.error || "A game profile could not be created"); @@ -119,10 +133,12 @@ export function useGameConfiguration() { } } await load(); - }, [load, targets, template]); + }, [cleanupTargetLaunchOptions, load, targets, template]); const resetSelected = useCallback(async () => { if (selectedAppId) { + const selectedTarget = targets.find((target) => target.appid === selectedAppId); + if (selectedTarget && !(await cleanupTargetLaunchOptions(selectedTarget))) return; const result = await resetGameConfig(selectedAppId); if (result.success) { setRunningGame((current) => current?.appid === selectedAppId ? { ...current, configured: false } : current); @@ -130,15 +146,18 @@ export function useGameConfiguration() { await load(); } } - }, [load, selectedAppId]); + }, [cleanupTargetLaunchOptions, load, selectedAppId, targets]); const resetAll = useCallback(async () => { + for (const target of targets.filter((item) => item.configured)) { + if (!(await cleanupTargetLaunchOptions(target))) return; + } const result = await resetAllGameConfigs(); if (result.success) { setRunningGame((current) => current ? { ...current, configured: false } : current); setSelectedAppId(""); await load(); } - }, [load]); + }, [cleanupTargetLaunchOptions, load, targets]); return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, resetSelected, resetAll, reload: load }; } diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts new file mode 100644 index 0000000..a937780 --- /dev/null +++ b/src/hooks/usePerAppWorkarounds.ts @@ -0,0 +1,173 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + applyWorkaroundChange, + parseWorkaroundOptions, + readSteamLaunchOptions, + subscribeSteamLaunchOptions, + updateSteamLaunchOptions, + type ParsedWorkaroundOptions, + type SteamLaunchOptionsSnapshot, + type WorkaroundField, +} from "../utils/steamLaunchOptions"; +import { showErrorToast } from "../utils/toastUtils"; + +export type WorkaroundLoadStatus = "loading" | "ready" | "error"; + +const SLIDER_DEBOUNCE_MS = 250; + +interface PendingSliderUpdate { + timer: number; + value: number; + waiters: Array<(success: boolean) => void>; +} + +interface WorkaroundSnapshot { + steam: SteamLaunchOptionsSnapshot; + parsed: ParsedWorkaroundOptions; +} + +interface PerAppWorkarounds { + status: WorkaroundLoadStatus; + snapshot: WorkaroundSnapshot | null; + refresh: () => Promise; + update: (field: WorkaroundField, value: boolean | number) => Promise; + error: string | null; +} + +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} + +function makeSnapshot(steam: SteamLaunchOptionsSnapshot): WorkaroundSnapshot { + return { steam, parsed: parseWorkaroundOptions(steam.options) }; +} + +export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWorkarounds { + const [status, setStatus] = useState("loading"); + const [snapshot, setSnapshot] = useState(null); + const [error, setError] = useState(null); + const pendingSliderUpdate = useRef(null); + const numericAppId = Number(appId); + + const applySnapshot = useCallback((steam: SteamLaunchOptionsSnapshot) => { + setSnapshot(makeSnapshot(steam)); + setStatus("ready"); + setError(null); + }, []); + + const refresh = useCallback(async () => { + setStatus("loading"); + setError(null); + try { + applySnapshot(await readSteamLaunchOptions(numericAppId, nonSteam)); + } catch (refreshError) { + const nextError = asError(refreshError); + setStatus("error"); + setError(nextError.message); + } + }, [applySnapshot, nonSteam, numericAppId]); + + useEffect(() => { + let active = true; + setStatus("loading"); + setSnapshot(null); + setError(null); + + const handleSnapshot = (nextSnapshot: SteamLaunchOptionsSnapshot) => { + if (!active) return; + applySnapshot(nextSnapshot); + }; + const handleSubscriptionError = (subscriptionError: Error) => { + if (!active) return; + setStatus("error"); + setError(subscriptionError.message); + }; + + let unsubscribe = () => {}; + try { + unsubscribe = subscribeSteamLaunchOptions( + numericAppId, + nonSteam, + handleSnapshot, + handleSubscriptionError, + ); + } catch (subscriptionError) { + handleSubscriptionError(asError(subscriptionError)); + } + + void readSteamLaunchOptions(numericAppId, nonSteam) + .then((nextSnapshot) => { + if (active) applySnapshot(nextSnapshot); + }) + .catch((readError) => { + if (active) handleSubscriptionError(asError(readError)); + }); + + return () => { + active = false; + unsubscribe(); + }; + }, [applySnapshot, nonSteam, numericAppId]); + + const persistUpdate = useCallback(async (field: WorkaroundField, value: boolean | number): Promise => { + setError(null); + try { + const nextSnapshot = await updateSteamLaunchOptions( + numericAppId, + nonSteam, + (options) => applyWorkaroundChange(options, field, value), + ); + applySnapshot(nextSnapshot); + return true; + } catch (updateError) { + const nextError = asError(updateError); + setStatus("error"); + setError(nextError.message); + showErrorToast("Workaround update failed", nextError.message); + return false; + } + }, [applySnapshot, nonSteam, numericAppId]); + + const flushSliderUpdate = useCallback(async (): Promise => { + const pending = pendingSliderUpdate.current; + if (!pending) return true; + + pendingSliderUpdate.current = null; + window.clearTimeout(pending.timer); + const success = await persistUpdate("dxvkFrameRate", pending.value); + pending.waiters.forEach((resolve) => resolve(success)); + return success; + }, [persistUpdate]); + + const update = useCallback(async (field: WorkaroundField, value: boolean | number): Promise => { + if (field === "dxvkFrameRate") { + setError(null); + return new Promise((resolve) => { + const pending = pendingSliderUpdate.current ?? { timer: 0, value: 0, waiters: [] }; + window.clearTimeout(pending.timer); + pending.value = Number(value); + pending.waiters.push(resolve); + pending.timer = window.setTimeout(() => { + void flushSliderUpdate(); + }, SLIDER_DEBOUNCE_MS); + pendingSliderUpdate.current = pending; + }); + } + + const sliderSuccess = await flushSliderUpdate(); + if (!sliderSuccess) return false; + return persistUpdate(field, value); + }, [flushSliderUpdate, persistUpdate]); + + useEffect(() => { + return () => { + const pending = pendingSliderUpdate.current; + if (!pending) return; + window.clearTimeout(pending.timer); + pendingSliderUpdate.current = null; + pending.waiters.forEach((resolve) => resolve(false)); + }; + }, [numericAppId, nonSteam]); + + return useMemo(() => ({ status, snapshot, refresh, update, error }), [error, refresh, snapshot, status, update]); +} diff --git a/src/i18n/languages.json b/src/i18n/languages.json index 3132083..3f1992c 100644 --- a/src/i18n/languages.json +++ b/src/i18n/languages.json @@ -10,7 +10,7 @@ "CONFIG_FLOW_SCALE_DESC": "内部モーション推定解像度を下げて、パフォーマンスをわずかに向上させます", "CONFIG_BASE_FPS_CAP": "基本FPS上限", "CONFIG_BASE_FPS_CAP_OFF": "オフ", - "CONFIG_BASE_FPS_CAP_DESC": "フレーム倍率適用前のDirectXゲームの基本フレームレート上限。(ゲームの再起動が必要)", + "CONFIG_BASE_FPS_CAP_DESC": "フレーム生成前のDXVKゲームの基本上限。0で無効。ゲームの再起動が必要です。", "CONFIG_PRESENT_MODE": "プレゼンテーションモード", "CONFIG_PRESENT_MODE_FIFO": "FIFO - VSync", "CONFIG_PRESENT_MODE_MAILBOX": "Mailbox", @@ -21,18 +21,14 @@ "CONFIG_HDR_MODE_DESC": "HDRモードを有効化します(HDRをサポートするゲームのみ)", "CONFIG_ENABLE_WSI": "WSIを有効化", "CONFIG_ENABLE_WSI_DESC": "Gamescope WSIレイヤーを再有効化します。ゲームの再起動が必要。", - "CONFIG_ENABLE_WOW64": "32ビットゲーム用WOW64を有効化", - "CONFIG_ENABLE_WOW64_DESC": "32ビットゲームにPROTON_USE_WOW64=1を有効化します(ProtonGEと併用してクラッシュを修正)", + "CONFIG_DISABLE_GAMESCOPE_WSI": "Gamescope WSIを無効化", + "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "HDRを変更せずENABLE_GAMESCOPE_WSI=0を追加します。ゲームの再起動が必要です。", "CONFIG_DISABLE_STEAMDECK_MODE": "Steam Deckモードを無効化", - "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "Steam Deckモードを無効化します(一部ゲームの隠し設定を解放)", - "CONFIG_MANGOHUD_WORKAROUND": "MangoHudワークアラウンド", - "CONFIG_MANGOHUD_WORKAROUND_DESC": "透明なMangoHudオーバーレイを有効化します。ゲームモードでの2X倍率問題を修正することがあります", + "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "ゲーム固有のSteam Deck互換スイッチを無効化します。ゲームの再起動が必要です。", "CONFIG_DISABLE_VKBASALT": "vkBasaltを無効化", "CONFIG_DISABLE_VKBASALT_DESC": "LSFGと競合する可能性のあるvkBasaltレイヤーを無効化します(Reshade、一部のDeckyプラグイン)", - "CONFIG_FORCE_ENABLE_VKBASALT": "vkBasaltを強制有効化", - "CONFIG_FORCE_ENABLE_VKBASALT_DESC": "ゲームモードのフレームペーシング問題を修正するためにvkBasaltを強制有効化します", - "CONFIG_ENABLE_ZINK": "OpenGLゲーム用Zinkを有効化", - "CONFIG_ENABLE_ZINK_DESC": "OpenGLゲームにVulkanベースのOpenGL実装を使用します(一部のゲームでクラッシュやフリーズが発生する場合があります)", + "CONFIG_ENABLE_ZINK": "OpenGLゲームでZinkを強制", + "CONFIG_ENABLE_ZINK_DESC": "MesaのZink OpenGL-to-Vulkanドライバーを使用します。一部のゲームでクラッシュやフリーズが発生する可能性があります。ゲームの再起動が必要です。", "INSTALL_INSTALLING": "インストール中...", "INSTALL_UNINSTALLING": "アンインストール中...", "INSTALL_UNINSTALL_BTN": "LSFG-VKをアンインストール", @@ -101,7 +97,7 @@ "CONFIG_FLOW_SCALE_DESC": "내부 모션 추정 해상도를 낮춰 성능을 약간 향상시킵니다", "CONFIG_BASE_FPS_CAP": "기본 FPS 상한", "CONFIG_BASE_FPS_CAP_OFF": "끄기", - "CONFIG_BASE_FPS_CAP_DESC": "프레임 배율 적용 전 DirectX 게임의 기본 프레임 상한. (게임 재시작 필요)", + "CONFIG_BASE_FPS_CAP_DESC": "프레임 생성 전 DXVK 게임의 기본 제한입니다. 0은 비활성화합니다. 게임 재시작 필요.", "CONFIG_PRESENT_MODE": "프레젠테이션 모드", "CONFIG_PRESENT_MODE_FIFO": "FIFO - VSync", "CONFIG_PRESENT_MODE_MAILBOX": "Mailbox", @@ -112,18 +108,14 @@ "CONFIG_HDR_MODE_DESC": "HDR 모드를 활성화합니다 (HDR을 지원하는 게임에만 해당)", "CONFIG_ENABLE_WSI": "WSI 활성화", "CONFIG_ENABLE_WSI_DESC": "Gamescope WSI 레이어를 다시 활성화합니다. 게임 재시작 필요.", - "CONFIG_ENABLE_WOW64": "32비트 게임용 WOW64 활성화", - "CONFIG_ENABLE_WOW64_DESC": "32비트 게임에 PROTON_USE_WOW64=1을 활성화합니다 (크래시 수정을 위해 ProtonGE와 함께 사용)", + "CONFIG_DISABLE_GAMESCOPE_WSI": "Gamescope WSI 비활성화", + "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "HDR을 변경하지 않고 ENABLE_GAMESCOPE_WSI=0을 추가합니다. 게임 재시작 필요.", "CONFIG_DISABLE_STEAMDECK_MODE": "Steam Deck 모드 비활성화", - "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "Steam Deck 모드를 비활성화합니다 (일부 게임의 숨겨진 설정 잠금 해제)", - "CONFIG_MANGOHUD_WORKAROUND": "MangoHud 우회", - "CONFIG_MANGOHUD_WORKAROUND_DESC": "투명한 MangoHud 오버레이를 활성화합니다. 게임 모드에서 2X 배율 문제를 수정하는 데 도움이 될 수 있습니다", + "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "게임별 Steam Deck 호환 스위치를 비활성화합니다. 게임 재시작 필요.", "CONFIG_DISABLE_VKBASALT": "vkBasalt 비활성화", "CONFIG_DISABLE_VKBASALT_DESC": "LSFG와 충돌할 수 있는 vkBasalt 레이어를 비활성화합니다 (Reshade, 일부 Decky 플러그인)", - "CONFIG_FORCE_ENABLE_VKBASALT": "vkBasalt 강제 활성화", - "CONFIG_FORCE_ENABLE_VKBASALT_DESC": "게임 모드에서 프레임 페이싱 문제 수정을 위해 vkBasalt를 강제 활성화합니다", - "CONFIG_ENABLE_ZINK": "OpenGL 게임에 Zink 활성화", - "CONFIG_ENABLE_ZINK_DESC": "OpenGL 게임에 Vulkan 기반 OpenGL 구현을 사용합니다 (일부 게임에서 크래시나 멈춤이 발생할 수 있습니다)", + "CONFIG_ENABLE_ZINK": "OpenGL 게임에 Zink 강제", + "CONFIG_ENABLE_ZINK_DESC": "Mesa의 Zink OpenGL-to-Vulkan 드라이버를 사용합니다. 일부 게임에서 충돌 또는 멈춤이 발생할 수 있으며 게임 재시작이 필요합니다.", "INSTALL_INSTALLING": "설치 중...", "INSTALL_UNINSTALLING": "제거 중...", "INSTALL_UNINSTALL_BTN": "LSFG-VK 제거", @@ -220,7 +212,7 @@ "CONFIG_FLOW_SCALE_DESC": "Lowers internal motion estimation resolution, improving performance slightly", "CONFIG_BASE_FPS_CAP": "Base FPS Cap", "CONFIG_BASE_FPS_CAP_OFF": "Off", - "CONFIG_BASE_FPS_CAP_DESC": "Base framerate cap for DirectX games, before frame multiplier. (Requires game restart to apply)", + "CONFIG_BASE_FPS_CAP_DESC": "Base cap for DXVK-backed games before frame generation; 0 disables. Requires game restart to apply.", "CONFIG_PRESENT_MODE": "Present Mode", "CONFIG_PRESENT_MODE_FIFO": "FIFO - VSync", "CONFIG_PRESENT_MODE_MAILBOX": "Mailbox", @@ -231,18 +223,14 @@ "CONFIG_HDR_MODE_DESC": "Enables HDR mode (only for games that support HDR)", "CONFIG_ENABLE_WSI": "Enable WSI", "CONFIG_ENABLE_WSI_DESC": "Re-Enable Gamescope WSI Layer. Requires game restart to apply.", - "CONFIG_ENABLE_WOW64": "Enable WOW64 for 32-bit games", - "CONFIG_ENABLE_WOW64_DESC": "Enables PROTON_USE_WOW64=1 for 32-bit games (Use with ProtonGE to fix crashing)", + "CONFIG_DISABLE_GAMESCOPE_WSI": "Disable Gamescope WSI", + "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "Adds ENABLE_GAMESCOPE_WSI=0 without changing HDR. Requires game restart to apply.", "CONFIG_DISABLE_STEAMDECK_MODE": "Disable Steam Deck Mode", - "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "Disables Steam Deck mode (Unlocks hidden settings in some games)", - "CONFIG_MANGOHUD_WORKAROUND": "MangoHud Workaround", - "CONFIG_MANGOHUD_WORKAROUND_DESC": "Enables a transparent mangohud overlay, sometimes fixes issues with 2X multiplier in game mode", + "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "Disables a game-specific Steam Deck compatibility switch. Requires game restart to apply.", "CONFIG_DISABLE_VKBASALT": "Disable vkBasalt", "CONFIG_DISABLE_VKBASALT_DESC": "Disables vkBasalt layer which can conflict with LSFG (Reshade, some Decky plugins)", - "CONFIG_FORCE_ENABLE_VKBASALT": "Force Enable vkBasalt", - "CONFIG_FORCE_ENABLE_VKBASALT_DESC": "Force vkBasalt to engage to fix framepacing issues in gamemode", - "CONFIG_ENABLE_ZINK": "Enable Zink for OpenGL Games", - "CONFIG_ENABLE_ZINK_DESC": "Use Vulkan-based OpenGL implementation for OpenGL games (may cause crashes or freezes with some games)", + "CONFIG_ENABLE_ZINK": "Force Zink for OpenGL Games", + "CONFIG_ENABLE_ZINK_DESC": "Uses Mesa's Zink OpenGL-to-Vulkan driver. May cause crashes or freezes with some games. Requires game restart to apply.", "INSTALL_INSTALLING": "Installing...", "INSTALL_UNINSTALLING": "Uninstalling...", "INSTALL_UNINSTALL_BTN": "Uninstall LSFG-VK", diff --git a/src/types.d.ts b/src/types.d.ts index dfc0472..4b88d3d 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -12,3 +12,27 @@ declare module "*.jpg" { const content: string; export default content; } + +interface SteamAppDetails { + strLaunchOptions?: string; + strShortcutLaunchOptions?: string; + strShortcutExe?: string; +} + +interface SteamAppDetailsRegistration { + unregister: () => void; +} + +interface SteamApps { + RegisterForAppDetails( + appId: number, + callback: (details: SteamAppDetails) => void, + ): SteamAppDetailsRegistration; + SetAppLaunchOptions(appId: number, options: string): void | Promise; + SetShortcutLaunchOptions(appId: number, options: string): void | Promise; + GetAllShortcuts?(): Promise; +} + +declare const SteamClient: { + Apps: SteamApps; +}; diff --git a/src/utils/steamLaunchOptionParser.ts b/src/utils/steamLaunchOptionParser.ts new file mode 100644 index 0000000..2fd7b67 --- /dev/null +++ b/src/utils/steamLaunchOptionParser.ts @@ -0,0 +1,489 @@ +export interface WorkaroundState { + dxvkFrameRate: number; + disableGamescopeWsi: boolean; + disableSteamdeckMode: boolean; + disableVkbasalt: boolean; + enableZink: boolean; +} + +export type WorkaroundField = keyof WorkaroundState; + +export interface ParsedWorkaroundOptions { + state: WorkaroundState; + issues: string[]; +} + +interface LaunchToken { + raw: string; + value: string; +} + +interface EnvironmentEntry { + value: string; + count: number; +} + +type BooleanWorkaroundField = Exclude; +type EnvironmentSpec = readonly [key: string, value: string]; +type DxvkFrameRateKey = "dxvk.maxFrameRate" | "dxgi.maxFrameRate" | "d3d9.maxFrameRate"; + +interface WorkaroundDefinition { + spec: EnvironmentSpec; + clear: readonly string[]; + label?: string; +} + +const COMMAND_TOKEN = "%command%"; +const DXVK_FRAME_RATE_KEYS: readonly DxvkFrameRateKey[] = [ + "dxvk.maxFrameRate", + "dxgi.maxFrameRate", + "d3d9.maxFrameRate", +]; +const DXVK_MANAGED_KEYS = new Set(["DXVK_CONFIG", "DXVK_FRAME_RATE"]); +const WORKAROUND_DEFINITIONS = { + disableGamescopeWsi: { + spec: ["ENABLE_GAMESCOPE_WSI", "0"], + clear: ["DISABLE_GAMESCOPE_WSI", "ENABLE_GAMESCOPE_WSI", "DXVK_HDR"], + }, + disableSteamdeckMode: { + spec: ["SteamDeck", "0"], + clear: ["SteamDeck"], + label: "Steam Deck mode", + }, + disableVkbasalt: { + spec: ["DISABLE_VKBASALT", "1"], + clear: ["DISABLE_VKBASALT"], + label: "Disable vkBasalt", + }, + enableZink: { + spec: ["MESA_LOADER_DRIVER_OVERRIDE", "zink"], + clear: ["__GLX_VENDOR_LIBRARY_NAME", "MESA_LOADER_DRIVER_OVERRIDE", "GALLIUM_DRIVER"], + }, +} as const satisfies Record; +const BOOLEAN_WORKAROUND_FIELDS: readonly BooleanWorkaroundField[] = [ + "disableGamescopeWsi", + "disableSteamdeckMode", + "disableVkbasalt", + "enableZink", +]; +const WSI_DISABLE_KEY = "DISABLE_GAMESCOPE_WSI"; +const WSI_ENABLE_KEY = "ENABLE_GAMESCOPE_WSI"; +const MANAGED_ENV_KEYS = new Set([ + ...DXVK_MANAGED_KEYS, + ...BOOLEAN_WORKAROUND_FIELDS.flatMap((field) => WORKAROUND_DEFINITIONS[field].clear), +]); + +const DEFAULT_WORKAROUND_STATE: WorkaroundState = { + dxvkFrameRate: 0, + disableGamescopeWsi: false, + disableSteamdeckMode: false, + disableVkbasalt: false, + enableZink: false, +}; + +export function getDefaultWorkaroundState(): WorkaroundState { + return { ...DEFAULT_WORKAROUND_STATE }; +} + +function decodeToken(raw: string): string { + let value = ""; + let quote: "'" | '"' | null = null; + + for (let index = 0; index < raw.length; index += 1) { + const character = raw[index]; + if (character === "\\" && quote !== "'" && index + 1 < raw.length) { + value += raw[index + 1]; + index += 1; + } else if (quote !== null) { + if (character === quote) quote = null; + else value += character; + } else if (character === "'" || character === '"') { + quote = character; + } else { + value += character; + } + } + + return value; +} + +// Steam stores one shell-like line. Keep each token's raw spelling beside its +// decoded value so managed edits leave unrelated quoting and arguments alone. +function tokenize(options: string): LaunchToken[] { + const tokens: LaunchToken[] = []; + let start = -1; + let quote: "'" | '"' | null = null; + let escaped = false; + + for (let index = 0; index < options.length; index += 1) { + const character = options[index]; + if (start < 0) { + if (/\s/.test(character)) continue; + start = index; + } + + if (escaped) { + escaped = false; + } else if (character === "\\" && quote !== "'") { + escaped = true; + } else if (quote !== null) { + if (character === quote) quote = null; + } else if (character === "'" || character === '"') { + quote = character; + } else if (/\s/.test(character)) { + const raw = options.slice(start, index); + tokens.push({ raw, value: decodeToken(raw) }); + start = -1; + } + } + + if (start >= 0) { + const raw = options.slice(start); + tokens.push({ raw, value: decodeToken(raw) }); + } + return tokens; +} + +function serialize(tokens: readonly LaunchToken[]): string { + return tokens.map((token) => token.raw).join(" "); +} + +export function normalizeLaunchOptions(options: string): string { + return serialize(tokenize(options)); +} + +function parseEnvironmentToken(token: LaunchToken): [string, string] | null { + const separator = token.value.indexOf("="); + if (separator < 1) return null; + const key = token.value.slice(0, separator); + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null; + return [key, token.value.slice(separator + 1)]; +} + +function findCommandIndex(tokens: readonly LaunchToken[]): number { + return tokens.findIndex((token) => token.raw.toLowerCase() === COMMAND_TOKEN); +} + +function leadingEnvironmentCount(tokens: readonly LaunchToken[]): number { + let count = 0; + while (count < tokens.length && parseEnvironmentToken(tokens[count]) !== null) count += 1; + return count; +} + +function effectivePrefixLimit(tokens: readonly LaunchToken[]): number { + // Only assignment words before the first command affect the launched game. + // Anything after a wrapper command is that command's argument, even when it + // happens to look like KEY=value. + return leadingEnvironmentCount(tokens); +} + +function effectiveEnvironmentEntries(tokens: readonly LaunchToken[]): Map { + const entries = new Map(); + for (let index = 0; index < effectivePrefixLimit(tokens); index += 1) { + const parsed = parseEnvironmentToken(tokens[index]); + if (!parsed) continue; + const [key, value] = parsed; + const previous = entries.get(key); + entries.set(key, { value, count: (previous?.count || 0) + 1 }); + } + return entries; +} + +function removePrefixAssignments(tokens: LaunchToken[], predicate: (token: LaunchToken) => boolean): boolean { + const limit = effectivePrefixLimit(tokens); + const retained = tokens.filter((token, index) => index >= limit || !predicate(token)); + if (retained.length === tokens.length) return false; + tokens.splice(0, tokens.length, ...retained); + return true; +} + +function removeAllAssignments(tokens: LaunchToken[], keys: ReadonlySet): boolean { + return removePrefixAssignments(tokens, (token) => { + const parsed = parseEnvironmentToken(token); + return parsed !== null && keys.has(parsed[0]); + }); +} + +function encodeEnvironmentValue(value: string): string { + if (/^[A-Za-z0-9_./:+,%=-]+$/.test(value)) return value; + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +function insertEnvironmentSpecs(tokens: LaunchToken[], specs: readonly EnvironmentSpec[]): void { + tokens.unshift(...specs.map(([key, value]) => ({ + raw: `${key}=${encodeEnvironmentValue(value)}`, + value: `${key}=${value}`, + }))); +} + +function ensureCommandToken(tokens: LaunchToken[]): void { + if (findCommandIndex(tokens) >= 0) return; + tokens.splice(leadingEnvironmentCount(tokens), 0, { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }); +} + +export function isLegacyWrapperToken(value: string): boolean { + const path = decodeToken(value); + return path === "~/lsfg" || path === "/home/deck/lsfg"; +} + +function removeLegacyWrapperFromTokens(tokens: LaunchToken[]): boolean { + const commandIndex = findCommandIndex(tokens); + const prefixEnd = commandIndex >= 0 ? commandIndex : tokens.length; + const wrapperIndex = leadingEnvironmentCount(tokens); + if (wrapperIndex >= prefixEnd || !isLegacyWrapperToken(tokens[wrapperIndex].raw)) return false; + tokens.splice(wrapperIndex, 1); + return true; +} + +interface DxvkConfigAssignment { + values: string[]; + malformed: number; +} + +interface ParsedDxvkConfig { + segments: string[]; + assignments: Map; +} + +function splitDxvkConfig(value: string): string[] { + const segments: string[] = []; + let start = 0; + let quote: "'" | '"' | null = null; + let escaped = false; + + for (let index = 0; index < value.length; index += 1) { + const character = value[index]; + if (escaped) escaped = false; + else if (character === "\\" && quote !== "'") escaped = true; + else if (quote !== null) { + if (character === quote) quote = null; + } else if (character === "'" || character === '"') quote = character; + else if (character === ";") { + segments.push(value.slice(start, index)); + start = index + 1; + } + } + + segments.push(value.slice(start)); + return segments; +} + +function knownDxvkKey(value: string): DxvkFrameRateKey | null { + const key = value.match(/^([A-Za-z][A-Za-z0-9.]*)/)?.[1]; + return key && DXVK_FRAME_RATE_KEYS.includes(key as DxvkFrameRateKey) + ? key as DxvkFrameRateKey + : null; +} + +function parseDxvkConfig(value: string): ParsedDxvkConfig { + const segments = splitDxvkConfig(value); + const assignments = new Map(); + for (const segment of segments) { + const trimmed = segment.trim(); + const key = knownDxvkKey(trimmed); + if (!key) continue; + const match = trimmed.match(/^[A-Za-z][A-Za-z0-9.]*\s*=\s*(.*?)\s*$/); + const entry = assignments.get(key) || { values: [], malformed: 0 }; + if (match) entry.values.push(match[1]); + else entry.malformed += 1; + assignments.set(key, entry); + } + return { segments, assignments }; +} + +function isDxvkFrameRateSegment(segment: string): boolean { + return knownDxvkKey(segment.trim()) !== null; +} + +function parseSupportedFrameRate(value: string): number | null { + if (!/^\d+$/.test(value)) return null; + const numericValue = Number(value); + return Number.isSafeInteger(numericValue) && numericValue <= 60 ? numericValue : null; +} + +function rewriteDxvkFrameRate(tokens: LaunchToken[], frameRate: number): void { + const config = effectiveEnvironmentEntries(tokens).get("DXVK_CONFIG"); + const parsed = parseDxvkConfig(config?.value || ""); + const retained = parsed.segments + .filter((segment) => !isDxvkFrameRateSegment(segment)) + .filter((segment) => segment.trim().length > 0) + .join(";"); + const nextConfig = frameRate > 0 + ? [`dxvk.maxFrameRate = ${frameRate}`, ...(retained ? [retained] : [])].join(";") + : retained; + + removeAllAssignments(tokens, DXVK_MANAGED_KEYS); + if (nextConfig) { + ensureCommandToken(tokens); + insertEnvironmentSpecs(tokens, [["DXVK_CONFIG", nextConfig]]); + } +} + +function environmentSpecsForState(state: WorkaroundState): EnvironmentSpec[] { + return BOOLEAN_WORKAROUND_FIELDS + .filter((field) => state[field]) + .map((field) => WORKAROUND_DEFINITIONS[field].spec); +} + +function validateFrameRate(frameRate: number): void { + if (!Number.isInteger(frameRate) || frameRate < 0 || frameRate > 60) { + throw new Error("Base FPS Cap must be an integer from 0 to 60"); + } +} + +function readBoolean( + entries: Map, + key: string, + label: string, + trueValue: string, + issues: string[], +): boolean { + const entry = entries.get(key); + if (!entry) return false; + const falseValue = trueValue === "1" ? "0" : "1"; + if (entry.value === trueValue) return true; + if (entry.value === falseValue) return false; + issues.push(`${label} has an unsupported value.`); + return false; +} + +export function parseWorkaroundOptions(options: string): ParsedWorkaroundOptions { + const tokens = tokenize(options); + const entries = effectiveEnvironmentEntries(tokens); + const state = getDefaultWorkaroundState(); + const issues: string[] = []; + + for (const [key, entry] of entries) { + if (MANAGED_ENV_KEYS.has(key) && entry.count > 1) { + issues.push(`${key} appears more than once; Steam uses the last value.`); + } + } + + const dxvkConfig = parseDxvkConfig(entries.get("DXVK_CONFIG")?.value || ""); + const effectiveDxvkValues = new Map(); + for (const key of DXVK_FRAME_RATE_KEYS) { + const assignment = dxvkConfig.assignments.get(key); + if (!assignment) continue; + if (assignment.malformed > 0) issues.push(`${key} in DXVK_CONFIG is malformed.`); + if (assignment.values.length > 1) { + issues.push(`${key} appears more than once in DXVK_CONFIG; DXVK uses the last value.`); + } + if (assignment.values.length === 0) continue; + const value = parseSupportedFrameRate(assignment.values[assignment.values.length - 1]); + effectiveDxvkValues.set(key, value); + if (value === null) issues.push(`${key} in DXVK_CONFIG is outside the supported 0-60 range.`); + } + + const unifiedFrameRate = effectiveDxvkValues.get("dxvk.maxFrameRate"); + const dxgiFrameRate = effectiveDxvkValues.get("dxgi.maxFrameRate"); + const d3d9FrameRate = effectiveDxvkValues.get("d3d9.maxFrameRate"); + if (unifiedFrameRate !== undefined) { + if (unifiedFrameRate !== null) state.dxvkFrameRate = unifiedFrameRate; + } else if (dxgiFrameRate !== undefined && d3d9FrameRate !== undefined) { + if (dxgiFrameRate !== null && dxgiFrameRate === d3d9FrameRate) state.dxvkFrameRate = dxgiFrameRate; + else issues.push("DXVK_CONFIG has conflicting or invalid DirectX frame caps."); + } else if (dxgiFrameRate !== undefined || d3d9FrameRate !== undefined) { + const partial = dxgiFrameRate ?? d3d9FrameRate; + if (partial !== null && partial !== undefined) state.dxvkFrameRate = partial; + issues.push("DXVK_CONFIG only caps one DirectX API; adjust the cap to normalize it."); + } + + if (entries.has("DXVK_FRAME_RATE")) { + issues.push("DXVK_FRAME_RATE is obsolete on current DXVK; adjust the cap to migrate it."); + } + + const wsiSignals: boolean[] = []; + const wsiDisable = entries.get(WSI_DISABLE_KEY); + if (wsiDisable) { + if (wsiDisable.value !== "0" && wsiDisable.value !== "1") issues.push("Disable Gamescope WSI has an unsupported value."); + else wsiSignals.push(wsiDisable.value === "1"); + } + const wsiEnable = entries.get(WSI_ENABLE_KEY); + if (wsiEnable) { + if (wsiEnable.value !== "0" && wsiEnable.value !== "1") issues.push("Enable Gamescope WSI has an unsupported value."); + else wsiSignals.push(wsiEnable.value === "0"); + } + if (wsiSignals.length > 0) { + if (wsiSignals.length === 2 && wsiSignals[0] !== wsiSignals[1]) { + issues.push("Gamescope WSI has conflicting enable and disable assignments."); + } + state.disableGamescopeWsi = wsiSignals.some(Boolean); + } + + for (const field of ["disableSteamdeckMode", "disableVkbasalt"] as const) { + const { spec, label } = WORKAROUND_DEFINITIONS[field]; + state[field] = readBoolean(entries, spec[0], label || field, spec[1], issues); + } + + const vkBasaltEnable = entries.get("ENABLE_VKBASALT"); + const vkBasaltDisable = entries.get("DISABLE_VKBASALT"); + if (vkBasaltEnable?.value === "1" && vkBasaltDisable?.value === "1") { + issues.push("vkBasalt has conflicting enable and disable assignments."); + } + + const zink = entries.get(WORKAROUND_DEFINITIONS.enableZink.spec[0]); + const glxVendor = entries.get("__GLX_VENDOR_LIBRARY_NAME"); + const galliumDriver = entries.get("GALLIUM_DRIVER"); + const hasLegacyZink = glxVendor !== undefined || galliumDriver !== undefined; + if (zink || hasLegacyZink) { + state.enableZink = zink?.value === WORKAROUND_DEFINITIONS.enableZink.spec[1]; + if (hasLegacyZink && ( + glxVendor?.value !== "mesa" || + zink?.value !== WORKAROUND_DEFINITIONS.enableZink.spec[1] || + galliumDriver?.value !== "zink" + )) { + issues.push("Zink workaround is only partially configured."); + } else if (!state.enableZink) { + issues.push("Zink workaround has an unsupported driver value."); + } + } + + return { state, issues }; +} + +export function applyWorkaroundState(options: string, state: WorkaroundState): string { + validateFrameRate(state.dxvkFrameRate); + const tokens = tokenize(options); + removeLegacyWrapperFromTokens(tokens); + rewriteDxvkFrameRate(tokens, state.dxvkFrameRate); + const keysToClear = new Set( + BOOLEAN_WORKAROUND_FIELDS.flatMap((field) => WORKAROUND_DEFINITIONS[field].clear), + ); + if (state.disableVkbasalt) keysToClear.add("ENABLE_VKBASALT"); + removeAllAssignments(tokens, keysToClear); + const specs = environmentSpecsForState(state); + if (specs.length > 0) { + ensureCommandToken(tokens); + insertEnvironmentSpecs(tokens, specs); + } + return serialize(tokens); +} + +export function applyWorkaroundChange(options: string, field: WorkaroundField, value: boolean | number): string { + const tokens = tokenize(options); + removeLegacyWrapperFromTokens(tokens); + + if (field === "dxvkFrameRate") { + if (typeof value !== "number") throw new Error("Base FPS Cap must be an integer from 0 to 60"); + validateFrameRate(value); + rewriteDxvkFrameRate(tokens, value); + return serialize(tokens); + } + + if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`); + const definition = WORKAROUND_DEFINITIONS[field]; + const keysToClear = new Set(definition.clear); + if (value && field === "disableVkbasalt") keysToClear.add("ENABLE_VKBASALT"); + removeAllAssignments(tokens, keysToClear); + if (value) { + ensureCommandToken(tokens); + insertEnvironmentSpecs(tokens, [definition.spec]); + } + return serialize(tokens); +} + +export function cleanupLegacyWrapper(options: string): string { + const tokens = tokenize(options); + removeLegacyWrapperFromTokens(tokens); + return serialize(tokens); +} diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts new file mode 100644 index 0000000..9c7b5eb --- /dev/null +++ b/src/utils/steamLaunchOptions.ts @@ -0,0 +1,211 @@ +// @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. +import { cleanupLegacyWrapper, isLegacyWrapperToken, normalizeLaunchOptions } from "./steamLaunchOptionParser.ts"; + +// @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. +export * from "./steamLaunchOptionParser.ts"; + +export interface SteamLaunchOptionsSnapshot { + appId: number; + nonSteam: boolean; + options: string; + details: SteamAppDetails; +} + +function validateAppId(appId: number): void { + if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error("Invalid Steam App ID"); +} + +function getSteamApps(): Partial | undefined { + return (globalThis as typeof globalThis & { + SteamClient?: { Apps?: Partial }; + }).SteamClient?.Apps; +} + +function snapshotFromDetails(appId: number, nonSteam: boolean, details: SteamAppDetails): SteamLaunchOptionsSnapshot { + if (nonSteam && isLegacyWrapperToken(details.strShortcutExe || "")) { + throw new Error("The shortcut Target still points to the legacy ~/lsfg wrapper; restore its original executable first"); + } + return { + appId, + nonSteam, + options: nonSteam ? details.strShortcutLaunchOptions || "" : details.strLaunchOptions || "", + details, + }; +} + +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} + +function registerSteamAppDetails( + appId: number, + onDetails: (details: SteamAppDetails) => boolean | void, +): () => void { + validateAppId(appId); + const apps = getSteamApps(); + const registerForAppDetails = apps?.RegisterForAppDetails; + if (!registerForAppDetails) throw new Error("Steam launch options API is unavailable"); + + let active = true; + let unregisterPending = false; + let registration: SteamAppDetailsRegistration | undefined; + const unsubscribe = () => { + active = false; + if (!registration) { + unregisterPending = true; + return; + } + try { + registration.unregister(); + } catch { + // Steam may invalidate registrations during a details refresh. + } + }; + + try { + registration = registerForAppDetails.call(apps, appId, (details) => { + if (!active) return; + if (onDetails(details || {}) === false && active) unsubscribe(); + }); + if (unregisterPending) { + try { + registration.unregister(); + } catch { + // The registration can be invalidated before a synchronous callback returns. + } + } + } catch (error) { + throw asError(error); + } + return unsubscribe; +} + +export async function readSteamLaunchOptions(appId: number, nonSteam: boolean): Promise { + return new Promise((resolve, reject) => { + let settled = false; + let timeout = 0; + let unsubscribe = () => {}; + const finish = (error?: unknown, details?: SteamAppDetails) => { + if (settled) return; + settled = true; + window.clearTimeout(timeout); + unsubscribe(); + if (error) { + reject(asError(error)); + return; + } + try { + resolve(snapshotFromDetails(appId, nonSteam, details || {})); + } catch (snapshotError) { + reject(asError(snapshotError)); + } + }; + + timeout = window.setTimeout(() => finish(new Error("Timed out reading Steam launch options")), 5000); + try { + unsubscribe = registerSteamAppDetails(appId, (details) => { + finish(undefined, details); + return false; + }); + } catch (error) { + finish(error); + } + }); +} + +export function subscribeSteamLaunchOptions( + appId: number, + nonSteam: boolean, + onSnapshot: (snapshot: SteamLaunchOptionsSnapshot) => void, + onError: (error: Error) => void, +): () => void { + return registerSteamAppDetails(appId, (details) => { + try { + onSnapshot(snapshotFromDetails(appId, nonSteam, details)); + } catch (error) { + onError(asError(error)); + } + }); +} + +async function setSteamLaunchOptions(appId: number, nonSteam: boolean, options: string): Promise { + const apps = getSteamApps(); + const setter = nonSteam ? apps?.SetShortcutLaunchOptions : apps?.SetAppLaunchOptions; + if (!setter) throw new Error(`Steam ${nonSteam ? "shortcut " : ""}launch options API is unavailable`); + await Promise.resolve(setter.call(apps, appId, options)); +} + +function delay(milliseconds: number): Promise { + return new Promise((resolve) => window.setTimeout(resolve, milliseconds)); +} + +async function waitForLaunchOptions( + appId: number, + nonSteam: boolean, + expected: string, +): Promise { + const deadline = Date.now() + 5000; + let lastError: Error | null = null; + while (Date.now() <= deadline) { + try { + const snapshot = await readSteamLaunchOptions(appId, nonSteam); + if (normalizeLaunchOptions(snapshot.options) === normalizeLaunchOptions(expected)) return snapshot; + } catch (error) { + lastError = asError(error); + } + if (Date.now() >= deadline) break; + await delay(100); + } + if (lastError) throw new Error(`Steam did not accept the launch options: ${lastError.message}`); + throw new Error("Steam did not accept the launch options before the readback timeout"); +} + +const operationQueues = new Map>(); + +function queueKey(appId: number, nonSteam: boolean): string { + return `${nonSteam ? "shortcut" : "app"}:${appId}`; +} + +function queueSteamAppOperation(appId: number, nonSteam: boolean, operation: () => Promise): Promise { + const key = queueKey(appId, nonSteam); + const previous = operationQueues.get(key) || Promise.resolve(); + const queued = previous.catch(() => undefined).then(operation); + let cleanup: Promise; + cleanup = queued.then( + () => { + if (operationQueues.get(key) === cleanup) operationQueues.delete(key); + }, + () => { + if (operationQueues.get(key) === cleanup) operationQueues.delete(key); + }, + ); + operationQueues.set(key, cleanup); + return queued; +} + +export function updateSteamLaunchOptions( + appId: number, + nonSteam: boolean, + transform: (options: string) => string, +): Promise { + return queueSteamAppOperation(appId, nonSteam, async () => { + const current = await readSteamLaunchOptions(appId, nonSteam); + const next = transform(current.options); + if (next === current.options) return current; + await setSteamLaunchOptions(appId, nonSteam, next); + return waitForLaunchOptions(appId, nonSteam, next); + }); +} + +export function cleanupSteamLaunchOptions( + appId: number, + nonSteam: boolean, +): Promise { + return queueSteamAppOperation(appId, nonSteam, async () => { + const current = await readSteamLaunchOptions(appId, nonSteam); + const next = cleanupLegacyWrapper(current.options); + if (next === current.options) return current; + await setSteamLaunchOptions(appId, nonSteam, next); + return waitForLaunchOptions(appId, nonSteam, next); + }); +} -- cgit v1.2.3 From bec26fe025c97c00d398e7a4fb571195706b9e76 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Tue, 8 Sep 2026 16:56:57 -0400 Subject: feat: more launch arg janitoring --- src/components/Content.tsx | 7 ++++--- src/hooks/useGameConfiguration.ts | 5 +++-- src/utils/steamLaunchOptionParser.ts | 28 ++++++++++++++++++++-------- src/utils/steamLaunchOptions.ts | 6 +++--- 4 files changed, 30 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index f1c8c11..1d7d2d1 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -80,8 +80,9 @@ export function Content() { const handleConfigChange = async ( fieldName: keyof ConfigurationData, value: boolean | number | string | string[], + cleanupLaunchOptions = false, ) => { - await save({ ...config, [fieldName]: value }); + await save({ ...config, [fieldName]: value }, cleanupLaunchOptions); }; const onInstall = () => { @@ -115,7 +116,7 @@ export function Content() { handleConfigChange(fieldName, value)} /> ), }] : []), @@ -128,7 +129,7 @@ export function Content() { targets={targets} runningGame={runningGame} onSelect={setSelectedAppId} - onConfigChange={handleConfigChange} + onConfigChange={(fieldName, value) => handleConfigChange(fieldName, value, true)} onEnable={enable} onEnableAll={enableAll} onReset={resetSelected} diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 7a572f9..46607cb 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -106,12 +106,13 @@ export function useGameConfiguration() { } }, [installedGames]); - const save = useCallback(async (next: ConfigurationData) => { + const save = useCallback(async (next: ConfigurationData, cleanupLaunchOptions = false) => { const selectedTarget = targets.find((target) => target.appid === selectedAppId); if (!selectedTarget?.name) return; + if (cleanupLaunchOptions && !(await cleanupTargetLaunchOptions(selectedTarget))) return; const result = await updateGameConfig(selectedAppId, selectedTarget.name, next); if (result.success) await load(); - }, [load, selectedAppId, targets]); + }, [cleanupTargetLaunchOptions, load, selectedAppId, targets]); const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); diff --git a/src/utils/steamLaunchOptionParser.ts b/src/utils/steamLaunchOptionParser.ts index 2fd7b67..5b8156c 100644 --- a/src/utils/steamLaunchOptionParser.ts +++ b/src/utils/steamLaunchOptionParser.ts @@ -34,6 +34,16 @@ interface WorkaroundDefinition { } const COMMAND_TOKEN = "%command%"; +const LEGACY_WRAPPER_TOKENS = new Set([ + "~/lsfg", + "/home/deck/lsfg", + "~/.local/bin/lsfg-vk-experimental", + "/home/deck/.local/bin/lsfg-vk-experimental", + "~/.local/bin/mako-run", + "/home/deck/.local/bin/mako-run", + "~/.local/bin/mako-launch", + "/home/deck/.local/bin/mako-launch", +]); const DXVK_FRAME_RATE_KEYS: readonly DxvkFrameRateKey[] = [ "dxvk.maxFrameRate", "dxgi.maxFrameRate", @@ -145,6 +155,7 @@ function tokenize(options: string): LaunchToken[] { } function serialize(tokens: readonly LaunchToken[]): string { + if (tokens.length === 1 && tokens[0].raw.toLowerCase() === COMMAND_TOKEN) return ""; return tokens.map((token) => token.raw).join(" "); } @@ -171,9 +182,6 @@ function leadingEnvironmentCount(tokens: readonly LaunchToken[]): number { } function effectivePrefixLimit(tokens: readonly LaunchToken[]): number { - // Only assignment words before the first command affect the launched game. - // Anything after a wrapper command is that command's argument, even when it - // happens to look like KEY=value. return leadingEnvironmentCount(tokens); } @@ -223,15 +231,15 @@ function ensureCommandToken(tokens: LaunchToken[]): void { export function isLegacyWrapperToken(value: string): boolean { const path = decodeToken(value); - return path === "~/lsfg" || path === "/home/deck/lsfg"; + return LEGACY_WRAPPER_TOKENS.has(path); } function removeLegacyWrapperFromTokens(tokens: LaunchToken[]): boolean { const commandIndex = findCommandIndex(tokens); const prefixEnd = commandIndex >= 0 ? commandIndex : tokens.length; - const wrapperIndex = leadingEnvironmentCount(tokens); - if (wrapperIndex >= prefixEnd || !isLegacyWrapperToken(tokens[wrapperIndex].raw)) return false; - tokens.splice(wrapperIndex, 1); + const retained = tokens.filter((token, index) => index >= prefixEnd || !isLegacyWrapperToken(token.raw)); + if (retained.length === tokens.length) return false; + tokens.splice(0, tokens.length, ...retained); return true; } @@ -482,8 +490,12 @@ export function applyWorkaroundChange(options: string, field: WorkaroundField, v return serialize(tokens); } -export function cleanupLegacyWrapper(options: string): string { +export function cleanupLegacyLaunchOptions(options: string): string { const tokens = tokenize(options); removeLegacyWrapperFromTokens(tokens); return serialize(tokens); } + +export function cleanupLegacyWrapper(options: string): string { + return cleanupLegacyLaunchOptions(options); +} diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 9c7b5eb..39125bd 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -1,5 +1,5 @@ // @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. -import { cleanupLegacyWrapper, isLegacyWrapperToken, normalizeLaunchOptions } from "./steamLaunchOptionParser.ts"; +import { cleanupLegacyLaunchOptions, isLegacyWrapperToken, normalizeLaunchOptions } from "./steamLaunchOptionParser.ts"; // @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. export * from "./steamLaunchOptionParser.ts"; @@ -23,7 +23,7 @@ function getSteamApps(): Partial | undefined { function snapshotFromDetails(appId: number, nonSteam: boolean, details: SteamAppDetails): SteamLaunchOptionsSnapshot { if (nonSteam && isLegacyWrapperToken(details.strShortcutExe || "")) { - throw new Error("The shortcut Target still points to the legacy ~/lsfg wrapper; restore its original executable first"); + throw new Error("The shortcut Target still points to a legacy frame-generation wrapper; restore its original executable first"); } return { appId, @@ -203,7 +203,7 @@ export function cleanupSteamLaunchOptions( ): Promise { return queueSteamAppOperation(appId, nonSteam, async () => { const current = await readSteamLaunchOptions(appId, nonSteam); - const next = cleanupLegacyWrapper(current.options); + const next = cleanupLegacyLaunchOptions(current.options); if (next === current.options) return current; await setSteamLaunchOptions(appId, nonSteam, next); return waitForLaunchOptions(appId, nonSteam, next); -- cgit v1.2.3 From 790132668c4421c68c32bdc8fc9792b0d6028f97 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Tue, 8 Sep 2026 22:18:13 -0400 Subject: I really dont want to but here you go little guy --- src/components/ConfigurationTab.tsx | 6 ++++ src/components/GameConfigurationSelector.tsx | 29 ++++++++++++++++-- src/components/ProfileDetails.tsx | 4 +-- src/components/WorkaroundsSection.tsx | 21 ++++++++----- src/hooks/useGameConfiguration.ts | 46 ++++++++++++++++++++++------ src/i18n/languages.json | 12 ++++++-- src/utils/steamLaunchOptionParser.ts | 40 +++++++++++++++++++----- src/utils/steamLaunchOptions.ts | 15 ++++++++- 8 files changed, 140 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 2bb0f26..c41c941 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -33,6 +33,7 @@ export function ConfigurationTab({ const [detailAppId, setDetailAppId] = useState(null); const [focusFpsMultiplier, setFocusFpsMultiplier] = useState(false); const [focusDetailAction, setFocusDetailAction] = useState<"enable" | "fps" | null>(null); + const [focusConfiguredToggle, setFocusConfiguredToggle] = useState(false); const enableRef = useRef(null); const promptedRunningAppId = useRef(null); const closeDetails = useCallback(() => { @@ -41,6 +42,7 @@ export function ConfigurationTab({ setDetailAppId(null); }, []); const clearFpsFocusRequest = useCallback(() => setFocusFpsMultiplier(false), []); + const clearConfiguredToggleFocusRequest = useCallback(() => setFocusConfiguredToggle(false), []); useEffect(() => { if (!focusDetailAction) return; @@ -77,12 +79,15 @@ export function ConfigurationTab({ targets={targets} runningGame={runningGame} onSelect={(appid) => { + setFocusConfiguredToggle(false); setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "fps" : "enable"); onSelect(appid); setDetailAppId(appid); }} onEnableAll={onEnableAll} onResetAll={onResetAll} + focusConfiguredToggle={focusConfiguredToggle} + onConfiguredToggleFocused={clearConfiguredToggleFocusRequest} /> ); @@ -96,6 +101,7 @@ export function ConfigurationTab({ if (selectedTarget?.configured) { promptedRunningAppId.current = detailAppId; await onReset(); + setFocusConfiguredToggle(true); closeDetails(); } else if (detailAppId && await onEnable(detailAppId)) { setFocusFpsMultiplier(true); diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 5f23b91..50b2cf8 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -1,5 +1,5 @@ import { ButtonItem, ConfirmModal, Field, PanelSectionRow, showModal } from "@decky/ui"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState, type RefObject } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { GameTarget } from "../hooks/useGameConfiguration"; @@ -9,6 +9,8 @@ interface Props { onSelect: (appid: string) => void; onEnableAll: () => Promise; onResetAll: () => Promise; + focusConfiguredToggle?: boolean; + onConfiguredToggleFocused?: () => void; } const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed-v3"; @@ -40,12 +42,14 @@ function GameGroup({ collapsed, onToggle, onSelect, + toggleRef, }: { title: string; games: GameTarget[]; collapsed: boolean; onToggle: () => void; onSelect: (appid: string) => void; + toggleRef?: RefObject; }) { if (games.length === 0) return null; @@ -56,6 +60,7 @@ function GameGroup({
@@ -86,7 +91,15 @@ function GameGroup({ ); } -export function GameConfigurationSelector({ targets, runningGame, onSelect, onEnableAll, onResetAll }: Props) { +export function GameConfigurationSelector({ + targets, + runningGame, + onSelect, + onEnableAll, + onResetAll, + focusConfiguredToggle = false, + onConfiguredToggleFocused, +}: Props) { const sortGames = (games: GameTarget[]) => [...games].sort((a, b) => { if (a.appid === runningGame?.appid) return -1; if (b.appid === runningGame?.appid) return 1; @@ -102,6 +115,17 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, onEn const [configuredNonSteamCollapsed, toggleConfiguredNonSteam] = usePersistentCollapsed(`${CONFIGURED_COLLAPSED_KEY}-non-steam`); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); const [availableNonSteamCollapsed, toggleAvailableNonSteam] = usePersistentCollapsed(`${AVAILABLE_COLLAPSED_KEY}-non-steam`); + const configuredToggleRef = useRef(null); + + useEffect(() => { + if (!focusConfiguredToggle) return; + const frame = requestAnimationFrame(() => { + configuredToggleRef.current?.querySelector('[role="button"], button')?.focus(); + onConfiguredToggleFocused?.(); + }); + return () => cancelAnimationFrame(frame); + }, [configuredGames.length, focusConfiguredToggle, onConfiguredToggleFocused]); + const confirmResetAll = () => { showModal( setExpanded((value) => !value)} > - {expanded ? : } Details + {expanded ? : } Game Details {expanded && ( - + )} diff --git a/src/components/WorkaroundsSection.tsx b/src/components/WorkaroundsSection.tsx index e990784..d783620 100644 --- a/src/components/WorkaroundsSection.tsx +++ b/src/components/WorkaroundsSection.tsx @@ -10,7 +10,7 @@ interface WorkaroundsSectionProps { nonSteam: boolean; } -const WORKAROUNDS_COLLAPSED_KEY = "lsfg-workarounds-collapsed"; +const WORKAROUNDS_COLLAPSED_KEY = "lsfg-workarounds-collapsed-v2"; type ToggleWorkaroundField = Exclude; const TOGGLE_ROWS: readonly { @@ -20,19 +20,26 @@ const TOGGLE_ROWS: readonly { descriptionKey: string; description: string; }[] = [ + { + field: "disableSteamdeckMode", + labelKey: "CONFIG_DISABLE_STEAMDECK_MODE", + label: "Disable Steam Deck Mode", + descriptionKey: "CONFIG_DISABLE_STEAMDECK_MODE_DESC", + description: "Disables a game-specific Steam Deck compatibility switch. Requires game restart to apply.", + }, { field: "disableGamescopeWsi", labelKey: "CONFIG_DISABLE_GAMESCOPE_WSI", label: "Disable Gamescope WSI", descriptionKey: "CONFIG_DISABLE_GAMESCOPE_WSI_DESC", - description: "Adds ENABLE_GAMESCOPE_WSI=0 without changing HDR. Requires game restart to apply.", + description: "Adds ENABLE_GAMESCOPE_WSI=0. Requires game restart to apply.", }, { - field: "disableSteamdeckMode", - labelKey: "CONFIG_DISABLE_STEAMDECK_MODE", - label: "Disable Steam Deck Mode", - descriptionKey: "CONFIG_DISABLE_STEAMDECK_MODE_DESC", - description: "Disables a game-specific Steam Deck compatibility switch. Requires game restart to apply.", + field: "disableHdr", + labelKey: "CONFIG_DISABLE_HDR", + label: "Disable HDR", + descriptionKey: "CONFIG_DISABLE_HDR_DESC", + description: "Prevents DXVK from exposing HDR to the game. Requires game restart to apply.", }, { field: "disableVkbasalt", diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 46607cb..6d1fe6a 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -3,7 +3,7 @@ import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; import { getGameConfigs, getInstalledGames, updateGameConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type GlobalConfig, type InstalledGame } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; -import { cleanupSteamLaunchOptions } from "../utils/steamLaunchOptions"; +import { applyWorkaroundState, cleanupLegacySteamLaunchOptions, cleanupSteamLaunchOptions, getDefaultWorkaroundState, updateSteamLaunchOptions } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; export interface GameTarget extends InstalledGame { configured: boolean; } @@ -98,7 +98,7 @@ export function useGameConfiguration() { const cleanupTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; try { - await cleanupSteamLaunchOptions(Number(target.appid), target.nonSteam); + await cleanupLegacySteamLaunchOptions(Number(target.appid), target.nonSteam); return true; } catch (error) { showErrorToast("Could not update Steam launch options", error instanceof Error ? error.message : String(error)); @@ -106,6 +106,32 @@ export function useGameConfiguration() { } }, [installedGames]); + const removeTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { + if (!installedGames.some((game) => game.appid === target.appid)) return true; + try { + await cleanupSteamLaunchOptions(Number(target.appid), target.nonSteam); + return true; + } catch (error) { + showErrorToast("Could not clean up Steam launch options", error instanceof Error ? error.message : String(error)); + return false; + } + }, [installedGames]); + + const initializeTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { + if (!installedGames.some((game) => game.appid === target.appid)) return true; + try { + await updateSteamLaunchOptions( + Number(target.appid), + target.nonSteam, + (options) => applyWorkaroundState(options, getDefaultWorkaroundState()), + ); + return true; + } catch (error) { + showErrorToast("Could not initialize Steam launch options", error instanceof Error ? error.message : String(error)); + return false; + } + }, [installedGames]); + const save = useCallback(async (next: ConfigurationData, cleanupLaunchOptions = false) => { const selectedTarget = targets.find((target) => target.appid === selectedAppId); if (!selectedTarget?.name) return; @@ -117,16 +143,16 @@ export function useGameConfiguration() { const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; - if (!(await cleanupTargetLaunchOptions(target))) return false; + if (!(await initializeTargetLaunchOptions(target))) return false; const result = await updateGameConfig(appid, target.name, template); if (result.success) await load(); return result.success; - }, [cleanupTargetLaunchOptions, load, targets, template]); + }, [initializeTargetLaunchOptions, load, targets, template]); const enableAll = useCallback(async (): Promise => { const available = targets.filter((target) => !target.configured && target.name); if (available.length === 0) return; for (const target of available) { - if (!(await cleanupTargetLaunchOptions(target))) return; + if (!(await initializeTargetLaunchOptions(target))) return; const result = await updateGameConfig(target.appid, target.name, template); if (!result.success) { showErrorToast("Could not enable all games", result.error || "A game profile could not be created"); @@ -134,12 +160,12 @@ export function useGameConfiguration() { } } await load(); - }, [cleanupTargetLaunchOptions, load, targets, template]); + }, [initializeTargetLaunchOptions, load, targets, template]); const resetSelected = useCallback(async () => { if (selectedAppId) { const selectedTarget = targets.find((target) => target.appid === selectedAppId); - if (selectedTarget && !(await cleanupTargetLaunchOptions(selectedTarget))) return; + if (selectedTarget && !(await removeTargetLaunchOptions(selectedTarget))) return; const result = await resetGameConfig(selectedAppId); if (result.success) { setRunningGame((current) => current?.appid === selectedAppId ? { ...current, configured: false } : current); @@ -147,10 +173,10 @@ export function useGameConfiguration() { await load(); } } - }, [cleanupTargetLaunchOptions, load, selectedAppId, targets]); + }, [load, removeTargetLaunchOptions, selectedAppId, targets]); const resetAll = useCallback(async () => { for (const target of targets.filter((item) => item.configured)) { - if (!(await cleanupTargetLaunchOptions(target))) return; + if (!(await removeTargetLaunchOptions(target))) return; } const result = await resetAllGameConfigs(); if (result.success) { @@ -158,7 +184,7 @@ export function useGameConfiguration() { setSelectedAppId(""); await load(); } - }, [cleanupTargetLaunchOptions, load, targets]); + }, [load, removeTargetLaunchOptions, targets]); return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, resetSelected, resetAll, reload: load }; } diff --git a/src/i18n/languages.json b/src/i18n/languages.json index 3f1992c..7e5676b 100644 --- a/src/i18n/languages.json +++ b/src/i18n/languages.json @@ -22,7 +22,9 @@ "CONFIG_ENABLE_WSI": "WSIを有効化", "CONFIG_ENABLE_WSI_DESC": "Gamescope WSIレイヤーを再有効化します。ゲームの再起動が必要。", "CONFIG_DISABLE_GAMESCOPE_WSI": "Gamescope WSIを無効化", - "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "HDRを変更せずENABLE_GAMESCOPE_WSI=0を追加します。ゲームの再起動が必要です。", + "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "ENABLE_GAMESCOPE_WSI=0を追加します。ゲームの再起動が必要です。", + "CONFIG_DISABLE_HDR": "HDRを無効化", + "CONFIG_DISABLE_HDR_DESC": "DXVKがゲームにHDRを公開しないようにします。ゲームの再起動が必要です。", "CONFIG_DISABLE_STEAMDECK_MODE": "Steam Deckモードを無効化", "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "ゲーム固有のSteam Deck互換スイッチを無効化します。ゲームの再起動が必要です。", "CONFIG_DISABLE_VKBASALT": "vkBasaltを無効化", @@ -109,7 +111,9 @@ "CONFIG_ENABLE_WSI": "WSI 활성화", "CONFIG_ENABLE_WSI_DESC": "Gamescope WSI 레이어를 다시 활성화합니다. 게임 재시작 필요.", "CONFIG_DISABLE_GAMESCOPE_WSI": "Gamescope WSI 비활성화", - "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "HDR을 변경하지 않고 ENABLE_GAMESCOPE_WSI=0을 추가합니다. 게임 재시작 필요.", + "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "ENABLE_GAMESCOPE_WSI=0을 추가합니다. 게임 재시작 필요.", + "CONFIG_DISABLE_HDR": "HDR 비활성화", + "CONFIG_DISABLE_HDR_DESC": "DXVK가 게임에 HDR을 노출하지 않도록 합니다. 게임 재시작 필요.", "CONFIG_DISABLE_STEAMDECK_MODE": "Steam Deck 모드 비활성화", "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "게임별 Steam Deck 호환 스위치를 비활성화합니다. 게임 재시작 필요.", "CONFIG_DISABLE_VKBASALT": "vkBasalt 비활성화", @@ -224,7 +228,9 @@ "CONFIG_ENABLE_WSI": "Enable WSI", "CONFIG_ENABLE_WSI_DESC": "Re-Enable Gamescope WSI Layer. Requires game restart to apply.", "CONFIG_DISABLE_GAMESCOPE_WSI": "Disable Gamescope WSI", - "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "Adds ENABLE_GAMESCOPE_WSI=0 without changing HDR. Requires game restart to apply.", + "CONFIG_DISABLE_GAMESCOPE_WSI_DESC": "Adds ENABLE_GAMESCOPE_WSI=0. Requires game restart to apply.", + "CONFIG_DISABLE_HDR": "Disable HDR", + "CONFIG_DISABLE_HDR_DESC": "Prevents DXVK from exposing HDR to the game. Requires game restart to apply.", "CONFIG_DISABLE_STEAMDECK_MODE": "Disable Steam Deck Mode", "CONFIG_DISABLE_STEAMDECK_MODE_DESC": "Disables a game-specific Steam Deck compatibility switch. Requires game restart to apply.", "CONFIG_DISABLE_VKBASALT": "Disable vkBasalt", diff --git a/src/utils/steamLaunchOptionParser.ts b/src/utils/steamLaunchOptionParser.ts index 5b8156c..9449b33 100644 --- a/src/utils/steamLaunchOptionParser.ts +++ b/src/utils/steamLaunchOptionParser.ts @@ -1,6 +1,7 @@ export interface WorkaroundState { dxvkFrameRate: number; disableGamescopeWsi: boolean; + disableHdr: boolean; disableSteamdeckMode: boolean; disableVkbasalt: boolean; enableZink: boolean; @@ -41,8 +42,10 @@ const LEGACY_WRAPPER_TOKENS = new Set([ "/home/deck/.local/bin/lsfg-vk-experimental", "~/.local/bin/mako-run", "/home/deck/.local/bin/mako-run", + "mako-run", "~/.local/bin/mako-launch", "/home/deck/.local/bin/mako-launch", + "mako-launch", ]); const DXVK_FRAME_RATE_KEYS: readonly DxvkFrameRateKey[] = [ "dxvk.maxFrameRate", @@ -53,7 +56,12 @@ const DXVK_MANAGED_KEYS = new Set(["DXVK_CONFIG", "DXVK_FRAME_RATE"]); const WORKAROUND_DEFINITIONS = { disableGamescopeWsi: { spec: ["ENABLE_GAMESCOPE_WSI", "0"], - clear: ["DISABLE_GAMESCOPE_WSI", "ENABLE_GAMESCOPE_WSI", "DXVK_HDR"], + clear: ["DISABLE_GAMESCOPE_WSI", "ENABLE_GAMESCOPE_WSI"], + }, + disableHdr: { + spec: ["DXVK_HDR", "0"], + clear: ["DXVK_HDR"], + label: "Disable HDR", }, disableSteamdeckMode: { spec: ["SteamDeck", "0"], @@ -72,24 +80,34 @@ const WORKAROUND_DEFINITIONS = { } as const satisfies Record; const BOOLEAN_WORKAROUND_FIELDS: readonly BooleanWorkaroundField[] = [ "disableGamescopeWsi", + "disableHdr", "disableSteamdeckMode", "disableVkbasalt", "enableZink", ]; const WSI_DISABLE_KEY = "DISABLE_GAMESCOPE_WSI"; const WSI_ENABLE_KEY = "ENABLE_GAMESCOPE_WSI"; +const WORKAROUND_ENV_KEYS = new Set( + BOOLEAN_WORKAROUND_FIELDS.flatMap((field) => WORKAROUND_DEFINITIONS[field].clear), +); const MANAGED_ENV_KEYS = new Set([ ...DXVK_MANAGED_KEYS, - ...BOOLEAN_WORKAROUND_FIELDS.flatMap((field) => WORKAROUND_DEFINITIONS[field].clear), + ...WORKAROUND_ENV_KEYS, ]); -const DEFAULT_WORKAROUND_STATE: WorkaroundState = { +const EMPTY_WORKAROUND_STATE: WorkaroundState = { dxvkFrameRate: 0, disableGamescopeWsi: false, + disableHdr: false, disableSteamdeckMode: false, disableVkbasalt: false, enableZink: false, }; +const DEFAULT_WORKAROUND_STATE: WorkaroundState = { + ...EMPTY_WORKAROUND_STATE, + disableGamescopeWsi: true, + disableHdr: true, +}; export function getDefaultWorkaroundState(): WorkaroundState { return { ...DEFAULT_WORKAROUND_STATE }; @@ -117,8 +135,6 @@ function decodeToken(raw: string): string { return value; } -// Steam stores one shell-like line. Keep each token's raw spelling beside its -// decoded value so managed edits leave unrelated quoting and arguments alone. function tokenize(options: string): LaunchToken[] { const tokens: LaunchToken[] = []; let start = -1; @@ -358,7 +374,7 @@ function readBoolean( export function parseWorkaroundOptions(options: string): ParsedWorkaroundOptions { const tokens = tokenize(options); const entries = effectiveEnvironmentEntries(tokens); - const state = getDefaultWorkaroundState(); + const state = { ...EMPTY_WORKAROUND_STATE }; const issues: string[] = []; for (const [key, entry] of entries) { @@ -418,7 +434,7 @@ export function parseWorkaroundOptions(options: string): ParsedWorkaroundOptions state.disableGamescopeWsi = wsiSignals.some(Boolean); } - for (const field of ["disableSteamdeckMode", "disableVkbasalt"] as const) { + for (const field of ["disableHdr", "disableSteamdeckMode", "disableVkbasalt"] as const) { const { spec, label } = WORKAROUND_DEFINITIONS[field]; state[field] = readBoolean(entries, spec[0], label || field, spec[1], issues); } @@ -455,7 +471,7 @@ export function applyWorkaroundState(options: string, state: WorkaroundState): s removeLegacyWrapperFromTokens(tokens); rewriteDxvkFrameRate(tokens, state.dxvkFrameRate); const keysToClear = new Set( - BOOLEAN_WORKAROUND_FIELDS.flatMap((field) => WORKAROUND_DEFINITIONS[field].clear), + WORKAROUND_ENV_KEYS, ); if (state.disableVkbasalt) keysToClear.add("ENABLE_VKBASALT"); removeAllAssignments(tokens, keysToClear); @@ -496,6 +512,14 @@ export function cleanupLegacyLaunchOptions(options: string): string { return serialize(tokens); } +export function cleanupPluginLaunchOptions(options: string): string { + const tokens = tokenize(options); + removeLegacyWrapperFromTokens(tokens); + rewriteDxvkFrameRate(tokens, 0); + removeAllAssignments(tokens, WORKAROUND_ENV_KEYS); + return serialize(tokens); +} + export function cleanupLegacyWrapper(options: string): string { return cleanupLegacyLaunchOptions(options); } diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 39125bd..82ff94b 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -1,5 +1,5 @@ // @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. -import { cleanupLegacyLaunchOptions, isLegacyWrapperToken, normalizeLaunchOptions } from "./steamLaunchOptionParser.ts"; +import { cleanupLegacyLaunchOptions, cleanupPluginLaunchOptions, isLegacyWrapperToken, normalizeLaunchOptions } from "./steamLaunchOptionParser.ts"; // @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. export * from "./steamLaunchOptionParser.ts"; @@ -200,6 +200,19 @@ export function updateSteamLaunchOptions( export function cleanupSteamLaunchOptions( appId: number, nonSteam: boolean, +): Promise { + return queueSteamAppOperation(appId, nonSteam, async () => { + const current = await readSteamLaunchOptions(appId, nonSteam); + const next = cleanupPluginLaunchOptions(current.options); + if (next === current.options) return current; + await setSteamLaunchOptions(appId, nonSteam, next); + return waitForLaunchOptions(appId, nonSteam, next); + }); +} + +export function cleanupLegacySteamLaunchOptions( + appId: number, + nonSteam: boolean, ): Promise { return queueSteamAppOperation(appId, nonSteam, async () => { const current = await readSteamLaunchOptions(appId, nonSteam); -- cgit v1.2.3 From 1b932fd69c3dba925e0cbf027e05508b2daf5e8c Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Wed, 9 Sep 2026 01:01:42 -0400 Subject: add back launcher script and correct pathing --- src/api/lsfgApi.ts | 29 ++ src/components/ConfigurationTab.tsx | 3 + src/components/Content.tsx | 2 + src/components/GameConfigurationControls.tsx | 8 +- src/components/WorkaroundsSection.tsx | 41 ++- src/hooks/useGameConfiguration.ts | 158 ++++++-- src/hooks/usePerAppWorkarounds.ts | 234 +++++++++--- src/types.d.ts | 1 + src/utils/steamLaunchOptionParser.ts | 525 --------------------------- src/utils/steamLaunchOptions.ts | 472 +++++++++++++++++++++--- 10 files changed, 795 insertions(+), 678 deletions(-) delete mode 100644 src/utils/steamLaunchOptionParser.ts (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 8eaad98..087228c 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -60,6 +60,27 @@ export interface GameConfigResult extends ConfigUpdateResult { config?: LsfgConfig; } +export interface WorkaroundState { + dxvkFrameRate: number; + disableGamescopeWsi: boolean; + disableHdr: boolean; + disableSteamdeckMode: boolean; + disableVkbasalt: boolean; + enableZink: boolean; +} + +export interface WorkaroundStateResult { + success: boolean; + message?: string; + error?: string; + appid?: string; + state?: WorkaroundState | null; + wrapper_path?: string; + wrapper_owned?: boolean; + shortcut_exe?: string | null; + command_token_added?: boolean; +} + export interface FileContentResult { success: boolean; content?: string; @@ -120,3 +141,11 @@ export const getInstalledGames = callable<[], InstalledGamesResult>("get_install 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"); +export const getWorkaroundState = callable<[string], WorkaroundStateResult>("get_workaround_state"); +export const setWorkaroundState = callable<[ + string, + WorkaroundState, + string | null | undefined, + boolean, +], WorkaroundStateResult>("set_workaround_state"); +export const removeWorkaroundState = callable<[string], WorkaroundStateResult>("remove_workaround_state"); diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index c41c941..62a971b 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -15,6 +15,7 @@ interface ConfigurationTabProps { onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; onEnable: (appid: string) => Promise; onEnableAll: () => Promise; + onRepair: (appid: string) => Promise; onReset: () => Promise; onResetAll: () => Promise; } @@ -27,6 +28,7 @@ export function ConfigurationTab({ onConfigChange, onEnable, onEnableAll, + onRepair, onReset, onResetAll, }: ConfigurationTabProps) { @@ -157,6 +159,7 @@ export function ConfigurationTab({ onFpsMultiplierFocused={clearFpsFocusRequest} showWorkarounds workaroundTarget={selectedTarget || undefined} + onRepairWorkaround={selectedTarget ? () => onRepair(selectedTarget.appid) : undefined} /> )} {selectedTarget?.configured && ( diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 1d7d2d1..59dc514 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -39,6 +39,7 @@ export function Content() { save, enable, enableAll, + repair, resetSelected, resetAll, reload, @@ -132,6 +133,7 @@ export function Content() { onConfigChange={(fieldName, value) => handleConfigChange(fieldName, value, true)} onEnable={enable} onEnableAll={enableAll} + onRepair={repair} onReset={resetSelected} onResetAll={resetAll} /> diff --git a/src/components/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx index 58ccd02..7025f78 100644 --- a/src/components/GameConfigurationControls.tsx +++ b/src/components/GameConfigurationControls.tsx @@ -11,6 +11,7 @@ interface Props { onFpsMultiplierFocused?: () => void; showWorkarounds?: boolean; workaroundTarget?: Pick; + onRepairWorkaround?: () => Promise; } export function GameConfigurationControls({ @@ -20,6 +21,7 @@ export function GameConfigurationControls({ onFpsMultiplierFocused, showWorkarounds = false, workaroundTarget, + onRepairWorkaround, }: Props) { return ( <> @@ -31,7 +33,11 @@ export function GameConfigurationControls({ /> {showWorkarounds && workaroundTarget && ( - + )} ); diff --git a/src/components/WorkaroundsSection.tsx b/src/components/WorkaroundsSection.tsx index d783620..dbdd6a3 100644 --- a/src/components/WorkaroundsSection.tsx +++ b/src/components/WorkaroundsSection.tsx @@ -3,11 +3,12 @@ import { useEffect, useState } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; import { usePerAppWorkarounds } from "../hooks/usePerAppWorkarounds"; import t from "../i18n/i18n"; -import type { WorkaroundField } from "../utils/steamLaunchOptions"; +import type { WorkaroundField } from "../hooks/usePerAppWorkarounds"; interface WorkaroundsSectionProps { appId: string; nonSteam: boolean; + onRepair?: () => Promise; } const WORKAROUNDS_COLLAPSED_KEY = "lsfg-workarounds-collapsed-v2"; @@ -78,18 +79,28 @@ function usePersistentCollapsed() { return [collapsed, () => setCollapsed((value) => !value)] as const; } -export function WorkaroundsSection({ appId, nonSteam }: WorkaroundsSectionProps) { +export function WorkaroundsSection({ appId, nonSteam, onRepair }: WorkaroundsSectionProps) { const [collapsed, toggleCollapsed] = usePersistentCollapsed(); const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam); - const state = snapshot?.parsed.state; - const issues = snapshot?.parsed.issues || []; - const controlsDisabled = status !== "ready" || state === undefined; + const [repairing, setRepairing] = useState(false); + const state = snapshot?.state; + const controlsDisabled = status !== "ready" || state === undefined || snapshot?.wrapperOwned !== true || snapshot.integrationInstalled !== true; const [fpsValue, setFpsValue] = useState(null); const effectiveFpsValue = fpsValue ?? state?.dxvkFrameRate ?? 0; const fpsLabel = effectiveFpsValue > 0 ? `${effectiveFpsValue} FPS` : t("CONFIG_BASE_FPS_CAP_OFF", "Off"); + const handleRepair = async () => { + if (!onRepair || repairing) return; + setRepairing(true); + try { + if (await onRepair()) await refresh(); + } finally { + setRepairing(false); + } + }; + useEffect(() => { setFpsValue(state?.dxvkFrameRate ?? null); }, [state?.dxvkFrameRate, status]); @@ -155,13 +166,19 @@ export function WorkaroundsSection({ appId, nonSteam }: WorkaroundsSectionProps) )} - {status === "ready" && issues.length > 0 && ( - - - + {status === "ready" && snapshot && (!snapshot.wrapperOwned || !snapshot.integrationInstalled) && ( + <> + + + + {onRepair && ( + + void handleRepair()}> + {repairing ? "Reinstalling..." : "Reinstall wrapper"} + + + )} + )} diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 6d1fe6a..c66596a 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,9 +1,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; -import { getGameConfigs, getInstalledGames, updateGameConfig, resetGameConfig, resetAllGameConfigs, type GameConfigEntry, type GlobalConfig, type InstalledGame } from "../api/lsfgApi"; +import { getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; -import { applyWorkaroundState, cleanupLegacySteamLaunchOptions, cleanupSteamLaunchOptions, getDefaultWorkaroundState, updateSteamLaunchOptions } from "../utils/steamLaunchOptions"; +import { cleanupLegacySteamLaunchOptions, getDefaultWrapperPath, hasWrapperLaunchIntegration, installWrapperIntegration, isLegacyWrapperToken, readSteamLaunchOptions, removeWrapperIntegration } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; export interface GameTarget extends InstalledGame { configured: boolean; } @@ -32,6 +32,19 @@ function mergeInstalledGames(backendGames: InstalledGame[], shortcutGames: Insta return Array.from(games.values()); } +const DEFAULT_WORKAROUND_STATE: WorkaroundState = { + dxvkFrameRate: 0, + disableGamescopeWsi: true, + disableHdr: true, + disableSteamdeckMode: false, + disableVkbasalt: false, + enableZink: false, +}; + +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); +} + export function useGameConfiguration() { const [games, setGames] = useState([]); const [globalConfig, setGlobalConfig] = useState({ dll: "", no_fp16: false }); @@ -95,39 +108,107 @@ export function useGameConfiguration() { const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); const config = games.find((game) => game.appid === selectedAppId)?.config || template; - const cleanupTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { + const ensureTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; + const appId = Number(target.appid); try { - await cleanupLegacySteamLaunchOptions(Number(target.appid), target.nonSteam); - return true; - } catch (error) { - showErrorToast("Could not update Steam launch options", error instanceof Error ? error.message : String(error)); - return false; - } - }, [installedGames]); + const existing = await getWorkaroundState(target.appid); + if (!existing.success) throw new Error(existing.error || "Could not read workaround state"); + const current = await readSteamLaunchOptions(appId, target.nonSteam); + const wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); + const oldState = existing.state; + const oldShortcutExe = existing.shortcut_exe || undefined; + const oldCommandTokenAdded = existing.command_token_added === true; + if (target.nonSteam && oldState && current.target === wrapperPath && !oldShortcutExe) { + throw new Error("Managed shortcut Target has no saved original executable"); + } + if (target.nonSteam && oldState && current.target !== wrapperPath && current.target !== oldShortcutExe) { + throw new Error("Shortcut Target changed externally; refusing to replace it"); + } + if (target.nonSteam && !oldState && current.target === wrapperPath) { + throw new Error("Shortcut Target is already the managed wrapper but its original Target is unknown"); + } + const state = oldState || { ...DEFAULT_WORKAROUND_STATE }; + const originalExecutable = target.nonSteam ? (oldShortcutExe || current.target) : undefined; + const initialIntegration = target.nonSteam + ? current.target === wrapperPath + : hasWrapperLaunchIntegration(current.options, wrapperPath); + const initialStateResult = await setWorkaroundState( + target.appid, + state, + originalExecutable || null, + oldCommandTokenAdded, + ); + if (!initialStateResult.success) throw new Error(initialStateResult.error || "Could not create workaround state"); - const removeTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { - if (!installedGames.some((game) => game.appid === target.appid)) return true; - try { - await cleanupSteamLaunchOptions(Number(target.appid), target.nonSteam); - return true; + let integration: Awaited> | null = null; + try { + integration = await installWrapperIntegration(appId, target.nonSteam, wrapperPath, oldCommandTokenAdded); + const finalStateResult = await setWorkaroundState( + target.appid, + state, + target.nonSteam ? (integration.originalExecutable || originalExecutable || null) : null, + integration.commandTokenAdded, + ); + if (!finalStateResult.success) throw new Error(finalStateResult.error || "Could not finalize workaround state"); + return true; + } catch (error) { + let rollbackSucceeded = true; + if (!initialIntegration && integration) { + try { + await removeWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + target.nonSteam ? (integration?.originalExecutable || originalExecutable) : undefined, + integration?.commandTokenAdded ?? oldCommandTokenAdded, + ); + } catch (rollbackError) { + showErrorToast("Workaround rollback failed", asError(rollbackError).message); + rollbackSucceeded = false; + } + } + if (rollbackSucceeded) { + const restored = oldState + ? await setWorkaroundState(target.appid, oldState, oldShortcutExe || null, oldCommandTokenAdded) + : await removeWorkaroundState(target.appid); + if (!restored.success) throw new Error(restored.error || "Could not roll back workaround state"); + } + throw error; + } } catch (error) { - showErrorToast("Could not clean up Steam launch options", error instanceof Error ? error.message : String(error)); + showErrorToast("Could not initialize workarounds", asError(error).message); return false; } }, [installedGames]); - const initializeTargetLaunchOptions = useCallback(async (target: GameTarget): Promise => { + const removeTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; + const appId = Number(target.appid); try { - await updateSteamLaunchOptions( - Number(target.appid), - target.nonSteam, - (options) => applyWorkaroundState(options, getDefaultWorkaroundState()), - ); + const existing = await getWorkaroundState(target.appid); + if (!existing.success) throw new Error(existing.error || "Could not read workaround state"); + const wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); + if (existing.state) { + await removeWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + existing.shortcut_exe || undefined, + existing.command_token_added === true, + ); + } else { + const current = await readSteamLaunchOptions(appId, target.nonSteam); + if (target.nonSteam && (current.target === wrapperPath || isLegacyWrapperToken(current.target))) { + throw new Error("Shortcut Target is a frame-generation wrapper but its original Target is unknown"); + } + await cleanupLegacySteamLaunchOptions(appId, target.nonSteam, wrapperPath); + } + const removed = await removeWorkaroundState(target.appid); + if (!removed.success) throw new Error(removed.error || "Could not remove workaround state"); return true; } catch (error) { - showErrorToast("Could not initialize Steam launch options", error instanceof Error ? error.message : String(error)); + showErrorToast("Could not clean up game workarounds", asError(error).message); return false; } }, [installedGames]); @@ -135,37 +216,46 @@ export function useGameConfiguration() { const save = useCallback(async (next: ConfigurationData, cleanupLaunchOptions = false) => { const selectedTarget = targets.find((target) => target.appid === selectedAppId); if (!selectedTarget?.name) return; - if (cleanupLaunchOptions && !(await cleanupTargetLaunchOptions(selectedTarget))) return; + // The profile owns its wrapper integration. Keep this check on every + // configuration save so an external edit is detected before the profile + // is changed; toggles update the sidecar only. + if (cleanupLaunchOptions && !(await ensureTargetWorkarounds(selectedTarget))) return; const result = await updateGameConfig(selectedAppId, selectedTarget.name, next); if (result.success) await load(); - }, [cleanupTargetLaunchOptions, load, selectedAppId, targets]); + }, [ensureTargetWorkarounds, load, selectedAppId, targets]); const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; - if (!(await initializeTargetLaunchOptions(target))) return false; + if (!(await ensureTargetWorkarounds(target))) return false; const result = await updateGameConfig(appid, target.name, template); if (result.success) await load(); + else await removeTargetWorkarounds(target); return result.success; - }, [initializeTargetLaunchOptions, load, targets, template]); + }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); const enableAll = useCallback(async (): Promise => { const available = targets.filter((target) => !target.configured && target.name); if (available.length === 0) return; for (const target of available) { - if (!(await initializeTargetLaunchOptions(target))) return; + if (!(await ensureTargetWorkarounds(target))) return; const result = await updateGameConfig(target.appid, target.name, template); if (!result.success) { showErrorToast("Could not enable all games", result.error || "A game profile could not be created"); + await removeTargetWorkarounds(target); return; } } await load(); - }, [initializeTargetLaunchOptions, load, targets, template]); + }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + const repair = useCallback(async (appid: string): Promise => { + const target = targets.find((item) => item.appid === appid); + return target ? ensureTargetWorkarounds(target) : false; + }, [ensureTargetWorkarounds, targets]); const resetSelected = useCallback(async () => { if (selectedAppId) { const selectedTarget = targets.find((target) => target.appid === selectedAppId); - if (selectedTarget && !(await removeTargetLaunchOptions(selectedTarget))) return; + if (selectedTarget && !(await removeTargetWorkarounds(selectedTarget))) return; const result = await resetGameConfig(selectedAppId); if (result.success) { setRunningGame((current) => current?.appid === selectedAppId ? { ...current, configured: false } : current); @@ -173,10 +263,10 @@ export function useGameConfiguration() { await load(); } } - }, [load, removeTargetLaunchOptions, selectedAppId, targets]); + }, [load, removeTargetWorkarounds, selectedAppId, targets]); const resetAll = useCallback(async () => { for (const target of targets.filter((item) => item.configured)) { - if (!(await removeTargetLaunchOptions(target))) return; + if (!(await removeTargetWorkarounds(target))) return; } const result = await resetAllGameConfigs(); if (result.success) { @@ -184,7 +274,7 @@ export function useGameConfiguration() { setSelectedAppId(""); await load(); } - }, [load, removeTargetLaunchOptions, targets]); + }, [load, removeTargetWorkarounds, targets]); - return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, resetSelected, resetAll, reload: load }; + return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, repair, resetSelected, resetAll, reload: load }; } diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index a937780..9e283db 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -1,29 +1,50 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { - applyWorkaroundChange, - parseWorkaroundOptions, + getWorkaroundState, + removeWorkaroundState, + setWorkaroundState, + type WorkaroundState, +} from "../api/lsfgApi"; +import { + getDefaultWrapperPath, + hasWrapperLaunchIntegration, + installWrapperIntegration, + isLegacyWrapperToken, readSteamLaunchOptions, + removeWrapperIntegration, subscribeSteamLaunchOptions, - updateSteamLaunchOptions, - type ParsedWorkaroundOptions, type SteamLaunchOptionsSnapshot, - type WorkaroundField, } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; +export type WorkaroundField = keyof WorkaroundState; export type WorkaroundLoadStatus = "loading" | "ready" | "error"; const SLIDER_DEBOUNCE_MS = 250; +const DEFAULT_WORKAROUND_STATE: WorkaroundState = { + dxvkFrameRate: 0, + disableGamescopeWsi: true, + disableHdr: true, + disableSteamdeckMode: false, + disableVkbasalt: false, + enableZink: false, +}; + interface PendingSliderUpdate { timer: number; value: number; waiters: Array<(success: boolean) => void>; } -interface WorkaroundSnapshot { +export interface WorkaroundSnapshot { steam: SteamLaunchOptionsSnapshot; - parsed: ParsedWorkaroundOptions; + state: WorkaroundState; + wrapperPath: string; + wrapperOwned: boolean; + integrationInstalled: boolean; + commandTokenAdded: boolean; + shortcutExe?: string | null; } interface PerAppWorkarounds { @@ -38,8 +59,84 @@ function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } -function makeSnapshot(steam: SteamLaunchOptionsSnapshot): WorkaroundSnapshot { - return { steam, parsed: parseWorkaroundOptions(steam.options) }; +function integrationIsInstalled( + steam: SteamLaunchOptionsSnapshot, + nonSteam: boolean, + wrapperPath: string, +): boolean { + return nonSteam ? steam.target === wrapperPath : hasWrapperLaunchIntegration(steam.options, wrapperPath); +} + +function makeSnapshot( + steam: SteamLaunchOptionsSnapshot, + result: Awaited>, + nonSteam: boolean, +): WorkaroundSnapshot { + if (!result.state) throw new Error("Workaround state is not initialized for this profile"); + const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); + if (nonSteam && steam.target === wrapperPath && !result.shortcut_exe) { + throw new Error("Managed shortcut Target has no saved original executable"); + } + return { + steam, + state: result.state, + wrapperPath, + wrapperOwned: result.wrapper_owned === true, + integrationInstalled: integrationIsInstalled(steam, nonSteam, wrapperPath), + commandTokenAdded: result.command_token_added === true, + shortcutExe: result.shortcut_exe, + }; +} + +async function adoptWorkaroundState( + appId: string, + nonSteam: boolean, + steam: SteamLaunchOptionsSnapshot, + wrapperPath: string, +): Promise { + if (nonSteam && (!steam.target || steam.target === wrapperPath || isLegacyWrapperToken(steam.target))) { + throw new Error("Shortcut Target is a wrapper but its original Target is unknown"); + } + const originalExecutable = nonSteam ? steam.target : null; + const initial = await setWorkaroundState(appId, DEFAULT_WORKAROUND_STATE, originalExecutable, false); + if (!initial.success) throw new Error(initial.error || "Could not create workaround state"); + let integration: Awaited> | null = null; + try { + integration = await installWrapperIntegration( + Number(appId), + nonSteam, + wrapperPath, + ); + const finalized = await setWorkaroundState( + appId, + DEFAULT_WORKAROUND_STATE, + nonSteam ? (integration.originalExecutable || originalExecutable) : null, + integration.commandTokenAdded, + ); + if (!finalized.success) throw new Error(finalized.error || "Could not finalize workaround state"); + return makeSnapshot(integration.snapshot, finalized, nonSteam); + } catch (error) { + let rollbackSucceeded = true; + if (integration) { + try { + await removeWrapperIntegration( + Number(appId), + nonSteam, + wrapperPath, + nonSteam ? (integration?.originalExecutable || originalExecutable || undefined) : undefined, + integration?.commandTokenAdded ?? false, + ); + } catch { + // Leave the owned integration in place rather than guessing at cleanup. + rollbackSucceeded = false; + } + } + if (rollbackSucceeded) { + const removed = await removeWorkaroundState(appId); + if (!removed.success) throw new Error(removed.error || "Could not roll back workaround state"); + } + throw error; + } } export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWorkarounds { @@ -49,8 +146,25 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo const pendingSliderUpdate = useRef(null); const numericAppId = Number(appId); - const applySnapshot = useCallback((steam: SteamLaunchOptionsSnapshot) => { - setSnapshot(makeSnapshot(steam)); + const loadSnapshot = useCallback(async () => { + const [result, steam] = await Promise.all([ + getWorkaroundState(appId), + readSteamLaunchOptions(numericAppId, nonSteam), + ]); + if (!result.success) throw new Error(result.error || "Could not read workaround state"); + if (!result.state) { + return adoptWorkaroundState( + appId, + nonSteam, + steam, + result.wrapper_path || getDefaultWrapperPath(), + ); + } + return makeSnapshot(steam, result, nonSteam); + }, [appId, nonSteam, numericAppId]); + + const applySnapshot = useCallback((next: WorkaroundSnapshot) => { + setSnapshot(next); setStatus("ready"); setError(null); }, []); @@ -59,65 +173,79 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo setStatus("loading"); setError(null); try { - applySnapshot(await readSteamLaunchOptions(numericAppId, nonSteam)); + applySnapshot(await loadSnapshot()); } catch (refreshError) { const nextError = asError(refreshError); setStatus("error"); setError(nextError.message); } - }, [applySnapshot, nonSteam, numericAppId]); + }, [applySnapshot, loadSnapshot]); useEffect(() => { let active = true; setStatus("loading"); setSnapshot(null); setError(null); - - const handleSnapshot = (nextSnapshot: SteamLaunchOptionsSnapshot) => { - if (!active) return; - applySnapshot(nextSnapshot); - }; - const handleSubscriptionError = (subscriptionError: Error) => { - if (!active) return; - setStatus("error"); - setError(subscriptionError.message); - }; - let unsubscribe = () => {}; try { unsubscribe = subscribeSteamLaunchOptions( numericAppId, nonSteam, - handleSnapshot, - handleSubscriptionError, + (steam) => { + if (!active) return; + setSnapshot((current) => current ? { + ...current, + steam, + integrationInstalled: integrationIsInstalled(steam, nonSteam, current.wrapperPath), + } : current); + }, + (subscriptionError) => { + if (!active) return; + setStatus("error"); + setError(subscriptionError.message); + }, ); } catch (subscriptionError) { - handleSubscriptionError(asError(subscriptionError)); + if (active) { + setStatus("error"); + setError(asError(subscriptionError).message); + } } - - void readSteamLaunchOptions(numericAppId, nonSteam) - .then((nextSnapshot) => { - if (active) applySnapshot(nextSnapshot); - }) + void loadSnapshot() + .then((next) => { if (active) applySnapshot(next); }) .catch((readError) => { - if (active) handleSubscriptionError(asError(readError)); + if (active) { + setStatus("error"); + setError(asError(readError).message); + } }); - return () => { active = false; unsubscribe(); }; - }, [applySnapshot, nonSteam, numericAppId]); + }, [applySnapshot, loadSnapshot, nonSteam, numericAppId]); const persistUpdate = useCallback(async (field: WorkaroundField, value: boolean | number): Promise => { + const current = snapshot; + if (!current) return false; setError(null); + const nextState = { ...current.state, [field]: value } as WorkaroundState; try { - const nextSnapshot = await updateSteamLaunchOptions( - numericAppId, - nonSteam, - (options) => applyWorkaroundChange(options, field, value), + const result = await setWorkaroundState( + appId, + nextState, + current.shortcutExe ?? null, + current.commandTokenAdded, ); - applySnapshot(nextSnapshot); + if (!result.success || !result.state) throw new Error(result.error || "Could not save workaround state"); + applySnapshot({ + ...current, + state: result.state, + wrapperPath: result.wrapper_path || current.wrapperPath, + wrapperOwned: result.wrapper_owned === true, + shortcutExe: result.shortcut_exe, + commandTokenAdded: result.command_token_added === true, + }); return true; } catch (updateError) { const nextError = asError(updateError); @@ -126,14 +254,13 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo showErrorToast("Workaround update failed", nextError.message); return false; } - }, [applySnapshot, nonSteam, numericAppId]); + }, [appId, applySnapshot, snapshot]); const flushSliderUpdate = useCallback(async (): Promise => { const pending = pendingSliderUpdate.current; if (!pending) return true; - pendingSliderUpdate.current = null; - window.clearTimeout(pending.timer); + clearTimeout(pending.timer); const success = await persistUpdate("dxvkFrameRate", pending.value); pending.waiters.forEach((resolve) => resolve(success)); return success; @@ -143,30 +270,25 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo if (field === "dxvkFrameRate") { setError(null); return new Promise((resolve) => { - const pending = pendingSliderUpdate.current ?? { timer: 0, value: 0, waiters: [] }; + const pending = pendingSliderUpdate.current || { timer: 0, value: 0, waiters: [] }; window.clearTimeout(pending.timer); pending.value = Number(value); pending.waiters.push(resolve); - pending.timer = window.setTimeout(() => { - void flushSliderUpdate(); - }, SLIDER_DEBOUNCE_MS); + pending.timer = window.setTimeout(() => { void flushSliderUpdate(); }, SLIDER_DEBOUNCE_MS); pendingSliderUpdate.current = pending; }); } - const sliderSuccess = await flushSliderUpdate(); if (!sliderSuccess) return false; return persistUpdate(field, value); }, [flushSliderUpdate, persistUpdate]); - useEffect(() => { - return () => { - const pending = pendingSliderUpdate.current; - if (!pending) return; - window.clearTimeout(pending.timer); - pendingSliderUpdate.current = null; - pending.waiters.forEach((resolve) => resolve(false)); - }; + useEffect(() => () => { + const pending = pendingSliderUpdate.current; + if (!pending) return; + window.clearTimeout(pending.timer); + pendingSliderUpdate.current = null; + pending.waiters.forEach((resolve) => resolve(false)); }, [numericAppId, nonSteam]); return useMemo(() => ({ status, snapshot, refresh, update, error }), [error, refresh, snapshot, status, update]); diff --git a/src/types.d.ts b/src/types.d.ts index 4b88d3d..7b5d055 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -30,6 +30,7 @@ interface SteamApps { ): SteamAppDetailsRegistration; SetAppLaunchOptions(appId: number, options: string): void | Promise; SetShortcutLaunchOptions(appId: number, options: string): void | Promise; + SetShortcutExe(appId: number, executable: string): void | Promise; GetAllShortcuts?(): Promise; } diff --git a/src/utils/steamLaunchOptionParser.ts b/src/utils/steamLaunchOptionParser.ts deleted file mode 100644 index 9449b33..0000000 --- a/src/utils/steamLaunchOptionParser.ts +++ /dev/null @@ -1,525 +0,0 @@ -export interface WorkaroundState { - dxvkFrameRate: number; - disableGamescopeWsi: boolean; - disableHdr: boolean; - disableSteamdeckMode: boolean; - disableVkbasalt: boolean; - enableZink: boolean; -} - -export type WorkaroundField = keyof WorkaroundState; - -export interface ParsedWorkaroundOptions { - state: WorkaroundState; - issues: string[]; -} - -interface LaunchToken { - raw: string; - value: string; -} - -interface EnvironmentEntry { - value: string; - count: number; -} - -type BooleanWorkaroundField = Exclude; -type EnvironmentSpec = readonly [key: string, value: string]; -type DxvkFrameRateKey = "dxvk.maxFrameRate" | "dxgi.maxFrameRate" | "d3d9.maxFrameRate"; - -interface WorkaroundDefinition { - spec: EnvironmentSpec; - clear: readonly string[]; - label?: string; -} - -const COMMAND_TOKEN = "%command%"; -const LEGACY_WRAPPER_TOKENS = new Set([ - "~/lsfg", - "/home/deck/lsfg", - "~/.local/bin/lsfg-vk-experimental", - "/home/deck/.local/bin/lsfg-vk-experimental", - "~/.local/bin/mako-run", - "/home/deck/.local/bin/mako-run", - "mako-run", - "~/.local/bin/mako-launch", - "/home/deck/.local/bin/mako-launch", - "mako-launch", -]); -const DXVK_FRAME_RATE_KEYS: readonly DxvkFrameRateKey[] = [ - "dxvk.maxFrameRate", - "dxgi.maxFrameRate", - "d3d9.maxFrameRate", -]; -const DXVK_MANAGED_KEYS = new Set(["DXVK_CONFIG", "DXVK_FRAME_RATE"]); -const WORKAROUND_DEFINITIONS = { - disableGamescopeWsi: { - spec: ["ENABLE_GAMESCOPE_WSI", "0"], - clear: ["DISABLE_GAMESCOPE_WSI", "ENABLE_GAMESCOPE_WSI"], - }, - disableHdr: { - spec: ["DXVK_HDR", "0"], - clear: ["DXVK_HDR"], - label: "Disable HDR", - }, - disableSteamdeckMode: { - spec: ["SteamDeck", "0"], - clear: ["SteamDeck"], - label: "Steam Deck mode", - }, - disableVkbasalt: { - spec: ["DISABLE_VKBASALT", "1"], - clear: ["DISABLE_VKBASALT"], - label: "Disable vkBasalt", - }, - enableZink: { - spec: ["MESA_LOADER_DRIVER_OVERRIDE", "zink"], - clear: ["__GLX_VENDOR_LIBRARY_NAME", "MESA_LOADER_DRIVER_OVERRIDE", "GALLIUM_DRIVER"], - }, -} as const satisfies Record; -const BOOLEAN_WORKAROUND_FIELDS: readonly BooleanWorkaroundField[] = [ - "disableGamescopeWsi", - "disableHdr", - "disableSteamdeckMode", - "disableVkbasalt", - "enableZink", -]; -const WSI_DISABLE_KEY = "DISABLE_GAMESCOPE_WSI"; -const WSI_ENABLE_KEY = "ENABLE_GAMESCOPE_WSI"; -const WORKAROUND_ENV_KEYS = new Set( - BOOLEAN_WORKAROUND_FIELDS.flatMap((field) => WORKAROUND_DEFINITIONS[field].clear), -); -const MANAGED_ENV_KEYS = new Set([ - ...DXVK_MANAGED_KEYS, - ...WORKAROUND_ENV_KEYS, -]); - -const EMPTY_WORKAROUND_STATE: WorkaroundState = { - dxvkFrameRate: 0, - disableGamescopeWsi: false, - disableHdr: false, - disableSteamdeckMode: false, - disableVkbasalt: false, - enableZink: false, -}; -const DEFAULT_WORKAROUND_STATE: WorkaroundState = { - ...EMPTY_WORKAROUND_STATE, - disableGamescopeWsi: true, - disableHdr: true, -}; - -export function getDefaultWorkaroundState(): WorkaroundState { - return { ...DEFAULT_WORKAROUND_STATE }; -} - -function decodeToken(raw: string): string { - let value = ""; - let quote: "'" | '"' | null = null; - - for (let index = 0; index < raw.length; index += 1) { - const character = raw[index]; - if (character === "\\" && quote !== "'" && index + 1 < raw.length) { - value += raw[index + 1]; - index += 1; - } else if (quote !== null) { - if (character === quote) quote = null; - else value += character; - } else if (character === "'" || character === '"') { - quote = character; - } else { - value += character; - } - } - - return value; -} - -function tokenize(options: string): LaunchToken[] { - const tokens: LaunchToken[] = []; - let start = -1; - let quote: "'" | '"' | null = null; - let escaped = false; - - for (let index = 0; index < options.length; index += 1) { - const character = options[index]; - if (start < 0) { - if (/\s/.test(character)) continue; - start = index; - } - - if (escaped) { - escaped = false; - } else if (character === "\\" && quote !== "'") { - escaped = true; - } else if (quote !== null) { - if (character === quote) quote = null; - } else if (character === "'" || character === '"') { - quote = character; - } else if (/\s/.test(character)) { - const raw = options.slice(start, index); - tokens.push({ raw, value: decodeToken(raw) }); - start = -1; - } - } - - if (start >= 0) { - const raw = options.slice(start); - tokens.push({ raw, value: decodeToken(raw) }); - } - return tokens; -} - -function serialize(tokens: readonly LaunchToken[]): string { - if (tokens.length === 1 && tokens[0].raw.toLowerCase() === COMMAND_TOKEN) return ""; - return tokens.map((token) => token.raw).join(" "); -} - -export function normalizeLaunchOptions(options: string): string { - return serialize(tokenize(options)); -} - -function parseEnvironmentToken(token: LaunchToken): [string, string] | null { - const separator = token.value.indexOf("="); - if (separator < 1) return null; - const key = token.value.slice(0, separator); - if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) return null; - return [key, token.value.slice(separator + 1)]; -} - -function findCommandIndex(tokens: readonly LaunchToken[]): number { - return tokens.findIndex((token) => token.raw.toLowerCase() === COMMAND_TOKEN); -} - -function leadingEnvironmentCount(tokens: readonly LaunchToken[]): number { - let count = 0; - while (count < tokens.length && parseEnvironmentToken(tokens[count]) !== null) count += 1; - return count; -} - -function effectivePrefixLimit(tokens: readonly LaunchToken[]): number { - return leadingEnvironmentCount(tokens); -} - -function effectiveEnvironmentEntries(tokens: readonly LaunchToken[]): Map { - const entries = new Map(); - for (let index = 0; index < effectivePrefixLimit(tokens); index += 1) { - const parsed = parseEnvironmentToken(tokens[index]); - if (!parsed) continue; - const [key, value] = parsed; - const previous = entries.get(key); - entries.set(key, { value, count: (previous?.count || 0) + 1 }); - } - return entries; -} - -function removePrefixAssignments(tokens: LaunchToken[], predicate: (token: LaunchToken) => boolean): boolean { - const limit = effectivePrefixLimit(tokens); - const retained = tokens.filter((token, index) => index >= limit || !predicate(token)); - if (retained.length === tokens.length) return false; - tokens.splice(0, tokens.length, ...retained); - return true; -} - -function removeAllAssignments(tokens: LaunchToken[], keys: ReadonlySet): boolean { - return removePrefixAssignments(tokens, (token) => { - const parsed = parseEnvironmentToken(token); - return parsed !== null && keys.has(parsed[0]); - }); -} - -function encodeEnvironmentValue(value: string): string { - if (/^[A-Za-z0-9_./:+,%=-]+$/.test(value)) return value; - return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; -} - -function insertEnvironmentSpecs(tokens: LaunchToken[], specs: readonly EnvironmentSpec[]): void { - tokens.unshift(...specs.map(([key, value]) => ({ - raw: `${key}=${encodeEnvironmentValue(value)}`, - value: `${key}=${value}`, - }))); -} - -function ensureCommandToken(tokens: LaunchToken[]): void { - if (findCommandIndex(tokens) >= 0) return; - tokens.splice(leadingEnvironmentCount(tokens), 0, { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }); -} - -export function isLegacyWrapperToken(value: string): boolean { - const path = decodeToken(value); - return LEGACY_WRAPPER_TOKENS.has(path); -} - -function removeLegacyWrapperFromTokens(tokens: LaunchToken[]): boolean { - const commandIndex = findCommandIndex(tokens); - const prefixEnd = commandIndex >= 0 ? commandIndex : tokens.length; - const retained = tokens.filter((token, index) => index >= prefixEnd || !isLegacyWrapperToken(token.raw)); - if (retained.length === tokens.length) return false; - tokens.splice(0, tokens.length, ...retained); - return true; -} - -interface DxvkConfigAssignment { - values: string[]; - malformed: number; -} - -interface ParsedDxvkConfig { - segments: string[]; - assignments: Map; -} - -function splitDxvkConfig(value: string): string[] { - const segments: string[] = []; - let start = 0; - let quote: "'" | '"' | null = null; - let escaped = false; - - for (let index = 0; index < value.length; index += 1) { - const character = value[index]; - if (escaped) escaped = false; - else if (character === "\\" && quote !== "'") escaped = true; - else if (quote !== null) { - if (character === quote) quote = null; - } else if (character === "'" || character === '"') quote = character; - else if (character === ";") { - segments.push(value.slice(start, index)); - start = index + 1; - } - } - - segments.push(value.slice(start)); - return segments; -} - -function knownDxvkKey(value: string): DxvkFrameRateKey | null { - const key = value.match(/^([A-Za-z][A-Za-z0-9.]*)/)?.[1]; - return key && DXVK_FRAME_RATE_KEYS.includes(key as DxvkFrameRateKey) - ? key as DxvkFrameRateKey - : null; -} - -function parseDxvkConfig(value: string): ParsedDxvkConfig { - const segments = splitDxvkConfig(value); - const assignments = new Map(); - for (const segment of segments) { - const trimmed = segment.trim(); - const key = knownDxvkKey(trimmed); - if (!key) continue; - const match = trimmed.match(/^[A-Za-z][A-Za-z0-9.]*\s*=\s*(.*?)\s*$/); - const entry = assignments.get(key) || { values: [], malformed: 0 }; - if (match) entry.values.push(match[1]); - else entry.malformed += 1; - assignments.set(key, entry); - } - return { segments, assignments }; -} - -function isDxvkFrameRateSegment(segment: string): boolean { - return knownDxvkKey(segment.trim()) !== null; -} - -function parseSupportedFrameRate(value: string): number | null { - if (!/^\d+$/.test(value)) return null; - const numericValue = Number(value); - return Number.isSafeInteger(numericValue) && numericValue <= 60 ? numericValue : null; -} - -function rewriteDxvkFrameRate(tokens: LaunchToken[], frameRate: number): void { - const config = effectiveEnvironmentEntries(tokens).get("DXVK_CONFIG"); - const parsed = parseDxvkConfig(config?.value || ""); - const retained = parsed.segments - .filter((segment) => !isDxvkFrameRateSegment(segment)) - .filter((segment) => segment.trim().length > 0) - .join(";"); - const nextConfig = frameRate > 0 - ? [`dxvk.maxFrameRate = ${frameRate}`, ...(retained ? [retained] : [])].join(";") - : retained; - - removeAllAssignments(tokens, DXVK_MANAGED_KEYS); - if (nextConfig) { - ensureCommandToken(tokens); - insertEnvironmentSpecs(tokens, [["DXVK_CONFIG", nextConfig]]); - } -} - -function environmentSpecsForState(state: WorkaroundState): EnvironmentSpec[] { - return BOOLEAN_WORKAROUND_FIELDS - .filter((field) => state[field]) - .map((field) => WORKAROUND_DEFINITIONS[field].spec); -} - -function validateFrameRate(frameRate: number): void { - if (!Number.isInteger(frameRate) || frameRate < 0 || frameRate > 60) { - throw new Error("Base FPS Cap must be an integer from 0 to 60"); - } -} - -function readBoolean( - entries: Map, - key: string, - label: string, - trueValue: string, - issues: string[], -): boolean { - const entry = entries.get(key); - if (!entry) return false; - const falseValue = trueValue === "1" ? "0" : "1"; - if (entry.value === trueValue) return true; - if (entry.value === falseValue) return false; - issues.push(`${label} has an unsupported value.`); - return false; -} - -export function parseWorkaroundOptions(options: string): ParsedWorkaroundOptions { - const tokens = tokenize(options); - const entries = effectiveEnvironmentEntries(tokens); - const state = { ...EMPTY_WORKAROUND_STATE }; - const issues: string[] = []; - - for (const [key, entry] of entries) { - if (MANAGED_ENV_KEYS.has(key) && entry.count > 1) { - issues.push(`${key} appears more than once; Steam uses the last value.`); - } - } - - const dxvkConfig = parseDxvkConfig(entries.get("DXVK_CONFIG")?.value || ""); - const effectiveDxvkValues = new Map(); - for (const key of DXVK_FRAME_RATE_KEYS) { - const assignment = dxvkConfig.assignments.get(key); - if (!assignment) continue; - if (assignment.malformed > 0) issues.push(`${key} in DXVK_CONFIG is malformed.`); - if (assignment.values.length > 1) { - issues.push(`${key} appears more than once in DXVK_CONFIG; DXVK uses the last value.`); - } - if (assignment.values.length === 0) continue; - const value = parseSupportedFrameRate(assignment.values[assignment.values.length - 1]); - effectiveDxvkValues.set(key, value); - if (value === null) issues.push(`${key} in DXVK_CONFIG is outside the supported 0-60 range.`); - } - - const unifiedFrameRate = effectiveDxvkValues.get("dxvk.maxFrameRate"); - const dxgiFrameRate = effectiveDxvkValues.get("dxgi.maxFrameRate"); - const d3d9FrameRate = effectiveDxvkValues.get("d3d9.maxFrameRate"); - if (unifiedFrameRate !== undefined) { - if (unifiedFrameRate !== null) state.dxvkFrameRate = unifiedFrameRate; - } else if (dxgiFrameRate !== undefined && d3d9FrameRate !== undefined) { - if (dxgiFrameRate !== null && dxgiFrameRate === d3d9FrameRate) state.dxvkFrameRate = dxgiFrameRate; - else issues.push("DXVK_CONFIG has conflicting or invalid DirectX frame caps."); - } else if (dxgiFrameRate !== undefined || d3d9FrameRate !== undefined) { - const partial = dxgiFrameRate ?? d3d9FrameRate; - if (partial !== null && partial !== undefined) state.dxvkFrameRate = partial; - issues.push("DXVK_CONFIG only caps one DirectX API; adjust the cap to normalize it."); - } - - if (entries.has("DXVK_FRAME_RATE")) { - issues.push("DXVK_FRAME_RATE is obsolete on current DXVK; adjust the cap to migrate it."); - } - - const wsiSignals: boolean[] = []; - const wsiDisable = entries.get(WSI_DISABLE_KEY); - if (wsiDisable) { - if (wsiDisable.value !== "0" && wsiDisable.value !== "1") issues.push("Disable Gamescope WSI has an unsupported value."); - else wsiSignals.push(wsiDisable.value === "1"); - } - const wsiEnable = entries.get(WSI_ENABLE_KEY); - if (wsiEnable) { - if (wsiEnable.value !== "0" && wsiEnable.value !== "1") issues.push("Enable Gamescope WSI has an unsupported value."); - else wsiSignals.push(wsiEnable.value === "0"); - } - if (wsiSignals.length > 0) { - if (wsiSignals.length === 2 && wsiSignals[0] !== wsiSignals[1]) { - issues.push("Gamescope WSI has conflicting enable and disable assignments."); - } - state.disableGamescopeWsi = wsiSignals.some(Boolean); - } - - for (const field of ["disableHdr", "disableSteamdeckMode", "disableVkbasalt"] as const) { - const { spec, label } = WORKAROUND_DEFINITIONS[field]; - state[field] = readBoolean(entries, spec[0], label || field, spec[1], issues); - } - - const vkBasaltEnable = entries.get("ENABLE_VKBASALT"); - const vkBasaltDisable = entries.get("DISABLE_VKBASALT"); - if (vkBasaltEnable?.value === "1" && vkBasaltDisable?.value === "1") { - issues.push("vkBasalt has conflicting enable and disable assignments."); - } - - const zink = entries.get(WORKAROUND_DEFINITIONS.enableZink.spec[0]); - const glxVendor = entries.get("__GLX_VENDOR_LIBRARY_NAME"); - const galliumDriver = entries.get("GALLIUM_DRIVER"); - const hasLegacyZink = glxVendor !== undefined || galliumDriver !== undefined; - if (zink || hasLegacyZink) { - state.enableZink = zink?.value === WORKAROUND_DEFINITIONS.enableZink.spec[1]; - if (hasLegacyZink && ( - glxVendor?.value !== "mesa" || - zink?.value !== WORKAROUND_DEFINITIONS.enableZink.spec[1] || - galliumDriver?.value !== "zink" - )) { - issues.push("Zink workaround is only partially configured."); - } else if (!state.enableZink) { - issues.push("Zink workaround has an unsupported driver value."); - } - } - - return { state, issues }; -} - -export function applyWorkaroundState(options: string, state: WorkaroundState): string { - validateFrameRate(state.dxvkFrameRate); - const tokens = tokenize(options); - removeLegacyWrapperFromTokens(tokens); - rewriteDxvkFrameRate(tokens, state.dxvkFrameRate); - const keysToClear = new Set( - WORKAROUND_ENV_KEYS, - ); - if (state.disableVkbasalt) keysToClear.add("ENABLE_VKBASALT"); - removeAllAssignments(tokens, keysToClear); - const specs = environmentSpecsForState(state); - if (specs.length > 0) { - ensureCommandToken(tokens); - insertEnvironmentSpecs(tokens, specs); - } - return serialize(tokens); -} - -export function applyWorkaroundChange(options: string, field: WorkaroundField, value: boolean | number): string { - const tokens = tokenize(options); - removeLegacyWrapperFromTokens(tokens); - - if (field === "dxvkFrameRate") { - if (typeof value !== "number") throw new Error("Base FPS Cap must be an integer from 0 to 60"); - validateFrameRate(value); - rewriteDxvkFrameRate(tokens, value); - return serialize(tokens); - } - - if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`); - const definition = WORKAROUND_DEFINITIONS[field]; - const keysToClear = new Set(definition.clear); - if (value && field === "disableVkbasalt") keysToClear.add("ENABLE_VKBASALT"); - removeAllAssignments(tokens, keysToClear); - if (value) { - ensureCommandToken(tokens); - insertEnvironmentSpecs(tokens, [definition.spec]); - } - return serialize(tokens); -} - -export function cleanupLegacyLaunchOptions(options: string): string { - const tokens = tokenize(options); - removeLegacyWrapperFromTokens(tokens); - return serialize(tokens); -} - -export function cleanupPluginLaunchOptions(options: string): string { - const tokens = tokenize(options); - removeLegacyWrapperFromTokens(tokens); - rewriteDxvkFrameRate(tokens, 0); - removeAllAssignments(tokens, WORKAROUND_ENV_KEYS); - return serialize(tokens); -} - -export function cleanupLegacyWrapper(options: string): string { - return cleanupLegacyLaunchOptions(options); -} diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 82ff94b..e00b32d 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -1,16 +1,52 @@ -// @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. -import { cleanupLegacyLaunchOptions, cleanupPluginLaunchOptions, isLegacyWrapperToken, normalizeLaunchOptions } from "./steamLaunchOptionParser.ts"; +const DEFAULT_WRAPPER_PATH = "~/.lsfg"; +const COMMAND_TOKEN = "%command%"; -// @ts-expect-error Node's built-in TypeScript loader requires explicit source extensions in tests. -export * from "./steamLaunchOptionParser.ts"; +export const LEGACY_WRAPPER_TOKENS = new Set([ + "~/lsfg", + "~/.local/bin/lsfg", + "~/.local/bin/lsfg-vk-experimental", + "~/.local/bin/mako-run", + "mako-run", + "~/.local/bin/mako-launch", + "mako-launch", +]); + +const LEGACY_ABSOLUTE_WRAPPER = /^\/(?:home|Users)\/[^/]+\/(?:lsfg|\.local\/bin\/(?:lsfg|lsfg-vk-experimental|mako-run|mako-launch))$/; + +const MANAGED_ENV_KEYS = new Set([ + "ENABLE_GAMESCOPE_WSI", + "DISABLE_GAMESCOPE_WSI", + "DXVK_HDR", + "SteamDeck", + "DISABLE_VKBASALT", + "ENABLE_VKBASALT", + "MESA_LOADER_DRIVER_OVERRIDE", + "__GLX_VENDOR_LIBRARY_NAME", + "GALLIUM_DRIVER", + "DXVK_FRAME_RATE", +]); + +const DXVK_FRAME_RATE_SEGMENT = /^(?:dxvk\.maxFrameRate|dxgi\.maxFrameRate|d3d9\.maxFrameRate)\s*=/i; + +interface LaunchToken { + raw: string; + value: string; +} export interface SteamLaunchOptionsSnapshot { appId: number; nonSteam: boolean; options: string; + target: string; details: SteamAppDetails; } +export interface WrapperIntegrationResult { + snapshot: SteamLaunchOptionsSnapshot; + originalExecutable?: string; + commandTokenAdded: boolean; +} + function validateAppId(appId: number): void { if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error("Invalid Steam App ID"); } @@ -21,14 +57,30 @@ function getSteamApps(): Partial | undefined { }).SteamClient?.Apps; } -function snapshotFromDetails(appId: number, nonSteam: boolean, details: SteamAppDetails): SteamLaunchOptionsSnapshot { - if (nonSteam && isLegacyWrapperToken(details.strShortcutExe || "")) { - throw new Error("The shortcut Target still points to a legacy frame-generation wrapper; restore its original executable first"); +interface TimerHost { + setTimeout(handler: () => void, timeout: number): number; + clearTimeout(timeout: number): void; +} + +function timerHost(): TimerHost { + if (typeof window !== "undefined") { + return { + setTimeout: (handler, timeout) => window.setTimeout(handler, timeout), + clearTimeout: (timeout) => window.clearTimeout(timeout), + }; } + return { + setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout) as unknown as number, + clearTimeout: (timeout) => globalThis.clearTimeout(timeout), + }; +} + +function snapshotFromDetails(appId: number, nonSteam: boolean, details: SteamAppDetails): SteamLaunchOptionsSnapshot { return { appId, nonSteam, options: nonSteam ? details.strShortcutLaunchOptions || "" : details.strLaunchOptions || "", + target: nonSteam ? details.strShortcutExe || "" : "", details, }; } @@ -44,7 +96,7 @@ function registerSteamAppDetails( validateAppId(appId); const apps = getSteamApps(); const registerForAppDetails = apps?.RegisterForAppDetails; - if (!registerForAppDetails) throw new Error("Steam launch options API is unavailable"); + if (!registerForAppDetails) throw new Error("Steam app-details API is unavailable"); let active = true; let unregisterPending = false; @@ -58,7 +110,7 @@ function registerSteamAppDetails( try { registration.unregister(); } catch { - // Steam may invalidate registrations during a details refresh. + // Steam can invalidate a registration while details are refreshing. } }; @@ -71,7 +123,7 @@ function registerSteamAppDetails( try { registration.unregister(); } catch { - // The registration can be invalidated before a synchronous callback returns. + // A synchronous callback can invalidate the registration before return. } } } catch (error) { @@ -83,25 +135,21 @@ function registerSteamAppDetails( export async function readSteamLaunchOptions(appId: number, nonSteam: boolean): Promise { return new Promise((resolve, reject) => { let settled = false; - let timeout = 0; + let timeout: number | undefined; let unsubscribe = () => {}; const finish = (error?: unknown, details?: SteamAppDetails) => { if (settled) return; settled = true; - window.clearTimeout(timeout); + if (timeout !== undefined) timerHost().clearTimeout(timeout); unsubscribe(); if (error) { reject(asError(error)); return; } - try { - resolve(snapshotFromDetails(appId, nonSteam, details || {})); - } catch (snapshotError) { - reject(asError(snapshotError)); - } + resolve(snapshotFromDetails(appId, nonSteam, details || {})); }; - timeout = window.setTimeout(() => finish(new Error("Timed out reading Steam launch options")), 5000); + timeout = timerHost().setTimeout(() => finish(new Error("Timed out reading Steam app details")), 5000); try { unsubscribe = registerSteamAppDetails(appId, (details) => { finish(undefined, details); @@ -128,6 +176,224 @@ export function subscribeSteamLaunchOptions( }); } +function decodeToken(raw: string): string { + let value = ""; + let quote: "'" | '"' | null = null; + for (let index = 0; index < raw.length; index += 1) { + const character = raw[index]; + if (character === "\\" && quote !== "'" && index + 1 < raw.length) { + value += raw[index + 1]; + index += 1; + } else if (quote !== null) { + if (character === quote) quote = null; + else value += character; + } else if (character === "'" || character === '"') { + quote = character; + } else { + value += character; + } + } + return value; +} + +function tokenize(options: string): LaunchToken[] { + const tokens: LaunchToken[] = []; + let start = -1; + let quote: "'" | '"' | null = null; + let escaped = false; + for (let index = 0; index < options.length; index += 1) { + const character = options[index]; + if (start < 0) { + if (/\s/.test(character)) continue; + start = index; + } + if (escaped) escaped = false; + else if (character === "\\" && quote !== "'") escaped = true; + else if (quote !== null) { + if (character === quote) quote = null; + } else if (character === "'" || character === '"') quote = character; + else if (/\s/.test(character)) { + const raw = options.slice(start, index); + tokens.push({ raw, value: decodeToken(raw) }); + start = -1; + } + } + if (start >= 0) { + const raw = options.slice(start); + tokens.push({ raw, value: decodeToken(raw) }); + } + return tokens; +} + +function serialize(tokens: readonly LaunchToken[]): string { + return tokens.map((token) => token.raw).join(" "); +} + +export function normalizeLaunchOptions(options: string): string { + return serialize(tokenize(options)); +} + +function isCommandToken(token: LaunchToken): boolean { + return token.raw.toLowerCase() === COMMAND_TOKEN; +} + +function commandIndex(tokens: readonly LaunchToken[]): number { + return tokens.findIndex(isCommandToken); +} + +function isAssignment(token: LaunchToken): boolean { + return /^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value); +} + +function isLegacyToken(value: string): boolean { + return LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); +} + +export function isLegacyWrapperToken(value: string): boolean { + return isLegacyToken(decodeToken(value)); +} + +function isWrapperToken(value: string, wrapperPath: string): boolean { + return decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); +} + +function removeWrapperTokens(tokens: LaunchToken[], wrapperPath: string): boolean { + const index = commandIndex(tokens); + const prefixEnd = index >= 0 ? index : tokens.length; + const retained = tokens.filter((token, tokenIndex) => tokenIndex >= prefixEnd || !isWrapperToken(token.value, wrapperPath)); + if (retained.length === tokens.length) return false; + tokens.splice(0, tokens.length, ...retained); + return true; +} + +function removeLegacyTokens(tokens: LaunchToken[]): boolean { + const index = commandIndex(tokens); + const prefixEnd = index >= 0 ? index : tokens.length; + const retained = tokens.filter((token, tokenIndex) => tokenIndex >= prefixEnd || !isLegacyToken(token.value)); + if (retained.length === tokens.length) return false; + tokens.splice(0, tokens.length, ...retained); + return true; +} + +function leadingAssignments(tokens: readonly LaunchToken[]): number { + let count = 0; + while (count < tokens.length && isAssignment(tokens[count])) count += 1; + return count; +} + +function wrapperToken(wrapperPath: string): LaunchToken { + return { raw: wrapperPath, value: wrapperPath }; +} + +export interface LaunchOptionRewrite { + options: string; + commandTokenAdded: boolean; +} + +/** Add one exact wrapper token immediately before Steam's command macro. */ +export function installWrapperLaunchOption(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): LaunchOptionRewrite { + const tokens = tokenize(options); + removeLegacyTokens(tokens); + let index = commandIndex(tokens); + if (index >= 0) { + const currentWrapper = tokens[index - 1]; + if (currentWrapper && currentWrapper.value === wrapperPath) { + return { options: serialize(tokens), commandTokenAdded: false }; + } + const retained = tokens.filter((token, tokenIndex) => tokenIndex >= index || token.value !== wrapperPath); + tokens.splice(0, tokens.length, ...retained); + index = commandIndex(tokens); + tokens.splice(index, 0, wrapperToken(wrapperPath)); + return { options: serialize(tokens), commandTokenAdded: false }; + } + + const insertion = leadingAssignments(tokens); + const argumentsOnly = insertion === tokens.length || tokens[insertion]?.value.startsWith("-"); + if (tokens.length !== insertion && !argumentsOnly) { + throw new Error("Launch options do not contain %command%; refusing to guess a launcher command"); + } + tokens.splice(insertion, 0, wrapperToken(wrapperPath), { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }); + return { options: serialize(tokens), commandTokenAdded: true }; +} + +/** Remove the wrapper and known legacy tokens, preserving the user's arguments. */ +export function removeWrapperLaunchOption( + options: string, + wrapperPath = DEFAULT_WRAPPER_PATH, + commandTokenAdded = false, +): string { + const tokens = tokenize(options); + const removed = removeWrapperTokens(tokens, wrapperPath); + if (removed && commandTokenAdded) { + const index = commandIndex(tokens); + if (index >= 0) tokens.splice(index, 1); + } + return serialize(tokens); +} + +function encodeAssignmentValue(value: string): string { + if (/^[A-Za-z0-9_./:+,%=-]+$/.test(value)) return value; + return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} + +function cleanDxvkConfigValue(value: string): string | null { + const retained = value + .split(";") + .map((segment) => segment.trim()) + .filter((segment) => segment && !DXVK_FRAME_RATE_SEGMENT.test(segment)); + return retained.length > 0 ? retained.join("; ") : null; +} + +/** Remove only the old plugin's direct assignments; unrelated prefixes remain. */ +export function cleanupPluginAssignments(options: string): string { + const tokens = tokenize(options); + const index = commandIndex(tokens); + const prefixEnd = index >= 0 ? index : tokens.length; + const retained: LaunchToken[] = []; + for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex += 1) { + const token = tokens[tokenIndex]; + if (tokenIndex >= prefixEnd || !isAssignment(token)) { + retained.push(token); + continue; + } + const separator = token.value.indexOf("="); + const key = token.value.slice(0, separator); + if (key === "DXVK_CONFIG") { + const cleaned = cleanDxvkConfigValue(token.value.slice(separator + 1)); + if (cleaned) retained.push({ raw: `DXVK_CONFIG=${encodeAssignmentValue(cleaned)}`, value: `DXVK_CONFIG=${cleaned}` }); + continue; + } + if (!MANAGED_ENV_KEYS.has(key)) retained.push(token); + } + return serialize(retained); +} + +export function cleanupLegacyLaunchOptions(options: string): string { + const tokens = tokenize(options); + removeLegacyTokens(tokens); + return serialize(tokens); +} + +export function cleanupPluginLaunchOptions(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): string { + const tokens = tokenize(options); + removeWrapperTokens(tokens, wrapperPath); + return cleanupPluginAssignments(serialize(tokens)); +} + +export function cleanupLegacyWrapper(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): string { + return cleanupPluginLaunchOptions(options, wrapperPath); +} + +export function hasWrapperLaunchIntegration(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): boolean { + const tokens = tokenize(options); + const index = commandIndex(tokens); + return index > 0 && tokens[index - 1].value === wrapperPath; +} + +function delay(milliseconds: number): Promise { + return new Promise((resolve) => timerHost().setTimeout(resolve, milliseconds)); +} + async function setSteamLaunchOptions(appId: number, nonSteam: boolean, options: string): Promise { const apps = getSteamApps(); const setter = nonSteam ? apps?.SetShortcutLaunchOptions : apps?.SetAppLaunchOptions; @@ -135,49 +401,96 @@ async function setSteamLaunchOptions(appId: number, nonSteam: boolean, options: await Promise.resolve(setter.call(apps, appId, options)); } -function delay(milliseconds: number): Promise { - return new Promise((resolve) => window.setTimeout(resolve, milliseconds)); +async function setShortcutExecutable(appId: number, executable: string): Promise { + const apps = getSteamApps(); + if (!apps?.SetShortcutExe) throw new Error("Steam shortcut Target API is unavailable"); + await Promise.resolve(apps.SetShortcutExe.call(apps, appId, executable)); } -async function waitForLaunchOptions( +async function waitForSnapshot( appId: number, nonSteam: boolean, - expected: string, + matches: (snapshot: SteamLaunchOptionsSnapshot) => boolean, + message: string, ): Promise { const deadline = Date.now() + 5000; let lastError: Error | null = null; while (Date.now() <= deadline) { try { const snapshot = await readSteamLaunchOptions(appId, nonSteam); - if (normalizeLaunchOptions(snapshot.options) === normalizeLaunchOptions(expected)) return snapshot; + if (matches(snapshot)) return snapshot; } catch (error) { lastError = asError(error); } if (Date.now() >= deadline) break; await delay(100); } - if (lastError) throw new Error(`Steam did not accept the launch options: ${lastError.message}`); - throw new Error("Steam did not accept the launch options before the readback timeout"); + if (lastError) throw new Error(`${message}: ${lastError.message}`); + throw new Error(`${message} before the readback timeout`); } -const operationQueues = new Map>(); +async function writeLaunchOptionsAndVerify( + appId: number, + nonSteam: boolean, + previous: string, + next: string, + message: string, +): Promise { + try { + await setSteamLaunchOptions(appId, nonSteam, next); + return await waitForSnapshot( + appId, + nonSteam, + (snapshot) => normalizeLaunchOptions(snapshot.options) === normalizeLaunchOptions(next), + message, + ); + } catch (error) { + const failure = asError(error); + try { + await setSteamLaunchOptions(appId, nonSteam, previous); + await waitForSnapshot( + appId, + nonSteam, + (snapshot) => normalizeLaunchOptions(snapshot.options) === normalizeLaunchOptions(previous), + "Steam did not restore the previous launch options", + ); + } catch (rollbackError) { + throw new Error(`${failure.message}; rollback also failed: ${asError(rollbackError).message}`); + } + throw failure; + } +} -function queueKey(appId: number, nonSteam: boolean): string { - return `${nonSteam ? "shortcut" : "app"}:${appId}`; +async function writeShortcutExecutableAndVerify( + appId: number, + previous: string, + next: string, + message: string, +): Promise { + try { + await setShortcutExecutable(appId, next); + return await waitForSnapshot(appId, true, (snapshot) => snapshot.target === next, message); + } catch (error) { + const failure = asError(error); + try { + await setShortcutExecutable(appId, previous); + await waitForSnapshot(appId, true, (snapshot) => snapshot.target === previous, "Steam did not restore the previous shortcut Target"); + } catch (rollbackError) { + throw new Error(`${failure.message}; rollback also failed: ${asError(rollbackError).message}`); + } + throw failure; + } } -function queueSteamAppOperation(appId: number, nonSteam: boolean, operation: () => Promise): Promise { - const key = queueKey(appId, nonSteam); +const operationQueues = new Map>(); + +function queueSteamOperation(appId: number, nonSteam: boolean, operation: () => Promise): Promise { + const key = `${nonSteam ? "shortcut" : "app"}:${appId}`; const previous = operationQueues.get(key) || Promise.resolve(); const queued = previous.catch(() => undefined).then(operation); - let cleanup: Promise; - cleanup = queued.then( - () => { - if (operationQueues.get(key) === cleanup) operationQueues.delete(key); - }, - () => { - if (operationQueues.get(key) === cleanup) operationQueues.delete(key); - }, + const cleanup = queued.then( + () => { if (operationQueues.get(key) === cleanup) operationQueues.delete(key); }, + () => { if (operationQueues.get(key) === cleanup) operationQueues.delete(key); }, ); operationQueues.set(key, cleanup); return queued; @@ -188,37 +501,96 @@ export function updateSteamLaunchOptions( nonSteam: boolean, transform: (options: string) => string, ): Promise { - return queueSteamAppOperation(appId, nonSteam, async () => { + return queueSteamOperation(appId, nonSteam, async () => { const current = await readSteamLaunchOptions(appId, nonSteam); const next = transform(current.options); if (next === current.options) return current; - await setSteamLaunchOptions(appId, nonSteam, next); - return waitForLaunchOptions(appId, nonSteam, next); + return writeLaunchOptionsAndVerify(appId, nonSteam, current.options, next, "Steam did not accept the launch options"); }); } -export function cleanupSteamLaunchOptions( +export function installWrapperIntegration( appId: number, nonSteam: boolean, + wrapperPath: string, + commandTokenAdded = false, +): Promise { + return queueSteamOperation(appId, nonSteam, async () => { + const current = await readSteamLaunchOptions(appId, nonSteam); + if (nonSteam) { + if (!current.target) throw new Error("Steam shortcut Target is empty; refusing to replace it"); + if (current.target !== wrapperPath && isWrapperToken(current.target, wrapperPath)) { + throw new Error("The shortcut Target points to a legacy frame-generation wrapper; restore it first"); + } + const cleanedOptions = cleanupPluginLaunchOptions(current.options, wrapperPath); + if (cleanedOptions !== current.options) { + await writeLaunchOptionsAndVerify(appId, true, current.options, cleanedOptions, "Steam did not accept shortcut launch options"); + } + if (current.target === wrapperPath) { + return { snapshot: await readSteamLaunchOptions(appId, true), originalExecutable: undefined, commandTokenAdded: false }; + } + const originalExecutable = current.target; + const snapshot = await writeShortcutExecutableAndVerify(appId, originalExecutable, wrapperPath, "Steam did not accept the shortcut Target"); + return { snapshot, originalExecutable, commandTokenAdded: false }; + } + + const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); + const alreadyInstalled = hasWrapperLaunchIntegration(current.options, wrapperPath); + const rewrite = installWrapperLaunchOption(cleaned, wrapperPath); + if (rewrite.options === current.options) { + return { snapshot: current, commandTokenAdded }; + } + const snapshot = await writeLaunchOptionsAndVerify(appId, false, current.options, rewrite.options, "Steam did not accept the launch options"); + return { snapshot, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded }; + }); +} + +export function removeWrapperIntegration( + appId: number, + nonSteam: boolean, + wrapperPath: string, + originalExecutable?: string, + commandTokenAdded = false, ): Promise { - return queueSteamAppOperation(appId, nonSteam, async () => { + return queueSteamOperation(appId, nonSteam, async () => { const current = await readSteamLaunchOptions(appId, nonSteam); - const next = cleanupPluginLaunchOptions(current.options); + if (nonSteam) { + if (!originalExecutable || isWrapperToken(originalExecutable, wrapperPath)) { + throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); + } + if (current.target !== wrapperPath && current.target !== originalExecutable) { + throw new Error("Shortcut Target changed externally; refusing to restore it"); + } + const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); + if (cleaned !== current.options) { + await writeLaunchOptionsAndVerify(appId, true, current.options, cleaned, "Steam did not clean shortcut launch options"); + } + if (current.target === originalExecutable) { + return readSteamLaunchOptions(appId, true); + } + return writeShortcutExecutableAndVerify(appId, wrapperPath, originalExecutable, "Steam did not restore the shortcut Target"); + } + + const withoutWrapper = removeWrapperLaunchOption(current.options, wrapperPath, commandTokenAdded); + const next = cleanupPluginAssignments(withoutWrapper); if (next === current.options) return current; - await setSteamLaunchOptions(appId, nonSteam, next); - return waitForLaunchOptions(appId, nonSteam, next); + return writeLaunchOptionsAndVerify(appId, false, current.options, next, "Steam did not clean the launch options"); }); } export function cleanupLegacySteamLaunchOptions( appId: number, nonSteam: boolean, + wrapperPath = DEFAULT_WRAPPER_PATH, ): Promise { - return queueSteamAppOperation(appId, nonSteam, async () => { + return queueSteamOperation(appId, nonSteam, async () => { const current = await readSteamLaunchOptions(appId, nonSteam); - const next = cleanupLegacyLaunchOptions(current.options); + const next = cleanupPluginLaunchOptions(current.options, wrapperPath); if (next === current.options) return current; - await setSteamLaunchOptions(appId, nonSteam, next); - return waitForLaunchOptions(appId, nonSteam, next); + return writeLaunchOptionsAndVerify(appId, nonSteam, current.options, next, "Steam did not clean legacy launch options"); }); } + +export function getDefaultWrapperPath(): string { + return DEFAULT_WRAPPER_PATH; +} -- cgit v1.2.3 From 102a4a0f0ce4af303a12e7f6f1a4454f4e572a17 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Wed, 9 Sep 2026 09:51:21 -0400 Subject: move all games --- src/components/GameConfigurationSelector.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 50b2cf8..df0c3e9 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -174,13 +174,6 @@ export function GameConfigurationSelector({ )} - {availableGames.length > 0 && ( - - - Enable all available games - - - )} + {availableGames.length > 0 && ( + + + Enable all available games + + + )} Date: Wed, 9 Sep 2026 19:16:30 -0400 Subject: refactor: unify flatpak targets with steam profiles --- src/api/lsfgApi.ts | 81 ++++++----- src/components/ConfigurationTab.tsx | 22 ++- src/components/Content.tsx | 41 +++--- src/components/FlatpaksTab.tsx | 196 --------------------------- src/components/GameConfigurationControls.tsx | 3 +- src/components/GameConfigurationSelector.tsx | 101 +++----------- src/components/NowPlayingTab.tsx | 93 +++++++++++-- src/components/SetupTab.tsx | 142 ++++++++++++++++--- src/components/WorkaroundsSection.tsx | 6 +- src/components/index.ts | 2 - src/hooks/useGameConfiguration.ts | 78 +++++++---- src/hooks/usePerAppWorkarounds.ts | 24 +++- src/types.d.ts | 1 + 13 files changed, 399 insertions(+), 391 deletions(-) delete mode 100644 src/components/FlatpaksTab.tsx (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 087228c..f487dff 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -43,7 +43,34 @@ export interface GameConfigEntry { profile: string; config: LsfgConfig; } -export interface InstalledGame { appid: string; name: string; nonSteam: boolean; } +export type TargetTransport = + | { kind: "host" } + | { kind: "flatpak"; flatpakAppId: string }; + +export type FlatpakTargetSupportStatus = "ready" | "needs-runtime" | "unsupported" | "error"; + +export interface FlatpakTargetSupport { + success: boolean; + message?: string; + error?: string | null; + flatpak_app_id?: string; + runtime?: string | null; + runtime_branch?: string | null; + support_status: FlatpakTargetSupportStatus; + extension_installed: boolean; + installed_branches: string[]; +} + +export interface InstalledGame { + appid: string; + name: string; + nonSteam: boolean; + transport: TargetTransport; + executable?: string; + arguments?: string; + startDir?: string; + flatpakSupport?: FlatpakTargetSupport; +} export interface InstalledGamesResult { success: boolean; games?: InstalledGame[]; error?: string; } export interface GlobalConfig { dll: string; no_fp16: boolean; } @@ -79,6 +106,7 @@ export interface WorkaroundStateResult { wrapper_owned?: boolean; shortcut_exe?: string | null; command_token_added?: boolean; + transport?: TargetTransport | null; } export interface FileContentResult { @@ -88,37 +116,25 @@ export interface FileContentResult { error?: string; } -// Flatpak management interfaces export interface FlatpakExtensionStatus { success: boolean; message: string; - error?: string; - installed_23_08: boolean; - installed_24_08: boolean; - installed_25_08: boolean; + error?: string | null; + available: boolean; + extension_id: string; + supported_branches: string[]; + installed_branches: string[]; + owned_branches: string[]; + ownership_uncertain: boolean; } -export interface FlatpakApp { - app_id: string; - app_name: string; - has_filesystem_override: boolean; - has_env_override: boolean; -} - -export interface FlatpakAppInfo { - success: boolean; - message: string; - error?: string; - apps: FlatpakApp[]; - total_apps: number; -} - -export interface FlatpakOperationResult { +export interface FlatpakCleanupResult { success: boolean; message: string; - error?: string; - app_id?: string; - operation?: string; + error?: string | null; + removed_branches: string[]; + preserved_branches: string[]; + ownership_uncertain: boolean; } // API functions @@ -128,13 +144,13 @@ export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); export const getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); -// Flatpak management API functions -export const checkFlatpakExtensionStatus = callable<[], FlatpakExtensionStatus>("check_flatpak_extension_status"); -export const installFlatpakExtension = callable<[string], FlatpakOperationResult>("install_flatpak_extension"); -export const uninstallFlatpakExtension = callable<[string], FlatpakOperationResult>("uninstall_flatpak_extension"); -export const getFlatpakApps = callable<[], FlatpakAppInfo>("get_flatpak_apps"); -export const setFlatpakAppOverride = callable<[string], FlatpakOperationResult>("set_flatpak_app_override"); -export const removeFlatpakAppOverride = callable<[string], FlatpakOperationResult>("remove_flatpak_app_override"); +export const getFlatpakSupportStatus = callable<[], FlatpakExtensionStatus>("get_flatpak_support_status"); +export const ensureFlatpakSupport = callable<[string], FlatpakTargetSupport>("ensure_flatpak_support"); +export const repairFlatpakSupport = callable<[string], FlatpakTargetSupport>("repair_flatpak_support"); +export const removePluginOwnedFlatpakExtensions = callable< + [], + FlatpakCleanupResult +>("remove_plugin_owned_flatpak_extensions"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); @@ -147,5 +163,6 @@ export const setWorkaroundState = callable<[ WorkaroundState, string | null | undefined, boolean, + TargetTransport | null | undefined, ], WorkaroundStateResult>("set_workaround_state"); export const removeWorkaroundState = callable<[string], WorkaroundStateResult>("remove_workaround_state"); diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 62a971b..90c1a7b 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -14,7 +14,6 @@ interface ConfigurationTabProps { onSelect: (appid: string) => void; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; onEnable: (appid: string) => Promise; - onEnableAll: () => Promise; onRepair: (appid: string) => Promise; onReset: () => Promise; onResetAll: () => Promise; @@ -27,7 +26,6 @@ export function ConfigurationTab({ onSelect, onConfigChange, onEnable, - onEnableAll, onRepair, onReset, onResetAll, @@ -86,7 +84,6 @@ export function ConfigurationTab({ onSelect(appid); setDetailAppId(appid); }} - onEnableAll={onEnableAll} onResetAll={onResetAll} focusConfiguredToggle={focusConfiguredToggle} onConfiguredToggleFocused={clearConfiguredToggleFocusRequest} @@ -96,8 +93,13 @@ export function ConfigurationTab({ } const profileLabel = selectedTarget?.name || "Game profile"; + const profileTransport = selectedTarget + ? selectedTarget.transport.kind === "flatpak" + ? "Non-Steam · Flatpak" + : selectedTarget.nonSteam ? "Non-Steam" : "Steam" + : "Game"; const profileDescription = selectedTarget - ? `${selectedTarget.nonSteam ? "Non-Steam" : "Steam"} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}` + ? `${profileTransport} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}` : "Game is no longer available"; const handleProfileAction = async () => { if (selectedTarget?.configured) { @@ -151,6 +153,18 @@ export function ConfigurationTab({ )} + {selectedTarget?.configured && selectedTarget.transport.kind === "flatpak" && selectedTarget.flatpakSupport?.support_status !== "ready" && ( + + + void onRepair(selectedTarget.appid)} + > + Repair Flatpak support + + + + )} {selectedTarget?.configured && ( , - configuration: , - flatpak: , - configFile: , + games: , setup: , }; @@ -38,7 +34,6 @@ export function Content() { setSelectedAppId, save, enable, - enableAll, repair, resetSelected, resetAll, @@ -52,25 +47,25 @@ export function Content() { steamBranchStatus?.success === true && steamBranchStatus.installed && !steamBranchStatus.needs_switch; - const previousRunningState = useRef<{ appid: string; configured: boolean } | null>(null); + const previousRunningAppId = useRef(null); useEffect(() => { if (!setupComplete) { setTab("Setup"); return; } - setTab((current) => current === "Setup" ? (runningGame?.configured ? "NowPlaying" : "Configuration") : current); - }, [runningGame?.configured, setupComplete]); + setTab((current) => current === "Setup" ? (runningGame ? "NowPlaying" : "Games") : current); + }, [runningGame?.appid, setupComplete]); useEffect(() => { if (!setupComplete) return; - const current = runningGame ? { appid: runningGame.appid, configured: runningGame.configured } : null; - const previous = previousRunningState.current; - previousRunningState.current = current; - if (current?.appid && (current.appid !== previous?.appid || current.configured !== previous?.configured)) { - setTab(current.configured ? "NowPlaying" : "Configuration"); - } else if (!current && previous) { - setTab((currentTab) => currentTab === "NowPlaying" ? "Configuration" : currentTab); + const appid = runningGame?.appid || null; + const previous = previousRunningAppId.current; + previousRunningAppId.current = appid; + if (appid && appid !== previous) { + setTab("NowPlaying"); + } else if (!appid && previous) { + setTab((currentTab) => currentTab === "NowPlaying" ? "Games" : currentTab); } }, [runningGame?.appid, runningGame?.configured, setupComplete]); @@ -105,12 +100,13 @@ export function Content() { isUninstalling={isUninstalling} onInstall={onInstall} onUninstall={onUninstall} + flatpakRelevant={targets.some((target) => target.transport.kind === "flatpak")} /> ); const tabs = setupComplete ? [ - ...(runningGame?.configured ? [{ + ...(runningGame ? [{ id: "NowPlaying", title: tabIcons.nowPlaying, content: ( @@ -118,12 +114,14 @@ export function Content() { game={runningGame} config={config} onConfigChange={(fieldName, value) => handleConfigChange(fieldName, value)} + onEnable={enable} + onRepair={repair} /> ), }] : []), { - id: "Configuration", - title: tabIcons.configuration, + id: "Games", + title: tabIcons.games, content: ( handleConfigChange(fieldName, value, true)} onEnable={enable} - onEnableAll={enableAll} onRepair={repair} onReset={resetSelected} onResetAll={resetAll} /> ), }, - { id: "Flatpak", title: tabIcons.flatpak, content: }, - { id: "ConfigFile", title: tabIcons.configFile, content: }, // comment out for prod { id: "Setup", title: tabIcons.setup, content: setupContent }, ] : [ diff --git a/src/components/FlatpaksTab.tsx b/src/components/FlatpaksTab.tsx deleted file mode 100644 index 8aab940..0000000 --- a/src/components/FlatpaksTab.tsx +++ /dev/null @@ -1,196 +0,0 @@ -import { useEffect, useState } from "react"; -import { - ConfirmModal, - Field, - PanelSection, - PanelSectionRow, - ToggleField, - showModal, -} from "@decky/ui"; -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 ( - - onAction()} - disabled={busy} - /> - - ); -} - -interface AppRowProps { - app: FlatpakApp; - runtimeReady: boolean; - busy: boolean; - onToggle: () => void; -} - -function AppRow({ app, runtimeReady, 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 - ? runtimeReady - ? t("FLATPAK_STATUS_READY", "Ready") - : t("FLATPAK_STATUS_RUNTIME_MISSING", "Runtime missing") - : partial - ? t("FLATPAK_STATUS_PARTIAL", "Partial") - : t("FLATPAK_STATUS_NOT_ENABLED", "Not enabled"); - - 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 runtimeReady = extensionStatus?.success === true - && runtimeVersions.some(({ key }) => extensionStatus[key]); - - 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/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx index 7025f78..6bea2e0 100644 --- a/src/components/GameConfigurationControls.tsx +++ b/src/components/GameConfigurationControls.tsx @@ -10,7 +10,7 @@ interface Props { autoFocusFpsMultiplier?: boolean; onFpsMultiplierFocused?: () => void; showWorkarounds?: boolean; - workaroundTarget?: Pick; + workaroundTarget?: Pick; onRepairWorkaround?: () => Promise; } @@ -36,6 +36,7 @@ export function GameConfigurationControls({ )} diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index df0c3e9..2a92c67 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -7,14 +7,13 @@ interface Props { targets: GameTarget[]; runningGame: GameTarget | null; onSelect: (appid: string) => void; - onEnableAll: () => Promise; onResetAll: () => Promise; focusConfiguredToggle?: boolean; onConfiguredToggleFocused?: () => void; } -const CONFIGURED_COLLAPSED_KEY = "lsfg-configured-games-collapsed-v3"; -const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed-v2"; +const ENABLED_COLLAPSED_KEY = "lsfg-enabled-games-collapsed-v4"; +const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed-v3"; function usePersistentCollapsed(key: string) { const [collapsed, setCollapsed] = useState(() => { @@ -36,6 +35,11 @@ function usePersistentCollapsed(key: string) { return [collapsed, () => setCollapsed((value) => !value)] as const; } +function targetDescription(game: GameTarget): string { + if (game.transport.kind === "flatpak") return "Non-Steam · Flatpak"; + return game.nonSteam ? "Non-Steam" : "Steam"; +} + function GameGroup({ title, games, @@ -56,7 +60,7 @@ function GameGroup({ return ( <> - +
- {collapsed ? ( - - ) : ( - - )} + {collapsed ? : }
@@ -81,7 +81,7 @@ function GameGroup({ onSelect(game.appid)} highlightOnFocus /> @@ -95,7 +95,6 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, - onEnableAll, onResetAll, focusConfiguredToggle = false, onConfiguredToggleFocused, @@ -105,26 +104,20 @@ export function GameConfigurationSelector({ if (b.appid === runningGame?.appid) return 1; return a.name.localeCompare(b.name); }); - const configuredGames = sortGames(targets.filter((game) => game.configured)); + const enabledGames = sortGames(targets.filter((game) => game.configured)); const availableGames = sortGames(targets.filter((game) => !game.configured)); - const configuredSteamGames = configuredGames.filter((game) => !game.nonSteam); - const configuredNonSteamGames = configuredGames.filter((game) => game.nonSteam); - const availableSteamGames = availableGames.filter((game) => !game.nonSteam); - const availableNonSteamGames = availableGames.filter((game) => game.nonSteam); - const [configuredCollapsed, toggleConfigured] = usePersistentCollapsed(CONFIGURED_COLLAPSED_KEY); - const [configuredNonSteamCollapsed, toggleConfiguredNonSteam] = usePersistentCollapsed(`${CONFIGURED_COLLAPSED_KEY}-non-steam`); + const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(ENABLED_COLLAPSED_KEY); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); - const [availableNonSteamCollapsed, toggleAvailableNonSteam] = usePersistentCollapsed(`${AVAILABLE_COLLAPSED_KEY}-non-steam`); - const configuredToggleRef = useRef(null); + const enabledToggleRef = useRef(null); useEffect(() => { if (!focusConfiguredToggle) return; const frame = requestAnimationFrame(() => { - configuredToggleRef.current?.querySelector('[role="button"], button')?.focus(); + enabledToggleRef.current?.querySelector('[role="button"], button')?.focus(); onConfiguredToggleFocused?.(); }); return () => cancelAnimationFrame(frame); - }, [configuredGames.length, focusConfiguredToggle, onConfiguredToggleFocused]); + }, [enabledGames.length, focusConfiguredToggle, onConfiguredToggleFocused]); const confirmResetAll = () => { showModal( @@ -137,79 +130,29 @@ export function GameConfigurationSelector({ />, ); }; - const confirmEnableAll = () => { - showModal( - void onEnableAll()} - onCancel={() => {}} - />, - ); - }; return ( <> - {targets.length === 0 && ( )} - - - {availableGames.length > 0 && ( - - - Enable all available games - - - )} Promise; + onConfigChange: ( + fieldName: keyof ConfigurationData, + value: boolean | number | string | string[], + ) => Promise; + onEnable: (appid: string) => Promise; + onRepair: (appid: string) => Promise; } -export function NowPlayingTab({ game, config, onConfigChange }: Props) { +function targetDescription(game: GameTarget): string { + if (game.transport.kind === "flatpak") return "Non-Steam · Flatpak"; + return game.nonSteam ? "Non-Steam" : "Steam"; +} + +export function NowPlayingTab({ + game, + config, + onConfigChange, + onEnable, + onRepair, +}: Props) { + const [busy, setBusy] = useState(false); + const supportNeedsRepair = + game.configured && + game.transport.kind === "flatpak" && + game.flatpakSupport?.support_status !== "ready"; + + const handleEnable = async () => { + if (busy) return; + setBusy(true); + try { + await onEnable(game.appid); + } finally { + setBusy(false); + } + }; + + const handleRepair = async () => { + if (busy) return; + setBusy(true); + try { + await onRepair(game.appid); + } finally { + setBusy(false); + } + }; + return ( - + - + - + {!game.configured && ( + + + + + + void handleEnable()}> + {busy ? "Enabling..." : "Enable LSFG-VK"} + + + + )} + {game.configured && supportNeedsRepair && ( + + + + + + void handleRepair()}> + {busy ? "Repairing..." : "Repair Flatpak support"} + + + + )} + {game.configured && ( + + )} ); } diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index 98d6e78..9c854e1 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,5 +1,11 @@ -import { PanelSection } from "@decky/ui"; -import type { SteamBranchStatus } from "../api/lsfgApi"; +import { ButtonItem, ConfirmModal, Field, PanelSection, PanelSectionRow, showModal } from "@decky/ui"; +import { useEffect, useState } from "react"; +import { + getFlatpakSupportStatus, + removePluginOwnedFlatpakExtensions, + type FlatpakExtensionStatus, + type SteamBranchStatus, +} from "../api/lsfgApi"; import { InstallationButton } from "./InstallationButton"; import { StatusDisplay } from "./StatusDisplay"; @@ -13,6 +19,104 @@ interface SetupTabProps { isUninstalling: boolean; onInstall: () => void; onUninstall: () => void; + flatpakRelevant: boolean; +} + +function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { + const [status, setStatus] = useState(null); + const [advanced, setAdvanced] = useState(false); + const [busy, setBusy] = useState(false); + + const refresh = async () => { + try { + setStatus(await getFlatpakSupportStatus()); + } catch (error) { + setStatus({ + success: false, + message: "", + error: String(error), + available: false, + extension_id: "", + supported_branches: [], + installed_branches: [], + owned_branches: [], + ownership_uncertain: false, + }); + } + }; + + useEffect(() => { + if (relevant) void refresh(); + }, [relevant]); + + if (!relevant || !status?.available) return null; + + const confirmCleanup = () => { + showModal( + { + setBusy(true); + try { + await removePluginOwnedFlatpakExtensions(); + await refresh(); + } finally { + setBusy(false); + } + }} + onCancel={() => {}} + />, + ); + }; + + return ( + + + + + + setAdvanced((value) => !value)}> + {advanced ? "Hide runtime details" : "Show runtime details"} + + + {advanced && ( + <> + {status.supported_branches.map((branch) => ( + + + + ))} + {status.ownership_uncertain && ( + + + + )} + + + {busy ? "Removing..." : "Remove plugin-installed extensions"} + + + + )} + + ); } export function SetupTab({ @@ -25,22 +129,26 @@ export function SetupTab({ isUninstalling, onInstall, onUninstall, + flatpakRelevant, }: SetupTabProps) { return ( - - - - + <> + + + + + + ); } diff --git a/src/components/WorkaroundsSection.tsx b/src/components/WorkaroundsSection.tsx index dbdd6a3..5587392 100644 --- a/src/components/WorkaroundsSection.tsx +++ b/src/components/WorkaroundsSection.tsx @@ -1,6 +1,7 @@ import { ButtonItem, Field, PanelSectionRow, SliderField, ToggleField } from "@decky/ui"; import { useEffect, useState } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; +import type { TargetTransport } from "../api/lsfgApi"; import { usePerAppWorkarounds } from "../hooks/usePerAppWorkarounds"; import t from "../i18n/i18n"; import type { WorkaroundField } from "../hooks/usePerAppWorkarounds"; @@ -8,6 +9,7 @@ import type { WorkaroundField } from "../hooks/usePerAppWorkarounds"; interface WorkaroundsSectionProps { appId: string; nonSteam: boolean; + transport: TargetTransport; onRepair?: () => Promise; } @@ -79,9 +81,9 @@ function usePersistentCollapsed() { return [collapsed, () => setCollapsed((value) => !value)] as const; } -export function WorkaroundsSection({ appId, nonSteam, onRepair }: WorkaroundsSectionProps) { +export function WorkaroundsSection({ appId, nonSteam, transport, onRepair }: WorkaroundsSectionProps) { const [collapsed, toggleCollapsed] = usePersistentCollapsed(); - const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam); + const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam, transport); const [repairing, setRepairing] = useState(false); const state = snapshot?.state; const controlsDisabled = status !== "ready" || state === undefined || snapshot?.wrapperOwned !== true || snapshot.integrationInstalled !== true; diff --git a/src/components/index.ts b/src/components/index.ts index 37a8edb..7c3ee0a 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -5,8 +5,6 @@ export { ConfigurationSection } from "./ConfigurationSection"; export { FpsMultiplierControl } from "./FpsMultiplierControl"; export { ConfigurationTab } from "./ConfigurationTab"; export { SetupTab } from "./SetupTab"; -export { ConfigFileTab } from "./ConfigFileTab"; -export { FlatpaksTab } from "./FlatpaksTab"; export { GameConfigurationSelector } from "./GameConfigurationSelector"; export { GameConfigurationControls } from "./GameConfigurationControls"; export { NowPlayingTab } from "./NowPlayingTab"; diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index c66596a..b59d592 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; -import { getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; +import { ensureFlatpakSupport, getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, repairFlatpakSupport, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; import { cleanupLegacySteamLaunchOptions, getDefaultWrapperPath, hasWrapperLaunchIntegration, installWrapperIntegration, isLegacyWrapperToken, readSteamLaunchOptions, removeWrapperIntegration } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; @@ -19,7 +19,12 @@ async function getSteamShortcuts(): Promise { const appid = Number(shortcut?.appid); const name = shortcut?.data?.strAppName; if (!Number.isInteger(appid) || appid === 0 || typeof name !== "string" || !name) return []; - return [{ appid: String(appid >>> 0), name, nonSteam: true }]; + return [{ + appid: String(appid >>> 0), + name, + nonSteam: true, + transport: { kind: "host" }, + }]; }); } catch { return []; @@ -28,7 +33,10 @@ async function getSteamShortcuts(): Promise { function mergeInstalledGames(backendGames: InstalledGame[], shortcutGames: InstalledGame[]) { const games = new Map(backendGames.map((game) => [game.appid, game])); - for (const game of shortcutGames) games.set(game.appid, game); + for (const game of shortcutGames) { + const existing = games.get(game.appid); + games.set(game.appid, existing ? { ...existing, name: game.name, nonSteam: true } : game); + } return Array.from(games.values()); } @@ -82,7 +90,7 @@ export function useGameConfiguration() { const name = app.display_name || installed?.name; if (!name) return setRunningGame(null); setRunningGame((current) => current?.appid === appid ? current : { - ...(installed || { appid, name, nonSteam: false }), + ...(installed || { appid, name, nonSteam: false, transport: { kind: "host" } }), name, configured: games.some((game) => game.appid === appid), }); @@ -101,13 +109,26 @@ export function useGameConfiguration() { const targets = useMemo(() => { 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 }); + for (const game of games) if (!configured.some((item) => item.appid === game.appid)) configured.push({ appid: game.appid, name: game.profile, nonSteam: false, transport: { kind: "host" }, configured: true }); if (runningGame && !configured.some((game) => game.appid === runningGame.appid)) configured.unshift(runningGame); return configured; }, [games, installedGames, runningGame]); const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); const config = games.find((game) => game.appid === selectedAppId)?.config || template; + const ensureTargetFlatpakSupport = useCallback(async (target: GameTarget): Promise => { + if (target.transport.kind !== "flatpak") return true; + const result = await ensureFlatpakSupport(target.transport.flatpakAppId); + if (!result.success || result.support_status !== "ready") { + showErrorToast( + "Flatpak support unavailable", + result.error || result.message || "The required Flatpak runtime extension is not ready", + ); + return false; + } + return true; + }, []); + const ensureTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; const appId = Number(target.appid); @@ -119,6 +140,7 @@ export function useGameConfiguration() { const oldState = existing.state; const oldShortcutExe = existing.shortcut_exe || undefined; const oldCommandTokenAdded = existing.command_token_added === true; + const oldTransport = existing.transport || target.transport; if (target.nonSteam && oldState && current.target === wrapperPath && !oldShortcutExe) { throw new Error("Managed shortcut Target has no saved original executable"); } @@ -138,6 +160,7 @@ export function useGameConfiguration() { state, originalExecutable || null, oldCommandTokenAdded, + target.transport, ); if (!initialStateResult.success) throw new Error(initialStateResult.error || "Could not create workaround state"); @@ -149,6 +172,7 @@ export function useGameConfiguration() { state, target.nonSteam ? (integration.originalExecutable || originalExecutable || null) : null, integration.commandTokenAdded, + target.transport, ); if (!finalStateResult.success) throw new Error(finalStateResult.error || "Could not finalize workaround state"); return true; @@ -170,7 +194,13 @@ export function useGameConfiguration() { } if (rollbackSucceeded) { const restored = oldState - ? await setWorkaroundState(target.appid, oldState, oldShortcutExe || null, oldCommandTokenAdded) + ? await setWorkaroundState( + target.appid, + oldState, + oldShortcutExe || null, + oldCommandTokenAdded, + oldTransport, + ) : await removeWorkaroundState(target.appid); if (!restored.success) throw new Error(restored.error || "Could not roll back workaround state"); } @@ -227,30 +257,30 @@ export function useGameConfiguration() { const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; + if (!(await ensureTargetFlatpakSupport(target))) return false; if (!(await ensureTargetWorkarounds(target))) return false; const result = await updateGameConfig(appid, target.name, template); if (result.success) await load(); else await removeTargetWorkarounds(target); return result.success; - }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); - const enableAll = useCallback(async (): Promise => { - const available = targets.filter((target) => !target.configured && target.name); - if (available.length === 0) return; - for (const target of available) { - if (!(await ensureTargetWorkarounds(target))) return; - const result = await updateGameConfig(target.appid, target.name, template); - if (!result.success) { - showErrorToast("Could not enable all games", result.error || "A game profile could not be created"); - await removeTargetWorkarounds(target); - return; - } - } - await load(); - }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + }, [ensureTargetFlatpakSupport, ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); const repair = useCallback(async (appid: string): Promise => { const target = targets.find((item) => item.appid === appid); - return target ? ensureTargetWorkarounds(target) : false; - }, [ensureTargetWorkarounds, targets]); + if (!target) return false; + if (target.transport.kind === "flatpak") { + const support = await repairFlatpakSupport(target.transport.flatpakAppId); + if (!support.success || support.support_status !== "ready") { + showErrorToast( + "Flatpak support unavailable", + support.error || support.message || "The required Flatpak runtime extension is not ready", + ); + return false; + } + } + const success = await ensureTargetWorkarounds(target); + if (success) await load(); + return success; + }, [ensureTargetWorkarounds, load, targets]); const resetSelected = useCallback(async () => { if (selectedAppId) { @@ -276,5 +306,5 @@ export function useGameConfiguration() { } }, [load, removeTargetWorkarounds, targets]); - return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, repair, resetSelected, resetAll, reload: load }; + return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, repair, resetSelected, resetAll, reload: load }; } diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index 9e283db..c7413b0 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -3,6 +3,7 @@ import { getWorkaroundState, removeWorkaroundState, setWorkaroundState, + type TargetTransport, type WorkaroundState, } from "../api/lsfgApi"; import { @@ -45,6 +46,7 @@ export interface WorkaroundSnapshot { integrationInstalled: boolean; commandTokenAdded: boolean; shortcutExe?: string | null; + transport: TargetTransport; } interface PerAppWorkarounds { @@ -85,12 +87,14 @@ function makeSnapshot( integrationInstalled: integrationIsInstalled(steam, nonSteam, wrapperPath), commandTokenAdded: result.command_token_added === true, shortcutExe: result.shortcut_exe, + transport: result.transport || { kind: "host" }, }; } async function adoptWorkaroundState( appId: string, nonSteam: boolean, + transport: TargetTransport, steam: SteamLaunchOptionsSnapshot, wrapperPath: string, ): Promise { @@ -98,7 +102,13 @@ async function adoptWorkaroundState( throw new Error("Shortcut Target is a wrapper but its original Target is unknown"); } const originalExecutable = nonSteam ? steam.target : null; - const initial = await setWorkaroundState(appId, DEFAULT_WORKAROUND_STATE, originalExecutable, false); + const initial = await setWorkaroundState( + appId, + DEFAULT_WORKAROUND_STATE, + originalExecutable, + false, + transport, + ); if (!initial.success) throw new Error(initial.error || "Could not create workaround state"); let integration: Awaited> | null = null; try { @@ -112,6 +122,7 @@ async function adoptWorkaroundState( DEFAULT_WORKAROUND_STATE, nonSteam ? (integration.originalExecutable || originalExecutable) : null, integration.commandTokenAdded, + transport, ); if (!finalized.success) throw new Error(finalized.error || "Could not finalize workaround state"); return makeSnapshot(integration.snapshot, finalized, nonSteam); @@ -139,7 +150,11 @@ async function adoptWorkaroundState( } } -export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWorkarounds { +export function usePerAppWorkarounds( + appId: string, + nonSteam: boolean, + transport: TargetTransport = { kind: "host" }, +): PerAppWorkarounds { const [status, setStatus] = useState("loading"); const [snapshot, setSnapshot] = useState(null); const [error, setError] = useState(null); @@ -156,12 +171,13 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo return adoptWorkaroundState( appId, nonSteam, + transport, steam, result.wrapper_path || getDefaultWrapperPath(), ); } return makeSnapshot(steam, result, nonSteam); - }, [appId, nonSteam, numericAppId]); + }, [appId, nonSteam, numericAppId, transport]); const applySnapshot = useCallback((next: WorkaroundSnapshot) => { setSnapshot(next); @@ -236,6 +252,7 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo nextState, current.shortcutExe ?? null, current.commandTokenAdded, + current.transport, ); if (!result.success || !result.state) throw new Error(result.error || "Could not save workaround state"); applySnapshot({ @@ -245,6 +262,7 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo wrapperOwned: result.wrapper_owned === true, shortcutExe: result.shortcut_exe, commandTokenAdded: result.command_token_added === true, + transport: result.transport || current.transport, }); return true; } catch (updateError) { diff --git a/src/types.d.ts b/src/types.d.ts index 7b5d055..df433e0 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -17,6 +17,7 @@ interface SteamAppDetails { strLaunchOptions?: string; strShortcutLaunchOptions?: string; strShortcutExe?: string; + strShortcutStartDir?: string; } interface SteamAppDetailsRegistration { -- cgit v1.2.3 From fb4d053213bdbda271a54b517a11a89c4780f80a Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Wed, 9 Sep 2026 20:45:20 -0400 Subject: fix: restore profile and Flatpak controls --- src/api/lsfgApi.ts | 15 ++++++ src/components/ConfigurationTab.tsx | 3 ++ src/components/Content.tsx | 11 +++- src/components/GameConfigurationSelector.tsx | 40 ++++++++++++++ src/components/SetupTab.tsx | 81 ++++++++++++++++++++++++---- src/components/index.ts | 1 + src/hooks/useGameConfiguration.ts | 65 ++++++++++++++++++++-- src/hooks/usePerAppWorkarounds.ts | 24 +++++++-- 8 files changed, 221 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index f487dff..16b6eab 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -137,6 +137,17 @@ export interface FlatpakCleanupResult { ownership_uncertain: boolean; } +export interface FlatpakExtensionToggleResult { + success: boolean; + message: string; + error?: string | null; + runtime_branch: string; + enabled: boolean; + installed: boolean; + owned_by_plugin: boolean; + preserved: boolean; +} + // API functions export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); @@ -147,6 +158,10 @@ export const getConfigFileContent = callable<[], FileContentResult>("get_config_ export const getFlatpakSupportStatus = callable<[], FlatpakExtensionStatus>("get_flatpak_support_status"); export const ensureFlatpakSupport = callable<[string], FlatpakTargetSupport>("ensure_flatpak_support"); export const repairFlatpakSupport = callable<[string], FlatpakTargetSupport>("repair_flatpak_support"); +export const setFlatpakExtensionEnabled = callable< + [string, boolean], + FlatpakExtensionToggleResult +>("set_flatpak_extension_enabled"); export const removePluginOwnedFlatpakExtensions = callable< [], FlatpakCleanupResult diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 90c1a7b..8f8690c 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -14,6 +14,7 @@ interface ConfigurationTabProps { onSelect: (appid: string) => void; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; onEnable: (appid: string) => Promise; + onEnableAll: () => Promise; onRepair: (appid: string) => Promise; onReset: () => Promise; onResetAll: () => Promise; @@ -26,6 +27,7 @@ export function ConfigurationTab({ onSelect, onConfigChange, onEnable, + onEnableAll, onRepair, onReset, onResetAll, @@ -84,6 +86,7 @@ export function ConfigurationTab({ onSelect(appid); setDetailAppId(appid); }} + onEnableAll={onEnableAll} onResetAll={onResetAll} focusConfiguredToggle={focusConfiguredToggle} onConfiguredToggleFocused={clearConfiguredToggleFocusRequest} diff --git a/src/components/Content.tsx b/src/components/Content.tsx index ff2376b..58512d5 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,18 +1,20 @@ import { Tabs } from "@decky/ui"; import { useEffect, useRef, useState } from "react"; -import { FaGamepad, FaList, FaTools } from "react-icons/fa"; +import { FaFileAlt, FaGamepad, FaList, 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 { useInstallationStatus } from "../hooks/useLsfgHooks"; import { ConfigurationTab } from "./ConfigurationTab"; +import { ConfigFileTab } from "./ConfigFileTab"; import { NowPlayingTab } from "./NowPlayingTab"; import { SetupTab } from "./SetupTab"; const tabIcons = { nowPlaying: , games: , + configFile: , setup: , }; @@ -34,6 +36,7 @@ export function Content() { setSelectedAppId, save, enable, + enableAll, repair, resetSelected, resetAll, @@ -130,12 +133,18 @@ export function Content() { onSelect={setSelectedAppId} onConfigChange={(fieldName, value) => handleConfigChange(fieldName, value, true)} onEnable={enable} + onEnableAll={enableAll} onRepair={repair} onReset={resetSelected} onResetAll={resetAll} /> ), }, + { + id: "ConfigFile", + title: tabIcons.configFile, + content: , + }, { id: "Setup", title: tabIcons.setup, content: setupContent }, ] : [ diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 2a92c67..92eacba 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -7,6 +7,7 @@ interface Props { targets: GameTarget[]; runningGame: GameTarget | null; onSelect: (appid: string) => void; + onEnableAll: () => Promise; onResetAll: () => Promise; focusConfiguredToggle?: boolean; onConfiguredToggleFocused?: () => void; @@ -95,6 +96,7 @@ export function GameConfigurationSelector({ targets, runningGame, onSelect, + onEnableAll, onResetAll, focusConfiguredToggle = false, onConfiguredToggleFocused, @@ -131,8 +133,39 @@ export function GameConfigurationSelector({ ); }; + const confirmEnableAll = () => { + showModal( + void onEnableAll()} + onCancel={() => {}} + />, + ); + }; + return ( <> + {targets.length === 0 && ( @@ -153,6 +186,13 @@ export function GameConfigurationSelector({ onToggle={toggleAvailable} onSelect={onSelect} /> + {availableGames.length > 0 && ( + + + Enable all available games + + + )} (null); const [advanced, setAdvanced] = useState(false); - const [busy, setBusy] = useState(false); + const [operation, setOperation] = useState(null); const refresh = async () => { try { @@ -51,6 +53,51 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { if (!relevant || !status?.available) return null; + const runExtensionOperation = async (version: string, enabled: boolean) => { + const operationKey = `${enabled ? "enable" : "disable"}-${version}`; + setOperation(operationKey); + try { + const result = await setFlatpakExtensionEnabled(version, enabled); + if (!result.success) throw new Error(result.error || result.message || "Flatpak runtime update failed"); + await refresh(); + } catch (error) { + showErrorToast("Flatpak runtime update failed", String(error)); + } finally { + setOperation(null); + } + }; + + const confirmDisable = (version: string) => { + showModal( + void runExtensionOperation(version, false)} + onCancel={() => {}} + />, + ); + }; + + const handleExtensionToggle = (version: string, enabled: boolean) => { + const installed = status.installed_branches.includes(version); + const owned = status.owned_branches.includes(version); + if (!enabled && installed && !owned) { + showErrorToast( + "Flatpak runtime preserved", + `${version} was not installed by this plugin, so it will remain installed.`, + ); + void refresh(); + return; + } + if (!enabled && installed && owned) { + confirmDisable(version); + return; + } + void runExtensionOperation(version, enabled); + }; + const confirmCleanup = () => { showModal( { - setBusy(true); + setOperation("cleanup"); try { - await removePluginOwnedFlatpakExtensions(); + const result = await removePluginOwnedFlatpakExtensions(); + if (!result.success) throw new Error(result.error || result.message || "Flatpak cleanup failed"); await refresh(); + } catch (error) { + showErrorToast("Flatpak cleanup failed", String(error)); } finally { - setBusy(false); + setOperation(null); } }} onCancel={() => {}} @@ -89,13 +139,22 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { <> {status.supported_branches.map((branch) => ( - handleExtensionToggle(branch, enabled)} + disabled={operation !== null || status.ownership_uncertain} /> ))} @@ -107,10 +166,10 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { - {busy ? "Removing..." : "Remove plugin-installed extensions"} + {operation === "cleanup" ? "Removing..." : "Remove plugin-installed extensions"} diff --git a/src/components/index.ts b/src/components/index.ts index 7c3ee0a..6856e76 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -4,6 +4,7 @@ export { InstallationButton } from "./InstallationButton"; export { ConfigurationSection } from "./ConfigurationSection"; export { FpsMultiplierControl } from "./FpsMultiplierControl"; export { ConfigurationTab } from "./ConfigurationTab"; +export { ConfigFileTab } from "./ConfigFileTab"; export { SetupTab } from "./SetupTab"; export { GameConfigurationSelector } from "./GameConfigurationSelector"; export { GameConfigurationControls } from "./GameConfigurationControls"; diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index b59d592..c70d589 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -40,6 +40,23 @@ function mergeInstalledGames(backendGames: InstalledGame[], shortcutGames: Insta return Array.from(games.values()); } +function selectShortcutExecutable( + target: GameTarget, + ...candidates: Array +): string | undefined { + const absolute = candidates + .map((candidate) => candidate?.trim()) + .find((candidate) => candidate && candidate.startsWith("/")); + if (absolute) return absolute; + + // Steam's app-details API can report a Flatpak Target as just "flatpak" + // even when the shortcut's canonical VDF executable is /usr/bin/flatpak. + // Keep the stored original executable absolute so SetShortcutExe and the + // generated dispatcher agree on the same direct transport. + if (target.transport.kind === "flatpak") return "/usr/bin/flatpak"; + return candidates.map((candidate) => candidate?.trim()).find(Boolean); +} + const DEFAULT_WORKAROUND_STATE: WorkaroundState = { dxvkFrameRate: 0, disableGamescopeWsi: true, @@ -151,7 +168,14 @@ export function useGameConfiguration() { throw new Error("Shortcut Target is already the managed wrapper but its original Target is unknown"); } const state = oldState || { ...DEFAULT_WORKAROUND_STATE }; - const originalExecutable = target.nonSteam ? (oldShortcutExe || current.target) : undefined; + const originalExecutable = target.nonSteam + ? selectShortcutExecutable( + target, + oldShortcutExe, + target.transport.kind === "flatpak" ? target.executable : undefined, + current.target, + ) + : undefined; const initialIntegration = target.nonSteam ? current.target === wrapperPath : hasWrapperLaunchIntegration(current.options, wrapperPath); @@ -170,7 +194,14 @@ export function useGameConfiguration() { const finalStateResult = await setWorkaroundState( target.appid, state, - target.nonSteam ? (integration.originalExecutable || originalExecutable || null) : null, + target.nonSteam + ? (selectShortcutExecutable( + target, + integration.originalExecutable, + originalExecutable, + target.transport.kind === "flatpak" ? target.executable : undefined, + ) || null) + : null, integration.commandTokenAdded, target.transport, ); @@ -184,7 +215,14 @@ export function useGameConfiguration() { appId, target.nonSteam, wrapperPath, - target.nonSteam ? (integration?.originalExecutable || originalExecutable) : undefined, + target.nonSteam + ? (selectShortcutExecutable( + target, + integration?.originalExecutable, + originalExecutable, + target.transport.kind === "flatpak" ? target.executable : undefined, + ) || undefined) + : undefined, integration?.commandTokenAdded ?? oldCommandTokenAdded, ); } catch (rollbackError) { @@ -264,6 +302,25 @@ export function useGameConfiguration() { else await removeTargetWorkarounds(target); return result.success; }, [ensureTargetFlatpakSupport, ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + const enableAll = useCallback(async (): Promise => { + const available = targets.filter((target) => !target.configured && target.name); + if (available.length === 0) return; + + for (const target of available) { + if (!(await ensureTargetFlatpakSupport(target))) return; + if (!(await ensureTargetWorkarounds(target))) return; + const result = await updateGameConfig(target.appid, target.name, template); + if (!result.success) { + await removeTargetWorkarounds(target); + showErrorToast( + "Could not enable all games", + result.error || `Could not create a profile for ${target.name}`, + ); + return; + } + } + await load(); + }, [ensureTargetFlatpakSupport, ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); const repair = useCallback(async (appid: string): Promise => { const target = targets.find((item) => item.appid === appid); if (!target) return false; @@ -306,5 +363,5 @@ export function useGameConfiguration() { } }, [load, removeTargetWorkarounds, targets]); - return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, repair, resetSelected, resetAll, reload: load }; + return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, repair, resetSelected, resetAll, reload: load }; } diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index c7413b0..e9e44e1 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -61,6 +61,18 @@ function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } +function selectShortcutExecutable( + transport: TargetTransport, + ...candidates: Array +): string | undefined { + const absolute = candidates + .map((candidate) => candidate?.trim()) + .find((candidate) => candidate && candidate.startsWith("/")); + if (absolute) return absolute; + if (transport.kind === "flatpak") return "/usr/bin/flatpak"; + return candidates.map((candidate) => candidate?.trim()).find(Boolean); +} + function integrationIsInstalled( steam: SteamLaunchOptionsSnapshot, nonSteam: boolean, @@ -101,7 +113,9 @@ async function adoptWorkaroundState( if (nonSteam && (!steam.target || steam.target === wrapperPath || isLegacyWrapperToken(steam.target))) { throw new Error("Shortcut Target is a wrapper but its original Target is unknown"); } - const originalExecutable = nonSteam ? steam.target : null; + const originalExecutable = nonSteam + ? selectShortcutExecutable(transport, steam.target) + : null; const initial = await setWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, @@ -120,7 +134,9 @@ async function adoptWorkaroundState( const finalized = await setWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, - nonSteam ? (integration.originalExecutable || originalExecutable) : null, + nonSteam + ? (selectShortcutExecutable(transport, integration.originalExecutable, originalExecutable) || null) + : null, integration.commandTokenAdded, transport, ); @@ -134,7 +150,9 @@ async function adoptWorkaroundState( Number(appId), nonSteam, wrapperPath, - nonSteam ? (integration?.originalExecutable || originalExecutable || undefined) : undefined, + nonSteam + ? (selectShortcutExecutable(transport, integration?.originalExecutable, originalExecutable) || undefined) + : undefined, integration?.commandTokenAdded ?? false, ); } catch { -- cgit v1.2.3 From bc75bb93d5aa9aa176262a138f47d3a1d53afbcb Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 00:25:58 -0400 Subject: fix: simplify Flatpak runtime toggles --- src/api/lsfgApi.ts | 17 ---------- src/components/SetupTab.tsx | 76 ++------------------------------------------- 2 files changed, 3 insertions(+), 90 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 16b6eab..8179ef9 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -124,17 +124,6 @@ export interface FlatpakExtensionStatus { extension_id: string; supported_branches: string[]; installed_branches: string[]; - owned_branches: string[]; - ownership_uncertain: boolean; -} - -export interface FlatpakCleanupResult { - success: boolean; - message: string; - error?: string | null; - removed_branches: string[]; - preserved_branches: string[]; - ownership_uncertain: boolean; } export interface FlatpakExtensionToggleResult { @@ -144,8 +133,6 @@ export interface FlatpakExtensionToggleResult { runtime_branch: string; enabled: boolean; installed: boolean; - owned_by_plugin: boolean; - preserved: boolean; } // API functions @@ -162,10 +149,6 @@ export const setFlatpakExtensionEnabled = callable< [string, boolean], FlatpakExtensionToggleResult >("set_flatpak_extension_enabled"); -export const removePluginOwnedFlatpakExtensions = callable< - [], - FlatpakCleanupResult ->("remove_plugin_owned_flatpak_extensions"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index df43c5e..aec0e93 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,8 +1,7 @@ -import { ButtonItem, ConfirmModal, Field, PanelSection, PanelSectionRow, ToggleField, showModal } from "@decky/ui"; +import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; import { useEffect, useState } from "react"; import { getFlatpakSupportStatus, - removePluginOwnedFlatpakExtensions, setFlatpakExtensionEnabled, type FlatpakExtensionStatus, type SteamBranchStatus, @@ -41,8 +40,6 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { extension_id: "", supported_branches: [], installed_branches: [], - owned_branches: [], - ownership_uncertain: false, }); } }; @@ -67,61 +64,10 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { } }; - const confirmDisable = (version: string) => { - showModal( - void runExtensionOperation(version, false)} - onCancel={() => {}} - />, - ); - }; - const handleExtensionToggle = (version: string, enabled: boolean) => { - const installed = status.installed_branches.includes(version); - const owned = status.owned_branches.includes(version); - if (!enabled && installed && !owned) { - showErrorToast( - "Flatpak runtime preserved", - `${version} was not installed by this plugin, so it will remain installed.`, - ); - void refresh(); - return; - } - if (!enabled && installed && owned) { - confirmDisable(version); - return; - } void runExtensionOperation(version, enabled); }; - const confirmCleanup = () => { - showModal( - { - setOperation("cleanup"); - try { - const result = await removePluginOwnedFlatpakExtensions(); - if (!result.success) throw new Error(result.error || result.message || "Flatpak cleanup failed"); - await refresh(); - } catch (error) { - showErrorToast("Flatpak cleanup failed", String(error)); - } finally { - setOperation(null); - } - }} - onCancel={() => {}} - />, - ); - }; - return ( @@ -147,31 +93,15 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { : operation === `disable-${branch}` ? "Uninstalling..." : status.installed_branches.includes(branch) - ? status.owned_branches.includes(branch) - ? "Installed · plugin-owned" - : "Installed · pre-existing (preserved)" + ? "Installed" : "Not installed" } checked={status.installed_branches.includes(branch)} onChange={(enabled) => handleExtensionToggle(branch, enabled)} - disabled={operation !== null || status.ownership_uncertain} + disabled={operation !== null} /> ))} - {status.ownership_uncertain && ( - - - - )} - - - {operation === "cleanup" ? "Removing..." : "Remove plugin-installed extensions"} - - )} -- cgit v1.2.3 From 28ebc17785a8cca52f289b74261d1f310fd35904 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 07:08:19 -0400 Subject: fix: detect wrapped Flatpak shortcuts --- src/components/Content.tsx | 1 - src/components/SetupTab.tsx | 68 +++++++++++++++++++-------------------------- 2 files changed, 28 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 58512d5..d4f54e9 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -103,7 +103,6 @@ export function Content() { isUninstalling={isUninstalling} onInstall={onInstall} onUninstall={onUninstall} - flatpakRelevant={targets.some((target) => target.transport.kind === "flatpak")} /> ); diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index aec0e93..6bf1fad 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,4 +1,4 @@ -import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; +import { Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; import { useEffect, useState } from "react"; import { getFlatpakSupportStatus, @@ -20,12 +20,10 @@ interface SetupTabProps { isUninstalling: boolean; onInstall: () => void; onUninstall: () => void; - flatpakRelevant: boolean; } -function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { +function FlatpakSupportDiagnostics() { const [status, setStatus] = useState(null); - const [advanced, setAdvanced] = useState(false); const [operation, setOperation] = useState(null); const refresh = async () => { @@ -45,10 +43,10 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { }; useEffect(() => { - if (relevant) void refresh(); - }, [relevant]); + void refresh(); + }, []); - if (!relevant || !status?.available) return null; + if (!status?.available) return null; const runExtensionOperation = async (version: string, enabled: boolean) => { const operationKey = `${enabled ? "enable" : "disable"}-${version}`; @@ -69,41 +67,32 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { }; return ( - + - - setAdvanced((value) => !value)}> - {advanced ? "Hide runtime details" : "Show runtime details"} - - - {advanced && ( - <> - {status.supported_branches.map((branch) => ( - - handleExtensionToggle(branch, enabled)} - disabled={operation !== null} - /> - - ))} - - )} + {status.supported_branches.map((branch) => ( + + handleExtensionToggle(branch, enabled)} + disabled={operation !== null} + /> + + ))} ); } @@ -118,7 +107,6 @@ export function SetupTab({ isUninstalling, onInstall, onUninstall, - flatpakRelevant, }: SetupTabProps) { return ( <> @@ -137,7 +125,7 @@ export function SetupTab({ onUninstall={onUninstall} /> - + ); } -- cgit v1.2.3 From 450d3e5e6612d467a00bb937538fded640c66ecb Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 07:24:05 -0400 Subject: refactor: simplify migration implementation --- src/api/lsfgApi.ts | 101 +++--- src/components/Content.tsx | 73 ++--- src/components/InstallationButton.tsx | 38 --- src/components/SetupTab.tsx | 145 +++++---- src/components/StatusDisplay.tsx | 41 --- src/components/index.ts | 2 - src/hooks/useInstallationActions.ts | 84 ----- src/hooks/useLsfgHooks.ts | 87 +++++- src/utils/steamLaunchOptions.ts | 566 ++++++++++++---------------------- src/utils/toastUtils.ts | 77 +---- 10 files changed, 434 insertions(+), 780 deletions(-) delete mode 100644 src/components/InstallationButton.tsx delete mode 100644 src/components/StatusDisplay.tsx delete mode 100644 src/hooks/useInstallationActions.ts (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 8179ef9..b96acec 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -1,11 +1,13 @@ import { callable } from "@decky/api"; import { ConfigurationData } from "../config/configSchema"; -// Type definitions for API responses -export interface InstallationResult { +interface ApiResult { success: boolean; - error?: string; message?: string; + error?: string | null; +} + +export interface InstallationResult extends ApiResult { removed_files?: string[]; } @@ -16,10 +18,8 @@ export interface InstallationStatus { error?: string; } -export interface SteamBranchStatus { - success: boolean; +export interface SteamBranchStatus extends ApiResult { message: string; - error?: string; installed: boolean; manifest_path?: string; selected_branch?: string; @@ -29,36 +29,16 @@ export interface SteamBranchStatus { restart_required: boolean; } -// Use centralized configuration data type export type LsfgConfig = ConfigurationData; - -export interface ConfigUpdateResult { - success: boolean; - message?: string; - error?: string; -} - -export interface GameConfigEntry { - appid: string; - profile: string; - config: LsfgConfig; -} export type TargetTransport = | { kind: "host" } | { kind: "flatpak"; flatpakAppId: string }; - export type FlatpakTargetSupportStatus = "ready" | "needs-runtime" | "unsupported" | "error"; -export interface FlatpakTargetSupport { - success: boolean; - message?: string; - error?: string | null; - flatpak_app_id?: string; - runtime?: string | null; - runtime_branch?: string | null; - support_status: FlatpakTargetSupportStatus; - extension_installed: boolean; - installed_branches: string[]; +export interface GameConfigEntry { + appid: string; + profile: string; + config: LsfgConfig; } export interface InstalledGame { @@ -71,20 +51,19 @@ export interface InstalledGame { startDir?: string; flatpakSupport?: FlatpakTargetSupport; } -export interface InstalledGamesResult { success: boolean; games?: InstalledGame[]; error?: string; } -export interface GlobalConfig { dll: string; no_fp16: boolean; } -export interface GameConfigsResult { - success: boolean; - global_config?: GlobalConfig; - games?: GameConfigEntry[]; - error?: string; +export interface GlobalConfig { + dll: string; + no_fp16: boolean; } -export interface GameConfigResult extends ConfigUpdateResult { - appid?: string; - exists?: boolean; - config?: LsfgConfig; +export interface FlatpakTargetSupport extends ApiResult { + flatpak_app_id?: string; + runtime?: string | null; + runtime_branch?: string | null; + support_status: FlatpakTargetSupportStatus; + extension_installed: boolean; + installed_branches: string[]; } export interface WorkaroundState { @@ -96,10 +75,7 @@ export interface WorkaroundState { enableZink: boolean; } -export interface WorkaroundStateResult { - success: boolean; - message?: string; - error?: string; +export interface WorkaroundStateResult extends ApiResult { appid?: string; state?: WorkaroundState | null; wrapper_path?: string; @@ -109,47 +85,50 @@ export interface WorkaroundStateResult { transport?: TargetTransport | null; } -export interface FileContentResult { - success: boolean; +export interface GameConfigsResult extends ApiResult { + global_config?: GlobalConfig; + games?: GameConfigEntry[]; +} + +export interface GameConfigResult extends ApiResult { + appid?: string; + exists?: boolean; + config?: LsfgConfig; +} + +export interface InstalledGamesResult extends ApiResult { + games?: InstalledGame[]; +} + +export interface FileContentResult extends ApiResult { content?: string; path?: string; - error?: string; } -export interface FlatpakExtensionStatus { - success: boolean; +export interface FlatpakExtensionStatus extends ApiResult { message: string; - error?: string | null; available: boolean; extension_id: string; supported_branches: string[]; installed_branches: string[]; } -export interface FlatpakExtensionToggleResult { - success: boolean; +export interface FlatpakExtensionToggleResult extends ApiResult { message: string; - error?: string | null; runtime_branch: string; enabled: boolean; installed: boolean; } -// API functions export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); export const getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); - export const getFlatpakSupportStatus = callable<[], FlatpakExtensionStatus>("get_flatpak_support_status"); export const ensureFlatpakSupport = callable<[string], FlatpakTargetSupport>("ensure_flatpak_support"); export const repairFlatpakSupport = callable<[string], FlatpakTargetSupport>("repair_flatpak_support"); -export const setFlatpakExtensionEnabled = callable< - [string, boolean], - FlatpakExtensionToggleResult ->("set_flatpak_extension_enabled"); - +export const setFlatpakExtensionEnabled = callable<[string, boolean], FlatpakExtensionToggleResult>("set_flatpak_extension_enabled"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); export const updateGameConfig = callable<[string, string, LsfgConfig], GameConfigResult>("update_game_config"); diff --git a/src/components/Content.tsx b/src/components/Content.tsx index d4f54e9..d92ef86 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -2,12 +2,11 @@ import { Tabs } from "@decky/ui"; import { useEffect, useRef, useState } from "react"; import { FaFileAlt, FaGamepad, FaList, 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 { useInstallationStatus } from "../hooks/useLsfgHooks"; -import { ConfigurationTab } from "./ConfigurationTab"; +import { useInstallation } from "../hooks/useLsfgHooks"; +import { tabStyles } from "../styles"; import { ConfigFileTab } from "./ConfigFileTab"; +import { ConfigurationTab } from "./ConfigurationTab"; import { NowPlayingTab } from "./NowPlayingTab"; import { SetupTab } from "./SetupTab"; @@ -19,16 +18,6 @@ const tabIcons = { }; export function Content() { - const { - isInstalled, - installationStatus, - setIsInstalled, - setInstallationStatus, - losslessScalingInstalled, - losslessScalingStatus, - steamBranchStatus, - checkInstallation, - } = useInstallationStatus(); const { config, targets, @@ -42,15 +31,25 @@ export function Content() { resetAll, reload, } = useGameConfiguration(); - const { isInstalling, isUninstalling, handleInstall, handleUninstall } = useInstallationActions(); + const { + isInstalled, + installationStatus, + losslessScalingInstalled, + losslessScalingStatus, + steamBranchStatus, + isInstalling, + isUninstalling, + install, + uninstall, + } = useInstallation(reload); const [tab, setTab] = useState("Setup"); + const previousRunningAppId = useRef(null); const setupComplete = isInstalled && losslessScalingInstalled && steamBranchStatus?.success === true && steamBranchStatus.installed && !steamBranchStatus.needs_switch; - const previousRunningAppId = useRef(null); useEffect(() => { if (!setupComplete) { @@ -65,10 +64,9 @@ export function Content() { const appid = runningGame?.appid || null; const previous = previousRunningAppId.current; previousRunningAppId.current = appid; - if (appid && appid !== previous) { - setTab("NowPlaying"); - } else if (!appid && previous) { - setTab((currentTab) => currentTab === "NowPlaying" ? "Games" : currentTab); + if (appid && appid !== previous) setTab("NowPlaying"); + else if (!appid && previous) { + setTab((current) => current === "NowPlaying" ? "Games" : current); } }, [runningGame?.appid, runningGame?.configured, setupComplete]); @@ -80,19 +78,9 @@ export function Content() { fieldName: keyof ConfigurationData, value: boolean | number | string | string[], cleanupLaunchOptions = false, - ) => { - await save({ ...config, [fieldName]: value }, cleanupLaunchOptions); - }; - - const onInstall = () => { - void handleInstall(setIsInstalled, setInstallationStatus, reload, checkInstallation); - }; - - const onUninstall = () => { - void handleUninstall(setIsInstalled, setInstallationStatus, checkInstallation); - }; + ) => save({ ...config, [fieldName]: value }, cleanupLaunchOptions); - const setupContent = ( + const setup = ( void install()} + onUninstall={() => void uninstall()} + flatpakRelevant={targets.some((target) => target.transport.kind === "flatpak")} /> ); @@ -115,7 +104,7 @@ export function Content() { handleConfigChange(fieldName, value)} + onConfigChange={(field, value) => handleConfigChange(field, value)} onEnable={enable} onRepair={repair} /> @@ -130,7 +119,7 @@ export function Content() { targets={targets} runningGame={runningGame} onSelect={setSelectedAppId} - onConfigChange={(fieldName, value) => handleConfigChange(fieldName, value, true)} + onConfigChange={(field, value) => handleConfigChange(field, value, true)} onEnable={enable} onEnableAll={enableAll} onRepair={repair} @@ -139,16 +128,10 @@ export function Content() { /> ), }, - { - id: "ConfigFile", - title: tabIcons.configFile, - content: , - }, - { id: "Setup", title: tabIcons.setup, content: setupContent }, + { id: "ConfigFile", title: tabIcons.configFile, content: }, + { id: "Setup", title: tabIcons.setup, content: setup }, ] - : [ - { id: "Setup", title: tabIcons.setup, content: setupContent }, - ]; + : [{ id: "Setup", title: tabIcons.setup, content: setup }]; return (
void; - onUninstall: () => void; -} - -export function InstallationButton({ - isInstalled, - isInstalling, - isUninstalling, - onInstall, - onUninstall -}: InstallationButtonProps) { - const label = isInstalling - ? t('INSTALL_INSTALLING', 'Installing...') - : isUninstalling - ? t('INSTALL_UNINSTALLING', 'Uninstalling...') - : isInstalled - ? t('INSTALL_UNINSTALL_BTN', 'Uninstall LSFG-VK') - : t('INSTALL_INSTALL_BTN', 'Install LSFG-VK'); - - return ( - - - {label} - - - ); -} diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index 6bf1fad..e936049 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,4 +1,4 @@ -import { Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; +import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; import { useEffect, useState } from "react"; import { getFlatpakSupportStatus, @@ -6,8 +6,7 @@ import { type FlatpakExtensionStatus, type SteamBranchStatus, } from "../api/lsfgApi"; -import { InstallationButton } from "./InstallationButton"; -import { StatusDisplay } from "./StatusDisplay"; +import t from "../i18n/i18n"; import { showErrorToast } from "../utils/toastUtils"; interface SetupTabProps { @@ -20,10 +19,12 @@ interface SetupTabProps { isUninstalling: boolean; onInstall: () => void; onUninstall: () => void; + flatpakRelevant: boolean; } -function FlatpakSupportDiagnostics() { +function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { const [status, setStatus] = useState(null); + const [advanced, setAdvanced] = useState(false); const [operation, setOperation] = useState(null); const refresh = async () => { @@ -43,16 +44,15 @@ function FlatpakSupportDiagnostics() { }; useEffect(() => { - void refresh(); - }, []); + if (relevant) void refresh(); + }, [relevant]); - if (!status?.available) return null; + if (!relevant || !status?.available) return null; - const runExtensionOperation = async (version: string, enabled: boolean) => { - const operationKey = `${enabled ? "enable" : "disable"}-${version}`; - setOperation(operationKey); + const setEnabled = async (branch: string, enabled: boolean) => { + setOperation(`${enabled ? "enable" : "disable"}-${branch}`); try { - const result = await setFlatpakExtensionEnabled(version, enabled); + const result = await setFlatpakExtensionEnabled(branch, enabled); if (!result.success) throw new Error(result.error || result.message || "Flatpak runtime update failed"); await refresh(); } catch (error) { @@ -62,70 +62,91 @@ function FlatpakSupportDiagnostics() { } }; - const handleExtensionToggle = (version: string, enabled: boolean) => { - void runExtensionOperation(version, enabled); - }; - return ( - + - {status.supported_branches.map((branch) => ( - - handleExtensionToggle(branch, enabled)} - disabled={operation !== null} - /> - - ))} + + setAdvanced((value) => !value)}> + {advanced ? "Hide runtime details" : "Show runtime details"} + + + {advanced && status.supported_branches.map((branch) => { + const installed = status.installed_branches.includes(branch); + const pending = operation?.endsWith(`-${branch}`); + return ( + + void setEnabled(branch, enabled)} + disabled={operation !== null} + /> + + ); + })} ); } -export function SetupTab({ - isInstalled, - installationStatus, - losslessScalingInstalled, - losslessScalingStatus, - steamBranchStatus, - isInstalling, - isUninstalling, - onInstall, - onUninstall, -}: SetupTabProps) { +export function SetupTab(props: SetupTabProps) { + const { + isInstalled, + installationStatus, + losslessScalingInstalled, + losslessScalingStatus, + steamBranchStatus, + isInstalling, + isUninstalling, + onInstall, + onUninstall, + flatpakRelevant, + } = props; + const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; + const buttonLabel = isInstalling + ? t("INSTALL_INSTALLING", "Installing...") + : isUninstalling + ? t("INSTALL_UNINSTALLING", "Uninstalling...") + : isInstalled + ? t("INSTALL_UNINSTALL_BTN", "Uninstall LSFG-VK") + : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); + return ( <> - - + + + + + + + {steamBranchStatus?.installed && ( + + + + )} + + + {buttonLabel} + + - + ); } diff --git a/src/components/StatusDisplay.tsx b/src/components/StatusDisplay.tsx deleted file mode 100644 index b1a98e5..0000000 --- a/src/components/StatusDisplay.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { Field, PanelSectionRow } from "@decky/ui"; -import type { SteamBranchStatus } from "../api/lsfgApi"; - -interface StatusDisplayProps { - installationStatus: string; - losslessScalingInstalled: boolean; - losslessScalingStatus: string; - steamBranchStatus: SteamBranchStatus | null; -} - -export function StatusDisplay({ - installationStatus, - losslessScalingInstalled, - losslessScalingStatus, - steamBranchStatus -}: StatusDisplayProps) { - const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; - - return ( - <> - - - - - - - - {steamBranchStatus?.installed && ( - - - - )} - - ); -} diff --git a/src/components/index.ts b/src/components/index.ts index 6856e76..bca6f6f 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -1,6 +1,4 @@ export { Content } from "./Content"; -export { StatusDisplay } from "./StatusDisplay"; -export { InstallationButton } from "./InstallationButton"; export { ConfigurationSection } from "./ConfigurationSection"; export { FpsMultiplierControl } from "./FpsMultiplierControl"; export { ConfigurationTab } from "./ConfigurationTab"; diff --git a/src/hooks/useInstallationActions.ts b/src/hooks/useInstallationActions.ts deleted file mode 100644 index 41189bd..0000000 --- a/src/hooks/useInstallationActions.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { useState } from "react"; -import { installLsfgVk, uninstallLsfgVk } from "../api/lsfgApi"; -import { - showInstallSuccessToast, - showInstallErrorToast, - showUninstallSuccessToast, - showUninstallErrorToast -} from "../utils/toastUtils"; - -export function useInstallationActions() { - const [isInstalling, setIsInstalling] = useState(false); - const [isUninstalling, setIsUninstalling] = useState(false); - - const handleInstall = async ( - setIsInstalled: (value: boolean) => void, - setInstallationStatus: (value: string) => void, - reloadConfig?: () => Promise, - reloadStatus?: () => Promise - ) => { - setIsInstalling(true); - setInstallationStatus("Installing lsfg-vk..."); - - try { - const result = await installLsfgVk(); - if (result.success) { - setIsInstalled(true); - setInstallationStatus("lsfg-vk installed"); - showInstallSuccessToast(); - - // Reload lsfg config after installation - if (reloadConfig) { - await reloadConfig(); - } - if (reloadStatus) { - await reloadStatus(); - } - } else { - setInstallationStatus(`Installation failed: ${result.error}`); - showInstallErrorToast(result.error); - } - } catch (error) { - setInstallationStatus(`Installation failed: ${error}`); - showInstallErrorToast(String(error)); - } finally { - setIsInstalling(false); - } - }; - - const handleUninstall = async ( - setIsInstalled: (value: boolean) => void, - setInstallationStatus: (value: string) => void, - reloadStatus?: () => Promise - ) => { - setIsUninstalling(true); - setInstallationStatus("Uninstalling lsfg-vk..."); - - try { - const result = await uninstallLsfgVk(); - if (result.success) { - setIsInstalled(false); - setInstallationStatus("lsfg-vk uninstalled successfully!"); - if (reloadStatus) { - await reloadStatus(); - } - showUninstallSuccessToast(); - } else { - setInstallationStatus(`Uninstallation failed: ${result.error}`); - showUninstallErrorToast(result.error); - } - } catch (error) { - setInstallationStatus(`Uninstallation failed: ${error}`); - showUninstallErrorToast(String(error)); - } finally { - setIsUninstalling(false); - } - }; - - return { - isInstalling, - isUninstalling, - handleInstall, - handleUninstall - }; -} diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index 0b71ee9..73cfa0c 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -1,16 +1,26 @@ -import { useState, useEffect } from "react"; +import { useEffect, useState } from "react"; import { checkLsfgVkInstalled, getLosslessScalingBranchStatus, - type SteamBranchStatus + installLsfgVk, + uninstallLsfgVk, + type SteamBranchStatus, } from "../api/lsfgApi"; +import { + showInstallErrorToast, + showInstallSuccessToast, + showUninstallErrorToast, + showUninstallSuccessToast, +} from "../utils/toastUtils"; -export function useInstallationStatus() { - const [isInstalled, setIsInstalled] = useState(false); - const [installationStatus, setInstallationStatus] = useState(""); - const [losslessScalingInstalled, setLosslessScalingInstalled] = useState(false); - const [losslessScalingStatus, setLosslessScalingStatus] = useState(""); +export function useInstallation(reloadConfig?: () => Promise) { + const [isInstalled, setIsInstalled] = useState(false); + const [installationStatus, setInstallationStatus] = useState(""); + const [losslessScalingInstalled, setLosslessScalingInstalled] = useState(false); + const [losslessScalingStatus, setLosslessScalingStatus] = useState(""); const [steamBranchStatus, setSteamBranchStatus] = useState(null); + const [isInstalling, setIsInstalling] = useState(false); + const [isUninstalling, setIsUninstalling] = useState(false); const checkInstallation = async () => { try { @@ -25,13 +35,9 @@ export function useInstallationStatus() { setIsInstalled(status.installed); setLosslessScalingInstalled(status.lossless_scaling_installed); setLosslessScalingStatus(status.lossless_scaling_status || "Lossless Scaling Not Installed"); - if (status.installed) { - setInstallationStatus("lsfg-vk Installed"); - } else { - setInstallationStatus("lsfg-vk Not Installed"); - } + setInstallationStatus(status.installed ? "lsfg-vk Installed" : "lsfg-vk Not Installed"); return status.installed; - } catch (error) { + } catch { setSteamBranchStatus(null); setLosslessScalingInstalled(false); setLosslessScalingStatus("Lossless Scaling Not Installed"); @@ -41,17 +47,64 @@ export function useInstallationStatus() { }; useEffect(() => { - checkInstallation(); + void checkInstallation(); }, []); + const install = async () => { + setIsInstalling(true); + setInstallationStatus("Installing lsfg-vk..."); + try { + const result = await installLsfgVk(); + if (!result.success) { + setInstallationStatus(`Installation failed: ${result.error}`); + showInstallErrorToast(result.error); + return; + } + setIsInstalled(true); + setInstallationStatus("lsfg-vk installed"); + showInstallSuccessToast(); + await reloadConfig?.(); + await checkInstallation(); + } catch (error) { + setInstallationStatus(`Installation failed: ${error}`); + showInstallErrorToast(String(error)); + } finally { + setIsInstalling(false); + } + }; + + const uninstall = async () => { + setIsUninstalling(true); + setInstallationStatus("Uninstalling lsfg-vk..."); + try { + const result = await uninstallLsfgVk(); + if (!result.success) { + setInstallationStatus(`Uninstallation failed: ${result.error}`); + showUninstallErrorToast(result.error); + return; + } + setIsInstalled(false); + setInstallationStatus("lsfg-vk uninstalled successfully!"); + await checkInstallation(); + showUninstallSuccessToast(); + } catch (error) { + setInstallationStatus(`Uninstallation failed: ${error}`); + showUninstallErrorToast(String(error)); + } finally { + setIsUninstalling(false); + } + }; + return { isInstalled, installationStatus, - setIsInstalled, - setInstallationStatus, losslessScalingInstalled, losslessScalingStatus, steamBranchStatus, - checkInstallation + isInstalling, + isUninstalling, + install, + uninstall, + checkInstallation, }; } diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index e00b32d..0af1bbf 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -12,27 +12,14 @@ export const LEGACY_WRAPPER_TOKENS = new Set([ ]); const LEGACY_ABSOLUTE_WRAPPER = /^\/(?:home|Users)\/[^/]+\/(?:lsfg|\.local\/bin\/(?:lsfg|lsfg-vk-experimental|mako-run|mako-launch))$/; - const MANAGED_ENV_KEYS = new Set([ - "ENABLE_GAMESCOPE_WSI", - "DISABLE_GAMESCOPE_WSI", - "DXVK_HDR", - "SteamDeck", - "DISABLE_VKBASALT", - "ENABLE_VKBASALT", - "MESA_LOADER_DRIVER_OVERRIDE", - "__GLX_VENDOR_LIBRARY_NAME", - "GALLIUM_DRIVER", - "DXVK_FRAME_RATE", + "ENABLE_GAMESCOPE_WSI", "DISABLE_GAMESCOPE_WSI", "DXVK_HDR", "SteamDeck", + "DISABLE_VKBASALT", "ENABLE_VKBASALT", "MESA_LOADER_DRIVER_OVERRIDE", + "__GLX_VENDOR_LIBRARY_NAME", "GALLIUM_DRIVER", "DXVK_FRAME_RATE", ]); - const DXVK_FRAME_RATE_SEGMENT = /^(?:dxvk\.maxFrameRate|dxgi\.maxFrameRate|d3d9\.maxFrameRate)\s*=/i; -interface LaunchToken { - raw: string; - value: string; -} - +interface LaunchToken { raw: string; value: string; } export interface SteamLaunchOptionsSnapshot { appId: number; nonSteam: boolean; @@ -40,42 +27,33 @@ export interface SteamLaunchOptionsSnapshot { target: string; details: SteamAppDetails; } - export interface WrapperIntegrationResult { snapshot: SteamLaunchOptionsSnapshot; originalExecutable?: string; commandTokenAdded: boolean; } -function validateAppId(appId: number): void { - if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error("Invalid Steam App ID"); +function asError(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)); } -function getSteamApps(): Partial | undefined { - return (globalThis as typeof globalThis & { - SteamClient?: { Apps?: Partial }; - }).SteamClient?.Apps; +function apps(): Partial | undefined { + return (globalThis as typeof globalThis & { SteamClient?: { Apps?: Partial } }).SteamClient?.Apps; } -interface TimerHost { - setTimeout(handler: () => void, timeout: number): number; - clearTimeout(timeout: number): void; +function validateAppId(appId: number): void { + if (!Number.isSafeInteger(appId) || appId <= 0) throw new Error("Invalid Steam App ID"); } -function timerHost(): TimerHost { - if (typeof window !== "undefined") { - return { - setTimeout: (handler, timeout) => window.setTimeout(handler, timeout), - clearTimeout: (timeout) => window.clearTimeout(timeout), - }; - } +function timer() { + const host = typeof window !== "undefined" ? window : globalThis; return { - setTimeout: (handler, timeout) => globalThis.setTimeout(handler, timeout) as unknown as number, - clearTimeout: (timeout) => globalThis.clearTimeout(timeout), + set: (handler: () => void, ms: number) => host.setTimeout(handler, ms) as unknown as number, + clear: (id: number) => host.clearTimeout(id), }; } -function snapshotFromDetails(appId: number, nonSteam: boolean, details: SteamAppDetails): SteamLaunchOptionsSnapshot { +function snapshot(appId: number, nonSteam: boolean, details: SteamAppDetails): SteamLaunchOptionsSnapshot { return { appId, nonSteam, @@ -85,73 +63,39 @@ function snapshotFromDetails(appId: number, nonSteam: boolean, details: SteamApp }; } -function asError(error: unknown): Error { - return error instanceof Error ? error : new Error(String(error)); -} - -function registerSteamAppDetails( - appId: number, - onDetails: (details: SteamAppDetails) => boolean | void, -): () => void { +function registerDetails(appId: number, onDetails: (details: SteamAppDetails) => boolean | void): () => void { validateAppId(appId); - const apps = getSteamApps(); - const registerForAppDetails = apps?.RegisterForAppDetails; - if (!registerForAppDetails) throw new Error("Steam app-details API is unavailable"); - + const register = apps()?.RegisterForAppDetails; + if (!register) throw new Error("Steam app-details API is unavailable"); let active = true; - let unregisterPending = false; let registration: SteamAppDetailsRegistration | undefined; const unsubscribe = () => { active = false; - if (!registration) { - unregisterPending = true; - return; - } - try { - registration.unregister(); - } catch { - // Steam can invalidate a registration while details are refreshing. - } + try { registration?.unregister(); } catch {} }; - - try { - registration = registerForAppDetails.call(apps, appId, (details) => { - if (!active) return; - if (onDetails(details || {}) === false && active) unsubscribe(); - }); - if (unregisterPending) { - try { - registration.unregister(); - } catch { - // A synchronous callback can invalidate the registration before return. - } - } - } catch (error) { - throw asError(error); - } + registration = register.call(apps(), appId, (details) => { + if (active && onDetails(details || {}) === false) unsubscribe(); + }); + if (!active) unsubscribe(); return unsubscribe; } export async function readSteamLaunchOptions(appId: number, nonSteam: boolean): Promise { return new Promise((resolve, reject) => { - let settled = false; - let timeout: number | undefined; + let done = false; let unsubscribe = () => {}; + const clock = timer(); + const timeout = clock.set(() => finish(new Error("Timed out reading Steam app details")), 5000); const finish = (error?: unknown, details?: SteamAppDetails) => { - if (settled) return; - settled = true; - if (timeout !== undefined) timerHost().clearTimeout(timeout); + if (done) return; + done = true; + clock.clear(timeout); unsubscribe(); - if (error) { - reject(asError(error)); - return; - } - resolve(snapshotFromDetails(appId, nonSteam, details || {})); + if (error) reject(asError(error)); + else resolve(snapshot(appId, nonSteam, details || {})); }; - - timeout = timerHost().setTimeout(() => finish(new Error("Timed out reading Steam app details")), 5000); try { - unsubscribe = registerSteamAppDetails(appId, (details) => { + unsubscribe = registerDetails(appId, (details) => { finish(undefined, details); return false; }); @@ -164,34 +108,24 @@ export async function readSteamLaunchOptions(appId: number, nonSteam: boolean): export function subscribeSteamLaunchOptions( appId: number, nonSteam: boolean, - onSnapshot: (snapshot: SteamLaunchOptionsSnapshot) => void, + onSnapshot: (value: SteamLaunchOptionsSnapshot) => void, onError: (error: Error) => void, ): () => void { - return registerSteamAppDetails(appId, (details) => { - try { - onSnapshot(snapshotFromDetails(appId, nonSteam, details)); - } catch (error) { - onError(asError(error)); - } + return registerDetails(appId, (details) => { + try { onSnapshot(snapshot(appId, nonSteam, details)); } + catch (error) { onError(asError(error)); } }); } function decodeToken(raw: string): string { let value = ""; let quote: "'" | '"' | null = null; - for (let index = 0; index < raw.length; index += 1) { - const character = raw[index]; - if (character === "\\" && quote !== "'" && index + 1 < raw.length) { - value += raw[index + 1]; - index += 1; - } else if (quote !== null) { - if (character === quote) quote = null; - else value += character; - } else if (character === "'" || character === '"') { - quote = character; - } else { - value += character; - } + for (let i = 0; i < raw.length; i++) { + const c = raw[i]; + if (c === "\\" && quote !== "'" && i + 1 < raw.length) value += raw[++i]; + else if (quote) { if (c === quote) quote = null; else value += c; } + else if (c === "'" || c === '"') quote = c; + else value += c; } return value; } @@ -201,299 +135,184 @@ function tokenize(options: string): LaunchToken[] { let start = -1; let quote: "'" | '"' | null = null; let escaped = false; - for (let index = 0; index < options.length; index += 1) { - const character = options[index]; - if (start < 0) { - if (/\s/.test(character)) continue; - start = index; - } - if (escaped) escaped = false; - else if (character === "\\" && quote !== "'") escaped = true; - else if (quote !== null) { - if (character === quote) quote = null; - } else if (character === "'" || character === '"') quote = character; - else if (/\s/.test(character)) { - const raw = options.slice(start, index); - tokens.push({ raw, value: decodeToken(raw) }); - start = -1; - } - } - if (start >= 0) { - const raw = options.slice(start); + const push = (end: number) => { + if (start < 0) return; + const raw = options.slice(start, end); tokens.push({ raw, value: decodeToken(raw) }); + start = -1; + }; + for (let i = 0; i < options.length; i++) { + const c = options[i]; + if (start < 0) { if (/\s/.test(c)) continue; start = i; } + if (escaped) escaped = false; + else if (c === "\\" && quote !== "'") escaped = true; + else if (quote) { if (c === quote) quote = null; } + else if (c === "'" || c === '"') quote = c; + else if (/\s/.test(c)) push(i); } + push(options.length); return tokens; } -function serialize(tokens: readonly LaunchToken[]): string { - return tokens.map((token) => token.raw).join(" "); -} - -export function normalizeLaunchOptions(options: string): string { - return serialize(tokenize(options)); -} - -function isCommandToken(token: LaunchToken): boolean { - return token.raw.toLowerCase() === COMMAND_TOKEN; -} +const serialize = (tokens: readonly LaunchToken[]) => tokens.map(({ raw }) => raw).join(" "); +const commandIndex = (tokens: readonly LaunchToken[]) => tokens.findIndex((token) => token.raw.toLowerCase() === COMMAND_TOKEN); +const isAssignment = (token: LaunchToken) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value); +const isLegacyToken = (value: string) => LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); +const isWrapperToken = (value: string, wrapperPath: string) => decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); -function commandIndex(tokens: readonly LaunchToken[]): number { - return tokens.findIndex(isCommandToken); -} +export const normalizeLaunchOptions = (options: string) => serialize(tokenize(options)); +export const isLegacyWrapperToken = (value: string) => isLegacyToken(decodeToken(value)); -function isAssignment(token: LaunchToken): boolean { - return /^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value); -} - -function isLegacyToken(value: string): boolean { - return LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); -} - -export function isLegacyWrapperToken(value: string): boolean { - return isLegacyToken(decodeToken(value)); -} - -function isWrapperToken(value: string, wrapperPath: string): boolean { - return decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); -} - -function removeWrapperTokens(tokens: LaunchToken[], wrapperPath: string): boolean { - const index = commandIndex(tokens); - const prefixEnd = index >= 0 ? index : tokens.length; - const retained = tokens.filter((token, tokenIndex) => tokenIndex >= prefixEnd || !isWrapperToken(token.value, wrapperPath)); - if (retained.length === tokens.length) return false; - tokens.splice(0, tokens.length, ...retained); +function removeMatchingWrappers(tokens: LaunchToken[], predicate: (value: string) => boolean): boolean { + const command = commandIndex(tokens); + const prefixEnd = command >= 0 ? command : tokens.length; + const kept = tokens.filter((token, i) => i >= prefixEnd || !predicate(token.value)); + if (kept.length === tokens.length) return false; + tokens.splice(0, tokens.length, ...kept); return true; } -function removeLegacyTokens(tokens: LaunchToken[]): boolean { - const index = commandIndex(tokens); - const prefixEnd = index >= 0 ? index : tokens.length; - const retained = tokens.filter((token, tokenIndex) => tokenIndex >= prefixEnd || !isLegacyToken(token.value)); - if (retained.length === tokens.length) return false; - tokens.splice(0, tokens.length, ...retained); - return true; -} - -function leadingAssignments(tokens: readonly LaunchToken[]): number { - let count = 0; - while (count < tokens.length && isAssignment(tokens[count])) count += 1; - return count; -} - -function wrapperToken(wrapperPath: string): LaunchToken { - return { raw: wrapperPath, value: wrapperPath }; -} - -export interface LaunchOptionRewrite { - options: string; - commandTokenAdded: boolean; -} - -/** Add one exact wrapper token immediately before Steam's command macro. */ -export function installWrapperLaunchOption(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): LaunchOptionRewrite { +export function installWrapperLaunchOption(options: string, wrapperPath = DEFAULT_WRAPPER_PATH) { const tokens = tokenize(options); - removeLegacyTokens(tokens); - let index = commandIndex(tokens); - if (index >= 0) { - const currentWrapper = tokens[index - 1]; - if (currentWrapper && currentWrapper.value === wrapperPath) { - return { options: serialize(tokens), commandTokenAdded: false }; - } - const retained = tokens.filter((token, tokenIndex) => tokenIndex >= index || token.value !== wrapperPath); - tokens.splice(0, tokens.length, ...retained); - index = commandIndex(tokens); - tokens.splice(index, 0, wrapperToken(wrapperPath)); + removeMatchingWrappers(tokens, isLegacyToken); + let command = commandIndex(tokens); + if (command >= 0) { + if (tokens[command - 1]?.value === wrapperPath) return { options: serialize(tokens), commandTokenAdded: false }; + removeMatchingWrappers(tokens, (value) => decodeToken(value) === wrapperPath); + command = commandIndex(tokens); + tokens.splice(command, 0, { raw: wrapperPath, value: wrapperPath }); return { options: serialize(tokens), commandTokenAdded: false }; } - - const insertion = leadingAssignments(tokens); - const argumentsOnly = insertion === tokens.length || tokens[insertion]?.value.startsWith("-"); - if (tokens.length !== insertion && !argumentsOnly) { + let insertion = 0; + while (insertion < tokens.length && isAssignment(tokens[insertion])) insertion++; + if (insertion < tokens.length && !tokens[insertion].value.startsWith("-")) { throw new Error("Launch options do not contain %command%; refusing to guess a launcher command"); } - tokens.splice(insertion, 0, wrapperToken(wrapperPath), { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }); + tokens.splice(insertion, 0, + { raw: wrapperPath, value: wrapperPath }, + { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }, + ); return { options: serialize(tokens), commandTokenAdded: true }; } -/** Remove the wrapper and known legacy tokens, preserving the user's arguments. */ export function removeWrapperLaunchOption( options: string, wrapperPath = DEFAULT_WRAPPER_PATH, commandTokenAdded = false, ): string { const tokens = tokenize(options); - const removed = removeWrapperTokens(tokens, wrapperPath); - if (removed && commandTokenAdded) { - const index = commandIndex(tokens); - if (index >= 0) tokens.splice(index, 1); + if (removeMatchingWrappers(tokens, (value) => isWrapperToken(value, wrapperPath)) && commandTokenAdded) { + const command = commandIndex(tokens); + if (command >= 0) tokens.splice(command, 1); } return serialize(tokens); } function encodeAssignmentValue(value: string): string { - if (/^[A-Za-z0-9_./:+,%=-]+$/.test(value)) return value; - return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; -} - -function cleanDxvkConfigValue(value: string): string | null { - const retained = value - .split(";") - .map((segment) => segment.trim()) - .filter((segment) => segment && !DXVK_FRAME_RATE_SEGMENT.test(segment)); - return retained.length > 0 ? retained.join("; ") : null; + return /^[A-Za-z0-9_./:+,%=-]+$/.test(value) + ? value + : `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } -/** Remove only the old plugin's direct assignments; unrelated prefixes remain. */ export function cleanupPluginAssignments(options: string): string { const tokens = tokenize(options); - const index = commandIndex(tokens); - const prefixEnd = index >= 0 ? index : tokens.length; - const retained: LaunchToken[] = []; - for (let tokenIndex = 0; tokenIndex < tokens.length; tokenIndex += 1) { - const token = tokens[tokenIndex]; - if (tokenIndex >= prefixEnd || !isAssignment(token)) { - retained.push(token); - continue; - } - const separator = token.value.indexOf("="); - const key = token.value.slice(0, separator); + const command = commandIndex(tokens); + const prefixEnd = command >= 0 ? command : tokens.length; + return serialize(tokens.flatMap((token, i) => { + if (i >= prefixEnd || !isAssignment(token)) return [token]; + const split = token.value.indexOf("="); + const key = token.value.slice(0, split); if (key === "DXVK_CONFIG") { - const cleaned = cleanDxvkConfigValue(token.value.slice(separator + 1)); - if (cleaned) retained.push({ raw: `DXVK_CONFIG=${encodeAssignmentValue(cleaned)}`, value: `DXVK_CONFIG=${cleaned}` }); - continue; + const value = token.value.slice(split + 1).split(";").map((part) => part.trim()) + .filter((part) => part && !DXVK_FRAME_RATE_SEGMENT.test(part)).join("; "); + return value ? [{ raw: `DXVK_CONFIG=${encodeAssignmentValue(value)}`, value: `DXVK_CONFIG=${value}` }] : []; } - if (!MANAGED_ENV_KEYS.has(key)) retained.push(token); - } - return serialize(retained); + return MANAGED_ENV_KEYS.has(key) ? [] : [token]; + })); } export function cleanupLegacyLaunchOptions(options: string): string { const tokens = tokenize(options); - removeLegacyTokens(tokens); + removeMatchingWrappers(tokens, isLegacyToken); return serialize(tokens); } - -export function cleanupPluginLaunchOptions(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): string { - const tokens = tokenize(options); - removeWrapperTokens(tokens, wrapperPath); - return cleanupPluginAssignments(serialize(tokens)); -} - -export function cleanupLegacyWrapper(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): string { - return cleanupPluginLaunchOptions(options, wrapperPath); -} - +export const cleanupPluginLaunchOptions = (options: string, wrapperPath = DEFAULT_WRAPPER_PATH) => + cleanupPluginAssignments(removeWrapperLaunchOption(options, wrapperPath)); +export const cleanupLegacyWrapper = cleanupPluginLaunchOptions; export function hasWrapperLaunchIntegration(options: string, wrapperPath = DEFAULT_WRAPPER_PATH): boolean { const tokens = tokenize(options); - const index = commandIndex(tokens); - return index > 0 && tokens[index - 1].value === wrapperPath; -} - -function delay(milliseconds: number): Promise { - return new Promise((resolve) => timerHost().setTimeout(resolve, milliseconds)); -} - -async function setSteamLaunchOptions(appId: number, nonSteam: boolean, options: string): Promise { - const apps = getSteamApps(); - const setter = nonSteam ? apps?.SetShortcutLaunchOptions : apps?.SetAppLaunchOptions; - if (!setter) throw new Error(`Steam ${nonSteam ? "shortcut " : ""}launch options API is unavailable`); - await Promise.resolve(setter.call(apps, appId, options)); + const command = commandIndex(tokens); + return command > 0 && tokens[command - 1].value === wrapperPath; } -async function setShortcutExecutable(appId: number, executable: string): Promise { - const apps = getSteamApps(); - if (!apps?.SetShortcutExe) throw new Error("Steam shortcut Target API is unavailable"); - await Promise.resolve(apps.SetShortcutExe.call(apps, appId, executable)); +const queues = new Map>(); +function queued(appId: number, nonSteam: boolean, operation: () => Promise): Promise { + const key = `${nonSteam ? "shortcut" : "app"}:${appId}`; + const previous = queues.get(key) || Promise.resolve(); + const current = previous.catch(() => undefined).then(operation); + const cleanup = current.then( + () => { if (queues.get(key) === cleanup) queues.delete(key); }, + () => { if (queues.get(key) === cleanup) queues.delete(key); }, + ); + queues.set(key, cleanup); + return current; } -async function waitForSnapshot( +async function waitFor( appId: number, nonSteam: boolean, - matches: (snapshot: SteamLaunchOptionsSnapshot) => boolean, + matches: (value: SteamLaunchOptionsSnapshot) => boolean, message: string, ): Promise { const deadline = Date.now() + 5000; let lastError: Error | null = null; while (Date.now() <= deadline) { try { - const snapshot = await readSteamLaunchOptions(appId, nonSteam); - if (matches(snapshot)) return snapshot; - } catch (error) { - lastError = asError(error); - } - if (Date.now() >= deadline) break; - await delay(100); + const value = await readSteamLaunchOptions(appId, nonSteam); + if (matches(value)) return value; + } catch (error) { lastError = asError(error); } + if (Date.now() < deadline) await new Promise((resolve) => timer().set(resolve as () => void, 100)); } - if (lastError) throw new Error(`${message}: ${lastError.message}`); - throw new Error(`${message} before the readback timeout`); + throw lastError ? new Error(`${message}: ${lastError.message}`) : new Error(`${message} before the readback timeout`); } -async function writeLaunchOptionsAndVerify( +async function writeVerified( appId: number, nonSteam: boolean, previous: string, next: string, + write: (value: string) => Promise, + read: (value: SteamLaunchOptionsSnapshot) => string, message: string, ): Promise { + const normalized = read === readOptions ? normalizeLaunchOptions : (value: string) => value; try { - await setSteamLaunchOptions(appId, nonSteam, next); - return await waitForSnapshot( - appId, - nonSteam, - (snapshot) => normalizeLaunchOptions(snapshot.options) === normalizeLaunchOptions(next), - message, - ); - } catch (error) { - const failure = asError(error); - try { - await setSteamLaunchOptions(appId, nonSteam, previous); - await waitForSnapshot( - appId, - nonSteam, - (snapshot) => normalizeLaunchOptions(snapshot.options) === normalizeLaunchOptions(previous), - "Steam did not restore the previous launch options", - ); - } catch (rollbackError) { - throw new Error(`${failure.message}; rollback also failed: ${asError(rollbackError).message}`); - } - throw failure; - } -} - -async function writeShortcutExecutableAndVerify( - appId: number, - previous: string, - next: string, - message: string, -): Promise { - try { - await setShortcutExecutable(appId, next); - return await waitForSnapshot(appId, true, (snapshot) => snapshot.target === next, message); + await write(next); + return await waitFor(appId, nonSteam, (value) => normalized(read(value)) === normalized(next), message); } catch (error) { const failure = asError(error); try { - await setShortcutExecutable(appId, previous); - await waitForSnapshot(appId, true, (snapshot) => snapshot.target === previous, "Steam did not restore the previous shortcut Target"); - } catch (rollbackError) { - throw new Error(`${failure.message}; rollback also failed: ${asError(rollbackError).message}`); + await write(previous); + await waitFor(appId, nonSteam, (value) => normalized(read(value)) === normalized(previous), `Steam did not restore the previous ${read === readOptions ? "launch options" : "shortcut Target"}`); + } catch (rollback) { + throw new Error(`${failure.message}; rollback also failed: ${asError(rollback).message}`); } throw failure; } } -const operationQueues = new Map>(); +const readOptions = (value: SteamLaunchOptionsSnapshot) => value.options; +const readTarget = (value: SteamLaunchOptionsSnapshot) => value.target; -function queueSteamOperation(appId: number, nonSteam: boolean, operation: () => Promise): Promise { - const key = `${nonSteam ? "shortcut" : "app"}:${appId}`; - const previous = operationQueues.get(key) || Promise.resolve(); - const queued = previous.catch(() => undefined).then(operation); - const cleanup = queued.then( - () => { if (operationQueues.get(key) === cleanup) operationQueues.delete(key); }, - () => { if (operationQueues.get(key) === cleanup) operationQueues.delete(key); }, - ); - operationQueues.set(key, cleanup); - return queued; +function writeOptions(appId: number, nonSteam: boolean, value: string): Promise { + const setter = nonSteam ? apps()?.SetShortcutLaunchOptions : apps()?.SetAppLaunchOptions; + if (!setter) return Promise.reject(new Error(`Steam ${nonSteam ? "shortcut " : ""}launch options API is unavailable`)); + return Promise.resolve(setter.call(apps(), appId, value)); +} +function writeTarget(appId: number, value: string): Promise { + const setter = apps()?.SetShortcutExe; + if (!setter) return Promise.reject(new Error("Steam shortcut Target API is unavailable")); + return Promise.resolve(setter.call(apps(), appId, value)); } export function updateSteamLaunchOptions( @@ -501,11 +320,14 @@ export function updateSteamLaunchOptions( nonSteam: boolean, transform: (options: string) => string, ): Promise { - return queueSteamOperation(appId, nonSteam, async () => { + return queued(appId, nonSteam, async () => { const current = await readSteamLaunchOptions(appId, nonSteam); const next = transform(current.options); - if (next === current.options) return current; - return writeLaunchOptionsAndVerify(appId, nonSteam, current.options, next, "Steam did not accept the launch options"); + return next === current.options ? current : writeVerified( + appId, nonSteam, current.options, next, + (value) => writeOptions(appId, nonSteam, value), readOptions, + "Steam did not accept the launch options", + ); }); } @@ -515,33 +337,41 @@ export function installWrapperIntegration( wrapperPath: string, commandTokenAdded = false, ): Promise { - return queueSteamOperation(appId, nonSteam, async () => { - const current = await readSteamLaunchOptions(appId, nonSteam); + return queued(appId, nonSteam, async () => { + let current = await readSteamLaunchOptions(appId, nonSteam); if (nonSteam) { if (!current.target) throw new Error("Steam shortcut Target is empty; refusing to replace it"); if (current.target !== wrapperPath && isWrapperToken(current.target, wrapperPath)) { throw new Error("The shortcut Target points to a legacy frame-generation wrapper; restore it first"); } - const cleanedOptions = cleanupPluginLaunchOptions(current.options, wrapperPath); - if (cleanedOptions !== current.options) { - await writeLaunchOptionsAndVerify(appId, true, current.options, cleanedOptions, "Steam did not accept shortcut launch options"); - } - if (current.target === wrapperPath) { - return { snapshot: await readSteamLaunchOptions(appId, true), originalExecutable: undefined, commandTokenAdded: false }; + const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); + if (cleaned !== current.options) { + current = await writeVerified( + appId, true, current.options, cleaned, + (value) => writeOptions(appId, true, value), readOptions, + "Steam did not accept shortcut launch options", + ); } + if (current.target === wrapperPath) return { snapshot: current, commandTokenAdded: false }; const originalExecutable = current.target; - const snapshot = await writeShortcutExecutableAndVerify(appId, originalExecutable, wrapperPath, "Steam did not accept the shortcut Target"); - return { snapshot, originalExecutable, commandTokenAdded: false }; + const value = await writeVerified( + appId, true, originalExecutable, wrapperPath, + (target) => writeTarget(appId, target), readTarget, + "Steam did not accept the shortcut Target", + ); + return { snapshot: value, originalExecutable, commandTokenAdded: false }; } const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); const alreadyInstalled = hasWrapperLaunchIntegration(current.options, wrapperPath); const rewrite = installWrapperLaunchOption(cleaned, wrapperPath); - if (rewrite.options === current.options) { - return { snapshot: current, commandTokenAdded }; - } - const snapshot = await writeLaunchOptionsAndVerify(appId, false, current.options, rewrite.options, "Steam did not accept the launch options"); - return { snapshot, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded }; + if (rewrite.options === current.options) return { snapshot: current, commandTokenAdded }; + const value = await writeVerified( + appId, false, current.options, rewrite.options, + (options) => writeOptions(appId, false, options), readOptions, + "Steam did not accept the launch options", + ); + return { snapshot: value, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded }; }); } @@ -552,8 +382,8 @@ export function removeWrapperIntegration( originalExecutable?: string, commandTokenAdded = false, ): Promise { - return queueSteamOperation(appId, nonSteam, async () => { - const current = await readSteamLaunchOptions(appId, nonSteam); + return queued(appId, nonSteam, async () => { + let current = await readSteamLaunchOptions(appId, nonSteam); if (nonSteam) { if (!originalExecutable || isWrapperToken(originalExecutable, wrapperPath)) { throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); @@ -563,34 +393,32 @@ export function removeWrapperIntegration( } const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); if (cleaned !== current.options) { - await writeLaunchOptionsAndVerify(appId, true, current.options, cleaned, "Steam did not clean shortcut launch options"); + current = await writeVerified( + appId, true, current.options, cleaned, + (value) => writeOptions(appId, true, value), readOptions, + "Steam did not clean shortcut launch options", + ); } - if (current.target === originalExecutable) { - return readSteamLaunchOptions(appId, true); - } - return writeShortcutExecutableAndVerify(appId, wrapperPath, originalExecutable, "Steam did not restore the shortcut Target"); + if (current.target === originalExecutable) return current; + return writeVerified( + appId, true, wrapperPath, originalExecutable, + (target) => writeTarget(appId, target), readTarget, + "Steam did not restore the shortcut Target", + ); } - - const withoutWrapper = removeWrapperLaunchOption(current.options, wrapperPath, commandTokenAdded); - const next = cleanupPluginAssignments(withoutWrapper); - if (next === current.options) return current; - return writeLaunchOptionsAndVerify(appId, false, current.options, next, "Steam did not clean the launch options"); + const next = cleanupPluginAssignments(removeWrapperLaunchOption(current.options, wrapperPath, commandTokenAdded)); + return next === current.options ? current : writeVerified( + appId, false, current.options, next, + (options) => writeOptions(appId, false, options), readOptions, + "Steam did not clean the launch options", + ); }); } -export function cleanupLegacySteamLaunchOptions( +export const cleanupLegacySteamLaunchOptions = ( appId: number, nonSteam: boolean, wrapperPath = DEFAULT_WRAPPER_PATH, -): Promise { - return queueSteamOperation(appId, nonSteam, async () => { - const current = await readSteamLaunchOptions(appId, nonSteam); - const next = cleanupPluginLaunchOptions(current.options, wrapperPath); - if (next === current.options) return current; - return writeLaunchOptionsAndVerify(appId, nonSteam, current.options, next, "Steam did not clean legacy launch options"); - }); -} +) => updateSteamLaunchOptions(appId, nonSteam, (options) => cleanupPluginLaunchOptions(options, wrapperPath)); -export function getDefaultWrapperPath(): string { - return DEFAULT_WRAPPER_PATH; -} +export const getDefaultWrapperPath = () => DEFAULT_WRAPPER_PATH; diff --git a/src/utils/toastUtils.ts b/src/utils/toastUtils.ts index cbbbc55..3468064 100644 --- a/src/utils/toastUtils.ts +++ b/src/utils/toastUtils.ts @@ -1,8 +1,3 @@ -/** - * Centralized toast notification utilities - * Provides consistent success/error messaging patterns - */ - import { toaster } from "@decky/api"; export interface ToastOptions { @@ -10,84 +5,44 @@ export interface ToastOptions { body: string; } -/** - * Show a success toast notification - */ -export function showSuccessToast(title: string, body: string): void { - toaster.toast({ - title, - body - }); -} +const showToast = (title: string, body: string): void => toaster.toast({ title, body }); +export const showSuccessToast = showToast; +export const showErrorToast = showToast; -/** - * Show an error toast notification - */ -export function showErrorToast(title: string, body: string): void { - toaster.toast({ - title, - body - }); -} - -/** - * Standard success messages for common operations - */ export const ToastMessages = { INSTALL_SUCCESS: { title: "Installation Complete", - body: "lsfg-vk has been installed successfully" + body: "lsfg-vk has been installed successfully", }, INSTALL_ERROR: { title: "Installation Failed", - body: "Unknown error occurred" + body: "Unknown error occurred", }, UNINSTALL_SUCCESS: { - title: "Uninstallation Complete", - body: "lsfg-vk has been uninstalled successfully" + title: "Uninstallation Complete", + body: "lsfg-vk has been uninstalled successfully", }, UNINSTALL_ERROR: { title: "Uninstallation Failed", - body: "Unknown error occurred" + body: "Unknown error occurred", }, CONFIG_UPDATE_ERROR: { title: "Update Failed", - body: "Failed to update configuration" - } + body: "Failed to update configuration", + }, } as const; -/** - * Show a toast with dynamic error message - */ -export function showErrorToastWithMessage(title: string, error: unknown): void { - const errorMessage = error instanceof Error ? error.message : String(error); - showErrorToast(title, errorMessage); -} +export const showErrorToastWithMessage = (title: string, error: unknown): void => + showErrorToast(title, error instanceof Error ? error.message : String(error)); -/** - * Show installation success toast - */ -export function showInstallSuccessToast(): void { +export const showInstallSuccessToast = (): void => showSuccessToast(ToastMessages.INSTALL_SUCCESS.title, ToastMessages.INSTALL_SUCCESS.body); -} -/** - * Show installation error toast - */ -export function showInstallErrorToast(error?: string): void { +export const showInstallErrorToast = (error?: string): void => showErrorToast(ToastMessages.INSTALL_ERROR.title, error || ToastMessages.INSTALL_ERROR.body); -} -/** - * Show uninstallation success toast - */ -export function showUninstallSuccessToast(): void { +export const showUninstallSuccessToast = (): void => showSuccessToast(ToastMessages.UNINSTALL_SUCCESS.title, ToastMessages.UNINSTALL_SUCCESS.body); -} -/** - * Show uninstallation error toast - */ -export function showUninstallErrorToast(error?: string): void { +export const showUninstallErrorToast = (error?: string): void => showErrorToast(ToastMessages.UNINSTALL_ERROR.title, error || ToastMessages.UNINSTALL_ERROR.body); -} -- cgit v1.2.3 From 6a927e30f743fac0a5451381ceed7f1d83e94a37 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 07:47:39 -0400 Subject: fix: clean up simple migration type errors --- src/hooks/useLsfgHooks.ts | 4 ++-- src/utils/toastUtils.ts | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index 73cfa0c..9beb749 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -57,7 +57,7 @@ export function useInstallation(reloadConfig?: () => Promise) { const result = await installLsfgVk(); if (!result.success) { setInstallationStatus(`Installation failed: ${result.error}`); - showInstallErrorToast(result.error); + showInstallErrorToast(result.error ?? undefined); return; } setIsInstalled(true); @@ -80,7 +80,7 @@ export function useInstallation(reloadConfig?: () => Promise) { const result = await uninstallLsfgVk(); if (!result.success) { setInstallationStatus(`Uninstallation failed: ${result.error}`); - showUninstallErrorToast(result.error); + showUninstallErrorToast(result.error ?? undefined); return; } setIsInstalled(false); diff --git a/src/utils/toastUtils.ts b/src/utils/toastUtils.ts index 3468064..c41f4c0 100644 --- a/src/utils/toastUtils.ts +++ b/src/utils/toastUtils.ts @@ -5,7 +5,9 @@ export interface ToastOptions { body: string; } -const showToast = (title: string, body: string): void => toaster.toast({ title, body }); +const showToast = (title: string, body: string): void => { + toaster.toast({ title, body }); +}; export const showSuccessToast = showToast; export const showErrorToast = showToast; -- cgit v1.2.3 From 840ea2802551a786de9b59f7aa00f04c5f335e2a Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 07:57:03 -0400 Subject: fix: keep Flatpak runtime controls simple --- src/components/Content.tsx | 1 - src/components/SetupTab.tsx | 26 +++++++++----------------- 2 files changed, 9 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index d92ef86..e5216ca 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -91,7 +91,6 @@ export function Content() { isUninstalling={isUninstalling} onInstall={() => void install()} onUninstall={() => void uninstall()} - flatpakRelevant={targets.some((target) => target.transport.kind === "flatpak")} /> ); diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index e936049..624be54 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -19,12 +19,10 @@ interface SetupTabProps { isUninstalling: boolean; onInstall: () => void; onUninstall: () => void; - flatpakRelevant: boolean; } -function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { +function FlatpakSupportDiagnostics() { const [status, setStatus] = useState(null); - const [advanced, setAdvanced] = useState(false); const [operation, setOperation] = useState(null); const refresh = async () => { @@ -44,10 +42,10 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { }; useEffect(() => { - if (relevant) void refresh(); - }, [relevant]); + void refresh(); + }, []); - if (!relevant || !status?.available) return null; + if (!status?.available) return null; const setEnabled = async (branch: string, enabled: boolean) => { setOperation(`${enabled ? "enable" : "disable"}-${branch}`); @@ -63,19 +61,14 @@ function FlatpakSupportDiagnostics({ relevant }: { relevant: boolean }) { }; return ( - + - - setAdvanced((value) => !value)}> - {advanced ? "Hide runtime details" : "Show runtime details"} - - - {advanced && status.supported_branches.map((branch) => { + {status.supported_branches.map((branch) => { const installed = status.installed_branches.includes(branch); const pending = operation?.endsWith(`-${branch}`); return ( @@ -105,7 +98,6 @@ export function SetupTab(props: SetupTabProps) { isUninstalling, onInstall, onUninstall, - flatpakRelevant, } = props; const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; const buttonLabel = isInstalling @@ -146,7 +138,7 @@ export function SetupTab(props: SetupTabProps) { - + ); } -- cgit v1.2.3 From e6efa4f0ff32d520982860180a29472068aab8e2 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 09:53:55 -0400 Subject: simplify unhooked game behavior on mount --- src/components/ConfigurationTab.tsx | 14 ------------- src/components/Content.tsx | 9 ++++---- src/components/NowPlayingTab.tsx | 42 ++++++------------------------------- 3 files changed, 10 insertions(+), 55 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 8f8690c..8150819 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -37,7 +37,6 @@ export function ConfigurationTab({ const [focusDetailAction, setFocusDetailAction] = useState<"enable" | "fps" | null>(null); const [focusConfiguredToggle, setFocusConfiguredToggle] = useState(false); const enableRef = useRef(null); - const promptedRunningAppId = useRef(null); const closeDetails = useCallback(() => { setFocusFpsMultiplier(false); setFocusDetailAction(null); @@ -60,18 +59,6 @@ export function ConfigurationTab({ return () => cancelAnimationFrame(frame); }, [focusDetailAction]); - useEffect(() => { - if (!runningGame || runningGame.configured) { - promptedRunningAppId.current = null; - return; - } - if (promptedRunningAppId.current !== runningGame.appid && detailAppId === null) { - promptedRunningAppId.current = runningGame.appid; - setFocusDetailAction("enable"); - setDetailAppId(runningGame.appid); - } - }, [detailAppId, runningGame?.appid, runningGame?.configured]); - const selectedTarget = detailAppId ? targets.find((target) => target.appid === detailAppId) : null; if (detailAppId === null) { @@ -106,7 +93,6 @@ export function ConfigurationTab({ : "Game is no longer available"; const handleProfileAction = async () => { if (selectedTarget?.configured) { - promptedRunningAppId.current = detailAppId; await onReset(); setFocusConfiguredToggle(true); closeDetails(); diff --git a/src/components/Content.tsx b/src/components/Content.tsx index e5216ca..578f984 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -56,15 +56,15 @@ export function Content() { setTab("Setup"); return; } - setTab((current) => current === "Setup" ? (runningGame ? "NowPlaying" : "Games") : current); - }, [runningGame?.appid, setupComplete]); + setTab((current) => current === "Setup" ? (runningGame?.configured ? "NowPlaying" : "Games") : current); + }, [runningGame?.appid, runningGame?.configured, setupComplete]); useEffect(() => { if (!setupComplete) return; const appid = runningGame?.appid || null; const previous = previousRunningAppId.current; previousRunningAppId.current = appid; - if (appid && appid !== previous) setTab("NowPlaying"); + if (appid && appid !== previous) setTab(runningGame?.configured ? "NowPlaying" : "Games"); else if (!appid && previous) { setTab((current) => current === "NowPlaying" ? "Games" : current); } @@ -96,7 +96,7 @@ export function Content() { const tabs = setupComplete ? [ - ...(runningGame ? [{ + ...(runningGame?.configured ? [{ id: "NowPlaying", title: tabIcons.nowPlaying, content: ( @@ -104,7 +104,6 @@ export function Content() { game={runningGame} config={config} onConfigChange={(field, value) => handleConfigChange(field, value)} - onEnable={enable} onRepair={repair} /> ), diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index 5bce5c4..57858db 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -11,7 +11,6 @@ interface Props { fieldName: keyof ConfigurationData, value: boolean | number | string | string[], ) => Promise; - onEnable: (appid: string) => Promise; onRepair: (appid: string) => Promise; } @@ -24,25 +23,13 @@ export function NowPlayingTab({ game, config, onConfigChange, - onEnable, onRepair, }: Props) { const [busy, setBusy] = useState(false); const supportNeedsRepair = - game.configured && game.transport.kind === "flatpak" && game.flatpakSupport?.support_status !== "ready"; - const handleEnable = async () => { - if (busy) return; - setBusy(true); - try { - await onEnable(game.appid); - } finally { - setBusy(false); - } - }; - const handleRepair = async () => { if (busy) return; setBusy(true); @@ -60,22 +47,7 @@ export function NowPlayingTab({ - {!game.configured && ( - - - - - - void handleEnable()}> - {busy ? "Enabling..." : "Enable LSFG-VK"} - - - - )} - {game.configured && supportNeedsRepair && ( + {supportNeedsRepair && ( )} - {game.configured && ( - - )} + ); } -- cgit v1.2.3 From 209ab92cc3baeb15ce808fc53ce9041a761d8df4 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 10:33:08 -0400 Subject: only warn quit on real steam games --- src/components/ConfigurationTab.tsx | 30 +++++++++++++++++++++++++++--- src/types.d.ts | 1 + 2 files changed, 28 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 8150819..5ae4a87 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,4 +1,4 @@ -import { ButtonItem, DialogButton, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses } from "@decky/ui"; +import { ButtonItem, ConfirmModal, DialogButton, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses, showModal } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; @@ -91,13 +91,37 @@ export function ConfigurationTab({ const profileDescription = selectedTarget ? `${profileTransport} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}` : "Game is no longer available"; + const enableProfile = async (appid: string, quitRunningGame = false) => { + if (!(await onEnable(appid))) return; + if (quitRunningGame) SteamClient.Apps.TerminateApp(appid, false); + setFocusFpsMultiplier(true); + }; const handleProfileAction = async () => { if (selectedTarget?.configured) { await onReset(); setFocusConfiguredToggle(true); closeDetails(); - } else if (detailAppId && await onEnable(detailAppId)) { - setFocusFpsMultiplier(true); + } else if (detailAppId) { + const isRunningUnconfigured = runningGame?.appid === detailAppId + && runningGame.nonSteam === false + && runningGame.transport.kind === "host" + && selectedTarget?.nonSteam === false + && selectedTarget?.transport.kind === "host" + && !runningGame.configured; + if (isRunningUnconfigured) { + showModal( + void enableProfile(detailAppId, true)} + onCancel={() => void enableProfile(detailAppId)} + />, + ); + } else { + await enableProfile(detailAppId); + } } }; diff --git a/src/types.d.ts b/src/types.d.ts index df433e0..e5db40d 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -32,6 +32,7 @@ interface SteamApps { SetAppLaunchOptions(appId: number, options: string): void | Promise; SetShortcutLaunchOptions(appId: number, options: string): void | Promise; SetShortcutExe(appId: number, executable: string): void | Promise; + TerminateApp(appId: string, param1: boolean): void; GetAllShortcuts?(): Promise; } -- cgit v1.2.3 From b197e25b45d53c6c7175a45dd0b14642f2aab198 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 11:51:22 -0400 Subject: fixes for appimage and flatpak --- src/components/SetupTab.tsx | 128 ++++++++------------------------------ src/hooks/useGameConfiguration.ts | 39 +++++++----- src/hooks/usePerAppWorkarounds.ts | 35 +++++++---- src/utils/steamLaunchOptions.ts | 24 ++++--- 4 files changed, 87 insertions(+), 139 deletions(-) (limited to 'src') diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index 624be54..d769200 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,13 +1,6 @@ -import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; -import { useEffect, useState } from "react"; -import { - getFlatpakSupportStatus, - setFlatpakExtensionEnabled, - type FlatpakExtensionStatus, - type SteamBranchStatus, -} from "../api/lsfgApi"; +import { ButtonItem, Field, PanelSection, PanelSectionRow } from "@decky/ui"; +import { type SteamBranchStatus } from "../api/lsfgApi"; import t from "../i18n/i18n"; -import { showErrorToast } from "../utils/toastUtils"; interface SetupTabProps { isInstalled: boolean; @@ -21,72 +14,6 @@ interface SetupTabProps { onUninstall: () => void; } -function FlatpakSupportDiagnostics() { - const [status, setStatus] = useState(null); - const [operation, setOperation] = useState(null); - - const refresh = async () => { - try { - setStatus(await getFlatpakSupportStatus()); - } catch (error) { - setStatus({ - success: false, - message: "", - error: String(error), - available: false, - extension_id: "", - supported_branches: [], - installed_branches: [], - }); - } - }; - - useEffect(() => { - void refresh(); - }, []); - - if (!status?.available) return null; - - const setEnabled = async (branch: string, enabled: boolean) => { - setOperation(`${enabled ? "enable" : "disable"}-${branch}`); - try { - const result = await setFlatpakExtensionEnabled(branch, enabled); - if (!result.success) throw new Error(result.error || result.message || "Flatpak runtime update failed"); - await refresh(); - } catch (error) { - showErrorToast("Flatpak runtime update failed", String(error)); - } finally { - setOperation(null); - } - }; - - return ( - - - - - {status.supported_branches.map((branch) => { - const installed = status.installed_branches.includes(branch); - const pending = operation?.endsWith(`-${branch}`); - return ( - - void setEnabled(branch, enabled)} - disabled={operation !== null} - /> - - ); - })} - - ); -} - export function SetupTab(props: SetupTabProps) { const { isInstalled, @@ -109,36 +36,33 @@ export function SetupTab(props: SetupTabProps) { : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); return ( - <> - + + + + + + + + {steamBranchStatus?.installed && ( - - - - {steamBranchStatus?.installed && ( - - - - )} - - - {buttonLabel} - - - - - + )} + + + {buttonLabel} + + + ); } diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index c70d589..e120426 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -48,11 +48,6 @@ function selectShortcutExecutable( .map((candidate) => candidate?.trim()) .find((candidate) => candidate && candidate.startsWith("/")); if (absolute) return absolute; - - // Steam's app-details API can report a Flatpak Target as just "flatpak" - // even when the shortcut's canonical VDF executable is /usr/bin/flatpak. - // Keep the stored original executable absolute so SetShortcutExe and the - // generated dispatcher agree on the same direct transport. if (target.transport.kind === "flatpak") return "/usr/bin/flatpak"; return candidates.map((candidate) => candidate?.trim()).find(Boolean); } @@ -158,25 +153,26 @@ export function useGameConfiguration() { const oldShortcutExe = existing.shortcut_exe || undefined; const oldCommandTokenAdded = existing.command_token_added === true; const oldTransport = existing.transport || target.transport; - if (target.nonSteam && oldState && current.target === wrapperPath && !oldShortcutExe) { + const usesShortcutTarget = target.nonSteam && target.transport.kind === "flatpak"; + if (usesShortcutTarget && oldState && current.target === wrapperPath && !oldShortcutExe) { throw new Error("Managed shortcut Target has no saved original executable"); } - if (target.nonSteam && oldState && current.target !== wrapperPath && current.target !== oldShortcutExe) { + if (usesShortcutTarget && oldState && current.target !== wrapperPath && current.target !== oldShortcutExe) { throw new Error("Shortcut Target changed externally; refusing to replace it"); } - if (target.nonSteam && !oldState && current.target === wrapperPath) { + if (usesShortcutTarget && !oldState && current.target === wrapperPath) { throw new Error("Shortcut Target is already the managed wrapper but its original Target is unknown"); } const state = oldState || { ...DEFAULT_WORKAROUND_STATE }; - const originalExecutable = target.nonSteam + const originalExecutable = usesShortcutTarget ? selectShortcutExecutable( target, oldShortcutExe, - target.transport.kind === "flatpak" ? target.executable : undefined, + target.executable, current.target, ) : undefined; - const initialIntegration = target.nonSteam + const initialIntegration = usesShortcutTarget ? current.target === wrapperPath : hasWrapperLaunchIntegration(current.options, wrapperPath); const initialStateResult = await setWorkaroundState( @@ -190,16 +186,22 @@ export function useGameConfiguration() { let integration: Awaited> | null = null; try { - integration = await installWrapperIntegration(appId, target.nonSteam, wrapperPath, oldCommandTokenAdded); + integration = await installWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + oldCommandTokenAdded, + target.transport.kind, + ); const finalStateResult = await setWorkaroundState( target.appid, state, - target.nonSteam + usesShortcutTarget ? (selectShortcutExecutable( target, integration.originalExecutable, originalExecutable, - target.transport.kind === "flatpak" ? target.executable : undefined, + target.executable, ) || null) : null, integration.commandTokenAdded, @@ -215,15 +217,16 @@ export function useGameConfiguration() { appId, target.nonSteam, wrapperPath, - target.nonSteam + usesShortcutTarget ? (selectShortcutExecutable( target, integration?.originalExecutable, originalExecutable, - target.transport.kind === "flatpak" ? target.executable : undefined, + target.executable, ) || undefined) : undefined, integration?.commandTokenAdded ?? oldCommandTokenAdded, + target.transport.kind, ); } catch (rollbackError) { showErrorToast("Workaround rollback failed", asError(rollbackError).message); @@ -257,6 +260,7 @@ export function useGameConfiguration() { const existing = await getWorkaroundState(target.appid); if (!existing.success) throw new Error(existing.error || "Could not read workaround state"); const wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); + const usesShortcutTarget = target.nonSteam && target.transport.kind === "flatpak"; if (existing.state) { await removeWrapperIntegration( appId, @@ -264,10 +268,11 @@ export function useGameConfiguration() { wrapperPath, existing.shortcut_exe || undefined, existing.command_token_added === true, + target.transport.kind, ); } else { const current = await readSteamLaunchOptions(appId, target.nonSteam); - if (target.nonSteam && (current.target === wrapperPath || isLegacyWrapperToken(current.target))) { + if (usesShortcutTarget && (current.target === wrapperPath || isLegacyWrapperToken(current.target))) { throw new Error("Shortcut Target is a frame-generation wrapper but its original Target is unknown"); } await cleanupLegacySteamLaunchOptions(appId, target.nonSteam, wrapperPath); diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index e9e44e1..ebb12e2 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -73,22 +73,31 @@ function selectShortcutExecutable( return candidates.map((candidate) => candidate?.trim()).find(Boolean); } +function usesShortcutTarget(nonSteam: boolean, transport: TargetTransport): boolean { + return nonSteam && transport.kind === "flatpak"; +} + function integrationIsInstalled( steam: SteamLaunchOptionsSnapshot, nonSteam: boolean, + transport: TargetTransport, wrapperPath: string, ): boolean { - return nonSteam ? steam.target === wrapperPath : hasWrapperLaunchIntegration(steam.options, wrapperPath); + return usesShortcutTarget(nonSteam, transport) + ? steam.target === wrapperPath + : hasWrapperLaunchIntegration(steam.options, wrapperPath); } function makeSnapshot( steam: SteamLaunchOptionsSnapshot, result: Awaited>, nonSteam: boolean, + transport: TargetTransport, ): WorkaroundSnapshot { if (!result.state) throw new Error("Workaround state is not initialized for this profile"); const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); - if (nonSteam && steam.target === wrapperPath && !result.shortcut_exe) { + const selectedTransport = result.transport || transport; + if (usesShortcutTarget(nonSteam, selectedTransport) && steam.target === wrapperPath && !result.shortcut_exe) { throw new Error("Managed shortcut Target has no saved original executable"); } return { @@ -96,10 +105,10 @@ function makeSnapshot( state: result.state, wrapperPath, wrapperOwned: result.wrapper_owned === true, - integrationInstalled: integrationIsInstalled(steam, nonSteam, wrapperPath), + integrationInstalled: integrationIsInstalled(steam, nonSteam, selectedTransport, wrapperPath), commandTokenAdded: result.command_token_added === true, shortcutExe: result.shortcut_exe, - transport: result.transport || { kind: "host" }, + transport: selectedTransport, }; } @@ -110,10 +119,11 @@ async function adoptWorkaroundState( steam: SteamLaunchOptionsSnapshot, wrapperPath: string, ): Promise { - if (nonSteam && (!steam.target || steam.target === wrapperPath || isLegacyWrapperToken(steam.target))) { + const shortcutTarget = usesShortcutTarget(nonSteam, transport); + if (shortcutTarget && (!steam.target || steam.target === wrapperPath || isLegacyWrapperToken(steam.target))) { throw new Error("Shortcut Target is a wrapper but its original Target is unknown"); } - const originalExecutable = nonSteam + const originalExecutable = shortcutTarget ? selectShortcutExecutable(transport, steam.target) : null; const initial = await setWorkaroundState( @@ -130,18 +140,20 @@ async function adoptWorkaroundState( Number(appId), nonSteam, wrapperPath, + false, + transport.kind, ); const finalized = await setWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, - nonSteam + shortcutTarget ? (selectShortcutExecutable(transport, integration.originalExecutable, originalExecutable) || null) : null, integration.commandTokenAdded, transport, ); if (!finalized.success) throw new Error(finalized.error || "Could not finalize workaround state"); - return makeSnapshot(integration.snapshot, finalized, nonSteam); + return makeSnapshot(integration.snapshot, finalized, nonSteam, transport); } catch (error) { let rollbackSucceeded = true; if (integration) { @@ -150,10 +162,11 @@ async function adoptWorkaroundState( Number(appId), nonSteam, wrapperPath, - nonSteam + shortcutTarget ? (selectShortcutExecutable(transport, integration?.originalExecutable, originalExecutable) || undefined) : undefined, integration?.commandTokenAdded ?? false, + transport.kind, ); } catch { // Leave the owned integration in place rather than guessing at cleanup. @@ -194,7 +207,7 @@ export function usePerAppWorkarounds( result.wrapper_path || getDefaultWrapperPath(), ); } - return makeSnapshot(steam, result, nonSteam); + return makeSnapshot(steam, result, nonSteam, transport); }, [appId, nonSteam, numericAppId, transport]); const applySnapshot = useCallback((next: WorkaroundSnapshot) => { @@ -230,7 +243,7 @@ export function usePerAppWorkarounds( setSnapshot((current) => current ? { ...current, steam, - integrationInstalled: integrationIsInstalled(steam, nonSteam, current.wrapperPath), + integrationInstalled: integrationIsInstalled(steam, nonSteam, current.transport, current.wrapperPath), } : current); }, (subscriptionError) => { diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 0af1bbf..65541d8 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -172,7 +172,11 @@ function removeMatchingWrappers(tokens: LaunchToken[], predicate: (value: string return true; } -export function installWrapperLaunchOption(options: string, wrapperPath = DEFAULT_WRAPPER_PATH) { +export function installWrapperLaunchOption( + options: string, + wrapperPath = DEFAULT_WRAPPER_PATH, + allowCommandArgs = false, +) { const tokens = tokenize(options); removeMatchingWrappers(tokens, isLegacyToken); let command = commandIndex(tokens); @@ -185,7 +189,7 @@ export function installWrapperLaunchOption(options: string, wrapperPath = DEFAUL } let insertion = 0; while (insertion < tokens.length && isAssignment(tokens[insertion])) insertion++; - if (insertion < tokens.length && !tokens[insertion].value.startsWith("-")) { + if (!allowCommandArgs && insertion < tokens.length && !tokens[insertion].value.startsWith("-")) { throw new Error("Launch options do not contain %command%; refusing to guess a launcher command"); } tokens.splice(insertion, 0, @@ -336,10 +340,11 @@ export function installWrapperIntegration( nonSteam: boolean, wrapperPath: string, commandTokenAdded = false, + transport: "host" | "flatpak" = "host", ): Promise { return queued(appId, nonSteam, async () => { let current = await readSteamLaunchOptions(appId, nonSteam); - if (nonSteam) { + if (nonSteam && transport === "flatpak") { if (!current.target) throw new Error("Steam shortcut Target is empty; refusing to replace it"); if (current.target !== wrapperPath && isWrapperToken(current.target, wrapperPath)) { throw new Error("The shortcut Target points to a legacy frame-generation wrapper; restore it first"); @@ -364,11 +369,11 @@ export function installWrapperIntegration( const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); const alreadyInstalled = hasWrapperLaunchIntegration(current.options, wrapperPath); - const rewrite = installWrapperLaunchOption(cleaned, wrapperPath); + const rewrite = installWrapperLaunchOption(cleaned, wrapperPath, nonSteam); if (rewrite.options === current.options) return { snapshot: current, commandTokenAdded }; const value = await writeVerified( - appId, false, current.options, rewrite.options, - (options) => writeOptions(appId, false, options), readOptions, + appId, nonSteam, current.options, rewrite.options, + (options) => writeOptions(appId, nonSteam, options), readOptions, "Steam did not accept the launch options", ); return { snapshot: value, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded }; @@ -381,10 +386,11 @@ export function removeWrapperIntegration( wrapperPath: string, originalExecutable?: string, commandTokenAdded = false, + transport: "host" | "flatpak" = "host", ): Promise { return queued(appId, nonSteam, async () => { let current = await readSteamLaunchOptions(appId, nonSteam); - if (nonSteam) { + if (nonSteam && transport === "flatpak") { if (!originalExecutable || isWrapperToken(originalExecutable, wrapperPath)) { throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); } @@ -408,8 +414,8 @@ export function removeWrapperIntegration( } const next = cleanupPluginAssignments(removeWrapperLaunchOption(current.options, wrapperPath, commandTokenAdded)); return next === current.options ? current : writeVerified( - appId, false, current.options, next, - (options) => writeOptions(appId, false, options), readOptions, + appId, nonSteam, current.options, next, + (options) => writeOptions(appId, nonSteam, options), readOptions, "Steam did not clean the launch options", ); }); -- cgit v1.2.3 From 670f36e8cc75da9c8b1b174c24e722657bbf2a56 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 12:15:05 -0400 Subject: cleanup flatpak handles --- src/hooks/useGameConfiguration.ts | 176 +++++++++++--------------------------- src/hooks/usePerAppWorkarounds.ts | 83 ++++-------------- src/utils/steamLaunchOptions.ts | 95 +++++++++++++++----- 3 files changed, 143 insertions(+), 211 deletions(-) (limited to 'src') diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index e120426..3260019 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -3,7 +3,7 @@ import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; import { ensureFlatpakSupport, getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, repairFlatpakSupport, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; -import { cleanupLegacySteamLaunchOptions, getDefaultWrapperPath, hasWrapperLaunchIntegration, installWrapperIntegration, isLegacyWrapperToken, readSteamLaunchOptions, removeWrapperIntegration } from "../utils/steamLaunchOptions"; +import { getDefaultWrapperPath, installWrapperIntegration, removeWrapperIntegration } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; export interface GameTarget extends InstalledGame { configured: boolean; } @@ -40,18 +40,6 @@ function mergeInstalledGames(backendGames: InstalledGame[], shortcutGames: Insta return Array.from(games.values()); } -function selectShortcutExecutable( - target: GameTarget, - ...candidates: Array -): string | undefined { - const absolute = candidates - .map((candidate) => candidate?.trim()) - .find((candidate) => candidate && candidate.startsWith("/")); - if (absolute) return absolute; - if (target.transport.kind === "flatpak") return "/usr/bin/flatpak"; - return candidates.map((candidate) => candidate?.trim()).find(Boolean); -} - const DEFAULT_WORKAROUND_STATE: WorkaroundState = { dxvkFrameRate: 0, disableGamescopeWsi: true, @@ -144,110 +132,59 @@ export function useGameConfiguration() { const ensureTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; const appId = Number(target.appid); + let integration: Awaited> | null = null; + let newState = false; + let stateWriteAttempted = false; + let wrapperPath = getDefaultWrapperPath(); try { const existing = await getWorkaroundState(target.appid); if (!existing.success) throw new Error(existing.error || "Could not read workaround state"); - const current = await readSteamLaunchOptions(appId, target.nonSteam); - const wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); - const oldState = existing.state; - const oldShortcutExe = existing.shortcut_exe || undefined; - const oldCommandTokenAdded = existing.command_token_added === true; - const oldTransport = existing.transport || target.transport; - const usesShortcutTarget = target.nonSteam && target.transport.kind === "flatpak"; - if (usesShortcutTarget && oldState && current.target === wrapperPath && !oldShortcutExe) { - throw new Error("Managed shortcut Target has no saved original executable"); - } - if (usesShortcutTarget && oldState && current.target !== wrapperPath && current.target !== oldShortcutExe) { - throw new Error("Shortcut Target changed externally; refusing to replace it"); - } - if (usesShortcutTarget && !oldState && current.target === wrapperPath) { - throw new Error("Shortcut Target is already the managed wrapper but its original Target is unknown"); - } - const state = oldState || { ...DEFAULT_WORKAROUND_STATE }; - const originalExecutable = usesShortcutTarget - ? selectShortcutExecutable( - target, - oldShortcutExe, - target.executable, - current.target, - ) - : undefined; - const initialIntegration = usesShortcutTarget - ? current.target === wrapperPath - : hasWrapperLaunchIntegration(current.options, wrapperPath); - const initialStateResult = await setWorkaroundState( + wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); + const state = existing.state || { ...DEFAULT_WORKAROUND_STATE }; + const commandTokenAdded = existing.command_token_added === true; + newState = !existing.state; + integration = await installWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + commandTokenAdded, + target.transport, + target.transport.kind === "flatpak" ? existing.shortcut_exe || undefined : undefined, + ); + stateWriteAttempted = true; + const saved = await setWorkaroundState( target.appid, state, - originalExecutable || null, - oldCommandTokenAdded, + integration.originalExecutable ?? null, + integration.commandTokenAdded, target.transport, ); - if (!initialStateResult.success) throw new Error(initialStateResult.error || "Could not create workaround state"); - - let integration: Awaited> | null = null; - try { - integration = await installWrapperIntegration( - appId, - target.nonSteam, - wrapperPath, - oldCommandTokenAdded, - target.transport.kind, - ); - const finalStateResult = await setWorkaroundState( - target.appid, - state, - usesShortcutTarget - ? (selectShortcutExecutable( - target, - integration.originalExecutable, - originalExecutable, - target.executable, - ) || null) - : null, - integration.commandTokenAdded, - target.transport, - ); - if (!finalStateResult.success) throw new Error(finalStateResult.error || "Could not finalize workaround state"); - return true; - } catch (error) { - let rollbackSucceeded = true; - if (!initialIntegration && integration) { - try { - await removeWrapperIntegration( - appId, - target.nonSteam, - wrapperPath, - usesShortcutTarget - ? (selectShortcutExecutable( - target, - integration?.originalExecutable, - originalExecutable, - target.executable, - ) || undefined) - : undefined, - integration?.commandTokenAdded ?? oldCommandTokenAdded, - target.transport.kind, - ); - } catch (rollbackError) { - showErrorToast("Workaround rollback failed", asError(rollbackError).message); - rollbackSucceeded = false; - } + if (!saved.success) throw new Error(saved.error || "Could not save workaround state"); + return true; + } catch (error) { + let rollbackSucceeded = true; + if (integration?.changed) { + try { + await removeWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + integration.originalExecutable, + integration.commandTokenAdded, + target.transport, + ); + } catch (rollbackError) { + showErrorToast("Workaround rollback failed", asError(rollbackError).message); + rollbackSucceeded = false; } - if (rollbackSucceeded) { - const restored = oldState - ? await setWorkaroundState( - target.appid, - oldState, - oldShortcutExe || null, - oldCommandTokenAdded, - oldTransport, - ) - : await removeWorkaroundState(target.appid); - if (!restored.success) throw new Error(restored.error || "Could not roll back workaround state"); + } + if (rollbackSucceeded && newState && stateWriteAttempted) { + const restored = await removeWorkaroundState(target.appid); + if (!restored.success) { + showErrorToast("Workaround rollback failed", restored.error || "Could not roll back workaround state"); + rollbackSucceeded = false; } - throw error; } - } catch (error) { showErrorToast("Could not initialize workarounds", asError(error).message); return false; } @@ -260,23 +197,14 @@ export function useGameConfiguration() { const existing = await getWorkaroundState(target.appid); if (!existing.success) throw new Error(existing.error || "Could not read workaround state"); const wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); - const usesShortcutTarget = target.nonSteam && target.transport.kind === "flatpak"; - if (existing.state) { - await removeWrapperIntegration( - appId, - target.nonSteam, - wrapperPath, - existing.shortcut_exe || undefined, - existing.command_token_added === true, - target.transport.kind, - ); - } else { - const current = await readSteamLaunchOptions(appId, target.nonSteam); - if (usesShortcutTarget && (current.target === wrapperPath || isLegacyWrapperToken(current.target))) { - throw new Error("Shortcut Target is a frame-generation wrapper but its original Target is unknown"); - } - await cleanupLegacySteamLaunchOptions(appId, target.nonSteam, wrapperPath); - } + await removeWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + target.transport.kind === "flatpak" ? existing.shortcut_exe || undefined : undefined, + existing.command_token_added === true, + target.transport, + ); const removed = await removeWorkaroundState(target.appid); if (!removed.success) throw new Error(removed.error || "Could not remove workaround state"); return true; diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index ebb12e2..29e1181 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -7,10 +7,10 @@ import { type WorkaroundState, } from "../api/lsfgApi"; import { + assertKnownShortcutTarget, getDefaultWrapperPath, - hasWrapperLaunchIntegration, installWrapperIntegration, - isLegacyWrapperToken, + isWrapperIntegrationInstalled, readSteamLaunchOptions, removeWrapperIntegration, subscribeSteamLaunchOptions, @@ -61,33 +61,6 @@ function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } -function selectShortcutExecutable( - transport: TargetTransport, - ...candidates: Array -): string | undefined { - const absolute = candidates - .map((candidate) => candidate?.trim()) - .find((candidate) => candidate && candidate.startsWith("/")); - if (absolute) return absolute; - if (transport.kind === "flatpak") return "/usr/bin/flatpak"; - return candidates.map((candidate) => candidate?.trim()).find(Boolean); -} - -function usesShortcutTarget(nonSteam: boolean, transport: TargetTransport): boolean { - return nonSteam && transport.kind === "flatpak"; -} - -function integrationIsInstalled( - steam: SteamLaunchOptionsSnapshot, - nonSteam: boolean, - transport: TargetTransport, - wrapperPath: string, -): boolean { - return usesShortcutTarget(nonSteam, transport) - ? steam.target === wrapperPath - : hasWrapperLaunchIntegration(steam.options, wrapperPath); -} - function makeSnapshot( steam: SteamLaunchOptionsSnapshot, result: Awaited>, @@ -97,17 +70,16 @@ function makeSnapshot( if (!result.state) throw new Error("Workaround state is not initialized for this profile"); const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); const selectedTransport = result.transport || transport; - if (usesShortcutTarget(nonSteam, selectedTransport) && steam.target === wrapperPath && !result.shortcut_exe) { - throw new Error("Managed shortcut Target has no saved original executable"); - } + const shortcutExe = selectedTransport.kind === "flatpak" ? result.shortcut_exe : undefined; + assertKnownShortcutTarget(steam, nonSteam, selectedTransport, wrapperPath, shortcutExe); return { steam, state: result.state, wrapperPath, wrapperOwned: result.wrapper_owned === true, - integrationInstalled: integrationIsInstalled(steam, nonSteam, selectedTransport, wrapperPath), + integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, selectedTransport, wrapperPath), commandTokenAdded: result.command_token_added === true, - shortcutExe: result.shortcut_exe, + shortcutExe, transport: selectedTransport, }; } @@ -116,24 +88,8 @@ async function adoptWorkaroundState( appId: string, nonSteam: boolean, transport: TargetTransport, - steam: SteamLaunchOptionsSnapshot, wrapperPath: string, ): Promise { - const shortcutTarget = usesShortcutTarget(nonSteam, transport); - if (shortcutTarget && (!steam.target || steam.target === wrapperPath || isLegacyWrapperToken(steam.target))) { - throw new Error("Shortcut Target is a wrapper but its original Target is unknown"); - } - const originalExecutable = shortcutTarget - ? selectShortcutExecutable(transport, steam.target) - : null; - const initial = await setWorkaroundState( - appId, - DEFAULT_WORKAROUND_STATE, - originalExecutable, - false, - transport, - ); - if (!initial.success) throw new Error(initial.error || "Could not create workaround state"); let integration: Awaited> | null = null; try { integration = await installWrapperIntegration( @@ -141,14 +97,12 @@ async function adoptWorkaroundState( nonSteam, wrapperPath, false, - transport.kind, + transport, ); const finalized = await setWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, - shortcutTarget - ? (selectShortcutExecutable(transport, integration.originalExecutable, originalExecutable) || null) - : null, + integration.originalExecutable ?? null, integration.commandTokenAdded, transport, ); @@ -156,17 +110,15 @@ async function adoptWorkaroundState( return makeSnapshot(integration.snapshot, finalized, nonSteam, transport); } catch (error) { let rollbackSucceeded = true; - if (integration) { + if (integration?.changed) { try { await removeWrapperIntegration( Number(appId), nonSteam, wrapperPath, - shortcutTarget - ? (selectShortcutExecutable(transport, integration?.originalExecutable, originalExecutable) || undefined) - : undefined, - integration?.commandTokenAdded ?? false, - transport.kind, + integration.originalExecutable, + integration.commandTokenAdded, + transport, ); } catch { // Leave the owned integration in place rather than guessing at cleanup. @@ -203,7 +155,6 @@ export function usePerAppWorkarounds( appId, nonSteam, transport, - steam, result.wrapper_path || getDefaultWrapperPath(), ); } @@ -243,7 +194,7 @@ export function usePerAppWorkarounds( setSnapshot((current) => current ? { ...current, steam, - integrationInstalled: integrationIsInstalled(steam, nonSteam, current.transport, current.wrapperPath), + integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, current.transport, current.wrapperPath), } : current); }, (subscriptionError) => { @@ -278,22 +229,24 @@ export function usePerAppWorkarounds( setError(null); const nextState = { ...current.state, [field]: value } as WorkaroundState; try { + const shortcutExe = current.transport.kind === "flatpak" ? current.shortcutExe ?? null : null; const result = await setWorkaroundState( appId, nextState, - current.shortcutExe ?? null, + shortcutExe, current.commandTokenAdded, current.transport, ); if (!result.success || !result.state) throw new Error(result.error || "Could not save workaround state"); + const selectedTransport = result.transport || current.transport; applySnapshot({ ...current, state: result.state, wrapperPath: result.wrapper_path || current.wrapperPath, wrapperOwned: result.wrapper_owned === true, - shortcutExe: result.shortcut_exe, + shortcutExe: selectedTransport.kind === "flatpak" ? result.shortcut_exe : undefined, commandTokenAdded: result.command_token_added === true, - transport: result.transport || current.transport, + transport: selectedTransport, }); return true; } catch (updateError) { diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 65541d8..959ce9e 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -1,3 +1,5 @@ +import type { TargetTransport } from "../api/lsfgApi"; + const DEFAULT_WRAPPER_PATH = "~/.lsfg"; const COMMAND_TOKEN = "%command%"; @@ -31,6 +33,7 @@ export interface WrapperIntegrationResult { snapshot: SteamLaunchOptionsSnapshot; originalExecutable?: string; commandTokenAdded: boolean; + changed: boolean; } function asError(error: unknown): Error { @@ -159,6 +162,13 @@ const commandIndex = (tokens: readonly LaunchToken[]) => tokens.findIndex((token const isAssignment = (token: LaunchToken) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value); const isLegacyToken = (value: string) => LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); const isWrapperToken = (value: string, wrapperPath: string) => decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); +const usesShortcutTarget = (nonSteam: boolean, transport: TargetTransport) => nonSteam && transport.kind === "flatpak"; + +function selectFlatpakExecutable(transport: TargetTransport, candidate?: string | null): string | undefined { + if (transport.kind !== "flatpak") return undefined; + const value = candidate?.trim(); + return value ? (value.startsWith("/") ? value : "/usr/bin/flatpak") : undefined; +} export const normalizeLaunchOptions = (options: string) => serialize(tokenize(options)); export const isLegacyWrapperToken = (value: string) => isLegacyToken(decodeToken(value)); @@ -172,10 +182,10 @@ function removeMatchingWrappers(tokens: LaunchToken[], predicate: (value: string return true; } -export function installWrapperLaunchOption( +function installLaunchOption( options: string, wrapperPath = DEFAULT_WRAPPER_PATH, - allowCommandArgs = false, + shortcutLaunchOptions = false, ) { const tokens = tokenize(options); removeMatchingWrappers(tokens, isLegacyToken); @@ -189,7 +199,7 @@ export function installWrapperLaunchOption( } let insertion = 0; while (insertion < tokens.length && isAssignment(tokens[insertion])) insertion++; - if (!allowCommandArgs && insertion < tokens.length && !tokens[insertion].value.startsWith("-")) { + if (!shortcutLaunchOptions && insertion < tokens.length && !tokens[insertion].value.startsWith("-")) { throw new Error("Launch options do not contain %command%; refusing to guess a launcher command"); } tokens.splice(insertion, 0, @@ -199,6 +209,10 @@ export function installWrapperLaunchOption( return { options: serialize(tokens), commandTokenAdded: true }; } +export function installWrapperLaunchOption(options: string, wrapperPath = DEFAULT_WRAPPER_PATH) { + return installLaunchOption(options, wrapperPath); +} + export function removeWrapperLaunchOption( options: string, wrapperPath = DEFAULT_WRAPPER_PATH, @@ -249,6 +263,29 @@ export function hasWrapperLaunchIntegration(options: string, wrapperPath = DEFAU return command > 0 && tokens[command - 1].value === wrapperPath; } +export function isWrapperIntegrationInstalled( + steam: SteamLaunchOptionsSnapshot, + nonSteam: boolean, + transport: TargetTransport, + wrapperPath = DEFAULT_WRAPPER_PATH, +): boolean { + return usesShortcutTarget(nonSteam, transport) + ? steam.target === wrapperPath + : hasWrapperLaunchIntegration(steam.options, wrapperPath); +} + +export function assertKnownShortcutTarget( + steam: SteamLaunchOptionsSnapshot, + nonSteam: boolean, + transport: TargetTransport, + wrapperPath: string, + originalExecutable?: string | null, +): void { + if (usesShortcutTarget(nonSteam, transport) && steam.target === wrapperPath && !originalExecutable) { + throw new Error("Managed shortcut Target has no saved original executable"); + } +} + const queues = new Map>(); function queued(appId: number, nonSteam: boolean, operation: () => Promise): Promise { const key = `${nonSteam ? "shortcut" : "app"}:${appId}`; @@ -340,43 +377,52 @@ export function installWrapperIntegration( nonSteam: boolean, wrapperPath: string, commandTokenAdded = false, - transport: "host" | "flatpak" = "host", + transport: TargetTransport = { kind: "host" }, + originalExecutable?: string, ): Promise { return queued(appId, nonSteam, async () => { let current = await readSteamLaunchOptions(appId, nonSteam); - if (nonSteam && transport === "flatpak") { + if (usesShortcutTarget(nonSteam, transport)) { if (!current.target) throw new Error("Steam shortcut Target is empty; refusing to replace it"); if (current.target !== wrapperPath && isWrapperToken(current.target, wrapperPath)) { throw new Error("The shortcut Target points to a legacy frame-generation wrapper; restore it first"); } const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); - if (cleaned !== current.options) { + const launchOptionsChanged = cleaned !== current.options; + if (launchOptionsChanged) { current = await writeVerified( appId, true, current.options, cleaned, (value) => writeOptions(appId, true, value), readOptions, "Steam did not accept shortcut launch options", ); } - if (current.target === wrapperPath) return { snapshot: current, commandTokenAdded: false }; - const originalExecutable = current.target; + const savedOriginal = selectFlatpakExecutable(transport, originalExecutable); + if (current.target === wrapperPath) { + if (!savedOriginal) throw new Error("Managed shortcut Target has no saved original executable"); + return { snapshot: current, originalExecutable: savedOriginal, commandTokenAdded: false, changed: launchOptionsChanged }; + } + if (savedOriginal && selectFlatpakExecutable(transport, current.target) !== savedOriginal) { + throw new Error("Shortcut Target changed externally; refusing to replace it"); + } + const currentOriginal = selectFlatpakExecutable(transport, current.target); const value = await writeVerified( - appId, true, originalExecutable, wrapperPath, + appId, true, current.target, wrapperPath, (target) => writeTarget(appId, target), readTarget, "Steam did not accept the shortcut Target", ); - return { snapshot: value, originalExecutable, commandTokenAdded: false }; + return { snapshot: value, originalExecutable: currentOriginal, commandTokenAdded: false, changed: true }; } const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); const alreadyInstalled = hasWrapperLaunchIntegration(current.options, wrapperPath); - const rewrite = installWrapperLaunchOption(cleaned, wrapperPath, nonSteam); - if (rewrite.options === current.options) return { snapshot: current, commandTokenAdded }; + const rewrite = installLaunchOption(cleaned, wrapperPath, nonSteam); + if (rewrite.options === current.options) return { snapshot: current, commandTokenAdded, changed: false }; const value = await writeVerified( appId, nonSteam, current.options, rewrite.options, (options) => writeOptions(appId, nonSteam, options), readOptions, "Steam did not accept the launch options", ); - return { snapshot: value, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded }; + return { snapshot: value, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded, changed: true }; }); } @@ -386,17 +432,11 @@ export function removeWrapperIntegration( wrapperPath: string, originalExecutable?: string, commandTokenAdded = false, - transport: "host" | "flatpak" = "host", + transport: TargetTransport = { kind: "host" }, ): Promise { return queued(appId, nonSteam, async () => { let current = await readSteamLaunchOptions(appId, nonSteam); - if (nonSteam && transport === "flatpak") { - if (!originalExecutable || isWrapperToken(originalExecutable, wrapperPath)) { - throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); - } - if (current.target !== wrapperPath && current.target !== originalExecutable) { - throw new Error("Shortcut Target changed externally; refusing to restore it"); - } + if (usesShortcutTarget(nonSteam, transport)) { const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); if (cleaned !== current.options) { current = await writeVerified( @@ -405,7 +445,18 @@ export function removeWrapperIntegration( "Steam did not clean shortcut launch options", ); } - if (current.target === originalExecutable) return current; + if (current.target !== wrapperPath) { + if (isWrapperToken(current.target, wrapperPath)) { + throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); + } + if (originalExecutable && selectFlatpakExecutable(transport, current.target) !== selectFlatpakExecutable(transport, originalExecutable)) { + throw new Error("Shortcut Target changed externally; refusing to restore it"); + } + return current; + } + if (!originalExecutable || isWrapperToken(originalExecutable, wrapperPath)) { + throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); + } return writeVerified( appId, true, wrapperPath, originalExecutable, (target) => writeTarget(appId, target), readTarget, -- cgit v1.2.3 From 9902135e53be129bd6096d51d5e510ab298c1ae2 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 12:19:40 -0400 Subject: fix: handle bare Flatpak shortcut targets --- src/utils/steamLaunchOptions.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 959ce9e..82cf116 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -166,8 +166,10 @@ const usesShortcutTarget = (nonSteam: boolean, transport: TargetTransport) => no function selectFlatpakExecutable(transport: TargetTransport, candidate?: string | null): string | undefined { if (transport.kind !== "flatpak") return undefined; - const value = candidate?.trim(); - return value ? (value.startsWith("/") ? value : "/usr/bin/flatpak") : undefined; + const value = candidate?.trim() ? decodeToken(candidate.trim()) : ""; + if (value === "flatpak") return "/usr/bin/flatpak"; + if (value === "/usr/bin/flatpak") return value; + return undefined; } export const normalizeLaunchOptions = (options: string) => serialize(tokenize(options)); @@ -405,6 +407,9 @@ export function installWrapperIntegration( throw new Error("Shortcut Target changed externally; refusing to replace it"); } const currentOriginal = selectFlatpakExecutable(transport, current.target); + if (!currentOriginal || (originalExecutable && !savedOriginal)) { + throw new Error("Flatpak shortcut Target is not a supported executable"); + } const value = await writeVerified( appId, true, current.target, wrapperPath, (target) => writeTarget(appId, target), readTarget, -- cgit v1.2.3 From de74f0d2499159ed1cf8f628a166302146ae1f13 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Thu, 10 Sep 2026 12:58:44 -0400 Subject: fix flatpak disable leftovers --- src/api/lsfgApi.ts | 14 +++++ src/components/ConfigFileTab.tsx | 119 +++++++++++++++++++++++++++++------- src/components/ConfigurationTab.tsx | 50 +++++++++------ src/components/Content.tsx | 34 ++++++++++- 4 files changed, 177 insertions(+), 40 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index b96acec..567e1ae 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -105,6 +105,19 @@ export interface FileContentResult extends ApiResult { path?: string; } +export interface DebugFileContent { + id: string; + label: string; + path: string; + exists: boolean; + content?: string | null; + error?: string | null; +} + +export interface DebugFileContentsResult extends ApiResult { + files?: DebugFileContent[]; +} + export interface FlatpakExtensionStatus extends ApiResult { message: string; available: boolean; @@ -143,3 +156,4 @@ export const setWorkaroundState = callable<[ TargetTransport | null | undefined, ], WorkaroundStateResult>("set_workaround_state"); export const removeWorkaroundState = callable<[string], WorkaroundStateResult>("remove_workaround_state"); +export const getDebugFileContents = callable<[], DebugFileContentsResult>("get_debug_file_contents"); diff --git a/src/components/ConfigFileTab.tsx b/src/components/ConfigFileTab.tsx index e3cc09d..07408d7 100644 --- a/src/components/ConfigFileTab.tsx +++ b/src/components/ConfigFileTab.tsx @@ -1,13 +1,79 @@ +import { ButtonItem, Field, PanelSection, PanelSectionRow, Spinner } from "@decky/ui"; import { useEffect, useState } from "react"; -import { Field, PanelSection, PanelSectionRow, Spinner } from "@decky/ui"; -import { getConfigFileContent, FileContentResult } from "../api/lsfgApi"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; +import { getDebugFileContents, type DebugFileContent, type DebugFileContentsResult } from "../api/lsfgApi"; import t from "../i18n/i18n"; +function usePersistentCollapsed(key: string) { + const [collapsed, setCollapsed] = useState(() => { + try { + return localStorage.getItem(key) !== "false"; + } catch { + return true; + } + }); + + useEffect(() => { + try { + localStorage.setItem(key, String(collapsed)); + } catch { + // Persisting the view preference is optional. + } + }, [collapsed, key]); + + return [collapsed, () => setCollapsed((value) => !value)] as const; +} + +function DebugFileSection({ file }: { file: DebugFileContent }) { + const [collapsed, toggleCollapsed] = usePersistentCollapsed(`lsfg-debug-file-${file.id}-collapsed-v1`); + const status = file.exists ? "Present" : "Not present"; + + return ( + <> + + + + +
+ + {collapsed ? : } + +
+
+ {!collapsed && ( + + {file.exists && file.content !== null && file.content !== undefined ? ( +
+              {file.content}
+            
+ ) : ( + + )} +
+ )} + + ); +} + export function ConfigFileTab() { - const [result, setResult] = useState(null); + const [result, setResult] = useState(null); useEffect(() => { - getConfigFileContent().then(setResult).catch((error) => { + getDebugFileContents().then(setResult).catch((error) => { setResult({ success: false, error: String(error) }); }); }, []); @@ -23,24 +89,35 @@ export function ConfigFileTab() { } return ( - - {result.error && ( - - - - )} - {result.success && result.content && ( - <> - - - + <> + + + {result.error && ( -
-              {result.content}
-            
+
- - )} -
+ )} + {result.success && result.files?.map((file) => ( + + ))} +
+ ); } diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 5ae4a87..4e2d93d 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,4 +1,4 @@ -import { ButtonItem, ConfirmModal, DialogButton, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses, showModal } from "@decky/ui"; +import { ButtonItem, ConfirmModal, DialogButton, Focusable, PanelSection, PanelSectionRow, ToggleField, gamepadDialogClasses, showModal } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; @@ -11,6 +11,8 @@ interface ConfigurationTabProps { config: ConfigurationData; targets: GameTarget[]; runningGame: GameTarget | null; + showDebugTab: boolean; + onShowDebugTabChange: (value: boolean) => void; onSelect: (appid: string) => void; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; onEnable: (appid: string) => Promise; @@ -24,6 +26,8 @@ export function ConfigurationTab({ config, targets, runningGame, + showDebugTab, + onShowDebugTabChange, onSelect, onConfigChange, onEnable, @@ -63,22 +67,34 @@ export function ConfigurationTab({ if (detailAppId === null) { return ( - - { - setFocusConfiguredToggle(false); - setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "fps" : "enable"); - onSelect(appid); - setDetailAppId(appid); - }} - onEnableAll={onEnableAll} - onResetAll={onResetAll} - focusConfiguredToggle={focusConfiguredToggle} - onConfiguredToggleFocused={clearConfiguredToggleFocusRequest} - /> - + <> + + { + setFocusConfiguredToggle(false); + setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "fps" : "enable"); + onSelect(appid); + setDetailAppId(appid); + }} + onEnableAll={onEnableAll} + onResetAll={onResetAll} + focusConfiguredToggle={focusConfiguredToggle} + onConfiguredToggleFocused={clearConfiguredToggleFocusRequest} + /> + + + + + + + ); } diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 578f984..43720c0 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -17,6 +17,29 @@ const tabIcons = { setup: , }; +const DEBUG_TAB_VISIBILITY_KEY = "lsfg-debug-tab-visible-v1"; + +function usePersistentBoolean(key: string, defaultValue: boolean) { + const [value, setValue] = useState(() => { + try { + const stored = localStorage.getItem(key); + return stored === null ? defaultValue : stored === "true"; + } catch { + return defaultValue; + } + }); + + useEffect(() => { + try { + localStorage.setItem(key, String(value)); + } catch { + // Persisting the visibility preference is optional. + } + }, [key, value]); + + return [value, setValue] as const; +} + export function Content() { const { config, @@ -43,6 +66,7 @@ export function Content() { uninstall, } = useInstallation(reload); const [tab, setTab] = useState("Setup"); + const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, true); const previousRunningAppId = useRef(null); const setupComplete = isInstalled && @@ -74,6 +98,10 @@ export function Content() { if (isInstalled) void reload(); }, [isInstalled, reload]); + useEffect(() => { + if (!showDebugTab && tab === "ConfigFile") setTab("Games"); + }, [showDebugTab, tab]); + const handleConfigChange = async ( fieldName: keyof ConfigurationData, value: boolean | number | string | string[], @@ -116,6 +144,8 @@ export function Content() { config={config} targets={targets} runningGame={runningGame} + showDebugTab={showDebugTab} + onShowDebugTabChange={setShowDebugTab} onSelect={setSelectedAppId} onConfigChange={(field, value) => handleConfigChange(field, value, true)} onEnable={enable} @@ -126,7 +156,7 @@ export function Content() { /> ), }, - { id: "ConfigFile", title: tabIcons.configFile, content: }, + ...(showDebugTab ? [{ id: "ConfigFile", title: tabIcons.configFile, content: }] : []), { id: "Setup", title: tabIcons.setup, content: setup }, ] : [{ id: "Setup", title: tabIcons.setup, content: setup }]; @@ -137,7 +167,7 @@ export function Content() { style={{ height: "95%", width: "300px", position: "fixed", marginTop: "-12px", overflow: "hidden" }} > - +
); } -- cgit v1.2.3 From 9f09fe0438c52922ac4f36eddb8c6e5808eb26b2 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:39:09 -0400 Subject: refactor: expose explicit flatpak app api --- src/api/lsfgApi.ts | 46 +++++++++++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 567e1ae..3e93620 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -30,10 +30,6 @@ export interface SteamBranchStatus extends ApiResult { } export type LsfgConfig = ConfigurationData; -export type TargetTransport = - | { kind: "host" } - | { kind: "flatpak"; flatpakAppId: string }; -export type FlatpakTargetSupportStatus = "ready" | "needs-runtime" | "unsupported" | "error"; export interface GameConfigEntry { appid: string; @@ -45,11 +41,10 @@ export interface InstalledGame { appid: string; name: string; nonSteam: boolean; - transport: TargetTransport; + directFlatpak?: boolean; executable?: string; arguments?: string; startDir?: string; - flatpakSupport?: FlatpakTargetSupport; } export interface GlobalConfig { @@ -57,15 +52,6 @@ export interface GlobalConfig { no_fp16: boolean; } -export interface FlatpakTargetSupport extends ApiResult { - flatpak_app_id?: string; - runtime?: string | null; - runtime_branch?: string | null; - support_status: FlatpakTargetSupportStatus; - extension_installed: boolean; - installed_branches: string[]; -} - export interface WorkaroundState { dxvkFrameRate: number; disableGamescopeWsi: boolean; @@ -82,7 +68,6 @@ export interface WorkaroundStateResult extends ApiResult { wrapper_owned?: boolean; shortcut_exe?: string | null; command_token_added?: boolean; - transport?: TargetTransport | null; } export interface GameConfigsResult extends ApiResult { @@ -133,14 +118,38 @@ export interface FlatpakExtensionToggleResult extends ApiResult { installed: boolean; } +export interface FlatpakApp { + app_id: string; + app_name: string; + runtime?: string | null; + runtime_branch?: string | null; + runtime_ready: boolean; + prepared: boolean; + owned: boolean; + error?: string | null; +} + +export interface FlatpakAppsResult extends ApiResult { + apps?: FlatpakApp[]; +} + +export interface FlatpakAppResult extends ApiResult { + app_id: string; + runtime?: string | null; + runtime_branch?: string | null; + prepared: boolean; + owned: boolean; +} + export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_vk"); export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); export const getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); export const getFlatpakSupportStatus = callable<[], FlatpakExtensionStatus>("get_flatpak_support_status"); -export const ensureFlatpakSupport = callable<[string], FlatpakTargetSupport>("ensure_flatpak_support"); -export const repairFlatpakSupport = callable<[string], FlatpakTargetSupport>("repair_flatpak_support"); +export const getFlatpakApps = callable<[], FlatpakAppsResult>("get_flatpak_apps"); +export const prepareFlatpakApp = callable<[string], FlatpakAppResult>("prepare_flatpak_app"); +export const removeFlatpakApp = callable<[string], FlatpakAppResult>("remove_flatpak_app"); export const setFlatpakExtensionEnabled = callable<[string, boolean], FlatpakExtensionToggleResult>("set_flatpak_extension_enabled"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); @@ -153,7 +162,6 @@ export const setWorkaroundState = callable<[ WorkaroundState, string | null | undefined, boolean, - TargetTransport | null | undefined, ], WorkaroundStateResult>("set_workaround_state"); export const removeWorkaroundState = callable<[string], WorkaroundStateResult>("remove_workaround_state"); export const getDebugFileContents = callable<[], DebugFileContentsResult>("get_debug_file_contents"); -- cgit v1.2.3 From 6c22d5ee540bc4c71a72c1e83ffc40e6b0494bc1 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:40:57 -0400 Subject: refactor: use explicit direct flatpak target wrapper --- src/utils/steamLaunchOptions.ts | 114 +++++++++++++++++----------------------- 1 file changed, 48 insertions(+), 66 deletions(-) (limited to 'src') diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 82cf116..08ae136 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -1,5 +1,3 @@ -import type { TargetTransport } from "../api/lsfgApi"; - const DEFAULT_WRAPPER_PATH = "~/.lsfg"; const COMMAND_TOKEN = "%command%"; @@ -31,7 +29,6 @@ export interface SteamLaunchOptionsSnapshot { } export interface WrapperIntegrationResult { snapshot: SteamLaunchOptionsSnapshot; - originalExecutable?: string; commandTokenAdded: boolean; changed: boolean; } @@ -162,14 +159,28 @@ const commandIndex = (tokens: readonly LaunchToken[]) => tokens.findIndex((token const isAssignment = (token: LaunchToken) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value); const isLegacyToken = (value: string) => LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); const isWrapperToken = (value: string, wrapperPath: string) => decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); -const usesShortcutTarget = (nonSteam: boolean, transport: TargetTransport) => nonSteam && transport.kind === "flatpak"; -function selectFlatpakExecutable(transport: TargetTransport, candidate?: string | null): string | undefined { - if (transport.kind !== "flatpak") return undefined; - const value = candidate?.trim() ? decodeToken(candidate.trim()) : ""; - if (value === "flatpak") return "/usr/bin/flatpak"; - if (value === "/usr/bin/flatpak") return value; - return undefined; +function flatpakExecutable(value: string): string | undefined { + const decoded = decodeToken(value.trim()); + return decoded === "flatpak" || decoded === "/usr/bin/flatpak" ? "/usr/bin/flatpak" : undefined; +} + +function wrappedFlatpakExecutable(target: string, wrapperPath: string, includeLegacy = true): string | undefined { + const tokens = tokenize(target); + if (tokens.length !== 2) return undefined; + const wrapper = tokens[0].value; + if (wrapper !== wrapperPath && !(includeLegacy && isLegacyToken(wrapper))) return undefined; + return flatpakExecutable(tokens[1].value); +} + +function directFlatpakExecutable(target: string, wrapperPath: string): string | undefined { + const tokens = tokenize(target); + if (tokens.length === 1) return flatpakExecutable(tokens[0].value); + return wrappedFlatpakExecutable(target, wrapperPath); +} + +function managedFlatpakTarget(wrapperPath: string, executable: string): string { + return `${wrapperPath} "${executable.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } export const normalizeLaunchOptions = (options: string) => serialize(tokenize(options)); @@ -268,24 +279,14 @@ export function hasWrapperLaunchIntegration(options: string, wrapperPath = DEFAU export function isWrapperIntegrationInstalled( steam: SteamLaunchOptionsSnapshot, nonSteam: boolean, - transport: TargetTransport, + directFlatpak = false, wrapperPath = DEFAULT_WRAPPER_PATH, ): boolean { - return usesShortcutTarget(nonSteam, transport) - ? steam.target === wrapperPath - : hasWrapperLaunchIntegration(steam.options, wrapperPath); -} - -export function assertKnownShortcutTarget( - steam: SteamLaunchOptionsSnapshot, - nonSteam: boolean, - transport: TargetTransport, - wrapperPath: string, - originalExecutable?: string | null, -): void { - if (usesShortcutTarget(nonSteam, transport) && steam.target === wrapperPath && !originalExecutable) { - throw new Error("Managed shortcut Target has no saved original executable"); + if (nonSteam && directFlatpak) { + const tokens = tokenize(steam.target); + return tokens.length === 2 && tokens[0].value === wrapperPath && flatpakExecutable(tokens[1].value) !== undefined; } + return hasWrapperLaunchIntegration(steam.options, wrapperPath); } const queues = new Map>(); @@ -328,7 +329,7 @@ async function writeVerified( read: (value: SteamLaunchOptionsSnapshot) => string, message: string, ): Promise { - const normalized = read === readOptions ? normalizeLaunchOptions : (value: string) => value; + const normalized = read === readOptions ? normalizeLaunchOptions : (value: string) => normalizeLaunchOptions(value); try { await write(next); return await waitFor(appId, nonSteam, (value) => normalized(read(value)) === normalized(next), message); @@ -379,16 +380,11 @@ export function installWrapperIntegration( nonSteam: boolean, wrapperPath: string, commandTokenAdded = false, - transport: TargetTransport = { kind: "host" }, - originalExecutable?: string, + directFlatpak = false, ): Promise { return queued(appId, nonSteam, async () => { let current = await readSteamLaunchOptions(appId, nonSteam); - if (usesShortcutTarget(nonSteam, transport)) { - if (!current.target) throw new Error("Steam shortcut Target is empty; refusing to replace it"); - if (current.target !== wrapperPath && isWrapperToken(current.target, wrapperPath)) { - throw new Error("The shortcut Target points to a legacy frame-generation wrapper; restore it first"); - } + if (nonSteam && directFlatpak) { const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); const launchOptionsChanged = cleaned !== current.options; if (launchOptionsChanged) { @@ -398,24 +394,18 @@ export function installWrapperIntegration( "Steam did not accept shortcut launch options", ); } - const savedOriginal = selectFlatpakExecutable(transport, originalExecutable); - if (current.target === wrapperPath) { - if (!savedOriginal) throw new Error("Managed shortcut Target has no saved original executable"); - return { snapshot: current, originalExecutable: savedOriginal, commandTokenAdded: false, changed: launchOptionsChanged }; - } - if (savedOriginal && selectFlatpakExecutable(transport, current.target) !== savedOriginal) { - throw new Error("Shortcut Target changed externally; refusing to replace it"); - } - const currentOriginal = selectFlatpakExecutable(transport, current.target); - if (!currentOriginal || (originalExecutable && !savedOriginal)) { - throw new Error("Flatpak shortcut Target is not a supported executable"); + const executable = directFlatpakExecutable(current.target, wrapperPath); + if (!executable) throw new Error("Flatpak shortcut Target is not a supported direct Flatpak executable"); + const target = managedFlatpakTarget(wrapperPath, executable); + if (normalizeLaunchOptions(current.target) === normalizeLaunchOptions(target)) { + return { snapshot: current, commandTokenAdded: false, changed: launchOptionsChanged }; } const value = await writeVerified( - appId, true, current.target, wrapperPath, - (target) => writeTarget(appId, target), readTarget, + appId, true, current.target, target, + (next) => writeTarget(appId, next), readTarget, "Steam did not accept the shortcut Target", ); - return { snapshot: value, originalExecutable: currentOriginal, commandTokenAdded: false, changed: true }; + return { snapshot: value, commandTokenAdded: false, changed: true }; } const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); @@ -435,13 +425,12 @@ export function removeWrapperIntegration( appId: number, nonSteam: boolean, wrapperPath: string, - originalExecutable?: string, commandTokenAdded = false, - transport: TargetTransport = { kind: "host" }, + directFlatpak = false, ): Promise { return queued(appId, nonSteam, async () => { let current = await readSteamLaunchOptions(appId, nonSteam); - if (usesShortcutTarget(nonSteam, transport)) { + if (nonSteam && directFlatpak) { const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); if (cleaned !== current.options) { current = await writeVerified( @@ -450,23 +439,16 @@ export function removeWrapperIntegration( "Steam did not clean shortcut launch options", ); } - if (current.target !== wrapperPath) { - if (isWrapperToken(current.target, wrapperPath)) { - throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); - } - if (originalExecutable && selectFlatpakExecutable(transport, current.target) !== selectFlatpakExecutable(transport, originalExecutable)) { - throw new Error("Shortcut Target changed externally; refusing to restore it"); - } - return current; - } - if (!originalExecutable || isWrapperToken(originalExecutable, wrapperPath)) { - throw new Error("Original shortcut Target is unavailable; refusing to overwrite the current Target"); + const wrapped = wrappedFlatpakExecutable(current.target, wrapperPath); + if (wrapped) { + return writeVerified( + appId, true, current.target, wrapped, + (target) => writeTarget(appId, target), readTarget, + "Steam did not restore the shortcut Target", + ); } - return writeVerified( - appId, true, wrapperPath, originalExecutable, - (target) => writeTarget(appId, target), readTarget, - "Steam did not restore the shortcut Target", - ); + if (flatpakExecutable(current.target)) return current; + throw new Error("Shortcut Target changed externally; refusing to restore it"); } const next = cleanupPluginAssignments(removeWrapperLaunchOption(current.options, wrapperPath, commandTokenAdded)); return next === current.options ? current : writeVerified( -- cgit v1.2.3 From 3817fb2ddd47baff55b9e4030731dbdda6948a3b Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:41:39 -0400 Subject: refactor: simplify workaround api types --- src/api/lsfgApi.ts | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 3e93620..aeaa502 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -66,7 +66,6 @@ export interface WorkaroundStateResult extends ApiResult { state?: WorkaroundState | null; wrapper_path?: string; wrapper_owned?: boolean; - shortcut_exe?: string | null; command_token_added?: boolean; } @@ -160,7 +159,6 @@ export const getWorkaroundState = callable<[string], WorkaroundStateResult>("get export const setWorkaroundState = callable<[ string, WorkaroundState, - string | null | undefined, boolean, ], WorkaroundStateResult>("set_workaround_state"); export const removeWorkaroundState = callable<[string], WorkaroundStateResult>("remove_workaround_state"); -- cgit v1.2.3 From 0df91099f4199dada43a7c804bb848722a493df2 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:42:13 -0400 Subject: refactor: decouple game profiles from flatpak setup --- src/hooks/useGameConfiguration.ts | 57 ++++++++++----------------------------- 1 file changed, 14 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 3260019..4131d0f 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; -import { ensureFlatpakSupport, getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, repairFlatpakSupport, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; +import { getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; import { getDefaultWrapperPath, installWrapperIntegration, removeWrapperIntegration } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; @@ -23,7 +23,7 @@ async function getSteamShortcuts(): Promise { appid: String(appid >>> 0), name, nonSteam: true, - transport: { kind: "host" }, + directFlatpak: false, }]; }); } catch { @@ -80,6 +80,7 @@ export function useGameConfiguration() { previousQuickAccessVisible.current = quickAccessVisible; if (initialLoad || becameVisible) void load(); }, [load, quickAccessVisible]); + useEffect(() => { const poll = () => { if (!configsLoaded) return; @@ -90,7 +91,7 @@ export function useGameConfiguration() { const name = app.display_name || installed?.name; if (!name) return setRunningGame(null); setRunningGame((current) => current?.appid === appid ? current : { - ...(installed || { appid, name, nonSteam: false, transport: { kind: "host" } }), + ...(installed || { appid, name, nonSteam: false, directFlatpak: false }), name, configured: games.some((game) => game.appid === appid), }); @@ -99,6 +100,7 @@ export function useGameConfiguration() { const interval = window.setInterval(poll, 2000); return () => window.clearInterval(interval); }, [configsLoaded, games, installedGames]); + useEffect(() => { const appid = runningGame?.appid || null; if (appid !== previousRunningAppId.current) { @@ -109,26 +111,13 @@ export function useGameConfiguration() { const targets = useMemo(() => { 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, transport: { kind: "host" }, configured: true }); + for (const game of games) if (!configured.some((item) => item.appid === game.appid)) configured.push({ appid: game.appid, name: game.profile, nonSteam: false, directFlatpak: false, configured: true }); if (runningGame && !configured.some((game) => game.appid === runningGame.appid)) configured.unshift(runningGame); return configured; }, [games, installedGames, runningGame]); const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); const config = games.find((game) => game.appid === selectedAppId)?.config || template; - const ensureTargetFlatpakSupport = useCallback(async (target: GameTarget): Promise => { - if (target.transport.kind !== "flatpak") return true; - const result = await ensureFlatpakSupport(target.transport.flatpakAppId); - if (!result.success || result.support_status !== "ready") { - showErrorToast( - "Flatpak support unavailable", - result.error || result.message || "The required Flatpak runtime extension is not ready", - ); - return false; - } - return true; - }, []); - const ensureTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; const appId = Number(target.appid); @@ -148,16 +137,13 @@ export function useGameConfiguration() { target.nonSteam, wrapperPath, commandTokenAdded, - target.transport, - target.transport.kind === "flatpak" ? existing.shortcut_exe || undefined : undefined, + target.directFlatpak === true, ); stateWriteAttempted = true; const saved = await setWorkaroundState( target.appid, state, - integration.originalExecutable ?? null, integration.commandTokenAdded, - target.transport, ); if (!saved.success) throw new Error(saved.error || "Could not save workaround state"); return true; @@ -169,9 +155,8 @@ export function useGameConfiguration() { appId, target.nonSteam, wrapperPath, - integration.originalExecutable, integration.commandTokenAdded, - target.transport, + target.directFlatpak === true, ); } catch (rollbackError) { showErrorToast("Workaround rollback failed", asError(rollbackError).message); @@ -201,9 +186,8 @@ export function useGameConfiguration() { appId, target.nonSteam, wrapperPath, - target.transport.kind === "flatpak" ? existing.shortcut_exe || undefined : undefined, existing.command_token_added === true, - target.transport, + target.directFlatpak === true, ); const removed = await removeWorkaroundState(target.appid); if (!removed.success) throw new Error(removed.error || "Could not remove workaround state"); @@ -217,9 +201,6 @@ export function useGameConfiguration() { const save = useCallback(async (next: ConfigurationData, cleanupLaunchOptions = false) => { const selectedTarget = targets.find((target) => target.appid === selectedAppId); if (!selectedTarget?.name) return; - // The profile owns its wrapper integration. Keep this check on every - // configuration save so an external edit is detected before the profile - // is changed; toggles update the sidecar only. if (cleanupLaunchOptions && !(await ensureTargetWorkarounds(selectedTarget))) return; const result = await updateGameConfig(selectedAppId, selectedTarget.name, next); if (result.success) await load(); @@ -228,19 +209,17 @@ export function useGameConfiguration() { const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; - if (!(await ensureTargetFlatpakSupport(target))) return false; if (!(await ensureTargetWorkarounds(target))) return false; const result = await updateGameConfig(appid, target.name, template); if (result.success) await load(); else await removeTargetWorkarounds(target); return result.success; - }, [ensureTargetFlatpakSupport, ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + const enableAll = useCallback(async (): Promise => { const available = targets.filter((target) => !target.configured && target.name); if (available.length === 0) return; - for (const target of available) { - if (!(await ensureTargetFlatpakSupport(target))) return; if (!(await ensureTargetWorkarounds(target))) return; const result = await updateGameConfig(target.appid, target.name, template); if (!result.success) { @@ -253,20 +232,11 @@ export function useGameConfiguration() { } } await load(); - }, [ensureTargetFlatpakSupport, ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + const repair = useCallback(async (appid: string): Promise => { const target = targets.find((item) => item.appid === appid); if (!target) return false; - if (target.transport.kind === "flatpak") { - const support = await repairFlatpakSupport(target.transport.flatpakAppId); - if (!support.success || support.support_status !== "ready") { - showErrorToast( - "Flatpak support unavailable", - support.error || support.message || "The required Flatpak runtime extension is not ready", - ); - return false; - } - } const success = await ensureTargetWorkarounds(target); if (success) await load(); return success; @@ -284,6 +254,7 @@ export function useGameConfiguration() { } } }, [load, removeTargetWorkarounds, selectedAppId, targets]); + const resetAll = useCallback(async () => { for (const target of targets.filter((item) => item.configured)) { if (!(await removeTargetWorkarounds(target))) return; -- cgit v1.2.3 From 05bde72a64bd3fbf675e15e273043090f79d0a49 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:44:10 -0400 Subject: refactor: remove flatpak transport from workaround hook --- src/hooks/usePerAppWorkarounds.ts | 48 +++++++++++++++------------------------ 1 file changed, 18 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index 29e1181..30bbc6b 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -3,11 +3,9 @@ import { getWorkaroundState, removeWorkaroundState, setWorkaroundState, - type TargetTransport, type WorkaroundState, } from "../api/lsfgApi"; import { - assertKnownShortcutTarget, getDefaultWrapperPath, installWrapperIntegration, isWrapperIntegrationInstalled, @@ -45,8 +43,7 @@ export interface WorkaroundSnapshot { wrapperOwned: boolean; integrationInstalled: boolean; commandTokenAdded: boolean; - shortcutExe?: string | null; - transport: TargetTransport; + directFlatpak: boolean; } interface PerAppWorkarounds { @@ -65,29 +62,25 @@ function makeSnapshot( steam: SteamLaunchOptionsSnapshot, result: Awaited>, nonSteam: boolean, - transport: TargetTransport, + directFlatpak: boolean, ): WorkaroundSnapshot { if (!result.state) throw new Error("Workaround state is not initialized for this profile"); const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); - const selectedTransport = result.transport || transport; - const shortcutExe = selectedTransport.kind === "flatpak" ? result.shortcut_exe : undefined; - assertKnownShortcutTarget(steam, nonSteam, selectedTransport, wrapperPath, shortcutExe); return { steam, state: result.state, wrapperPath, wrapperOwned: result.wrapper_owned === true, - integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, selectedTransport, wrapperPath), + integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, directFlatpak, wrapperPath), commandTokenAdded: result.command_token_added === true, - shortcutExe, - transport: selectedTransport, + directFlatpak, }; } async function adoptWorkaroundState( appId: string, nonSteam: boolean, - transport: TargetTransport, + directFlatpak: boolean, wrapperPath: string, ): Promise { let integration: Awaited> | null = null; @@ -97,17 +90,15 @@ async function adoptWorkaroundState( nonSteam, wrapperPath, false, - transport, + directFlatpak, ); const finalized = await setWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, - integration.originalExecutable ?? null, integration.commandTokenAdded, - transport, ); if (!finalized.success) throw new Error(finalized.error || "Could not finalize workaround state"); - return makeSnapshot(integration.snapshot, finalized, nonSteam, transport); + return makeSnapshot(integration.snapshot, finalized, nonSteam, directFlatpak); } catch (error) { let rollbackSucceeded = true; if (integration?.changed) { @@ -116,12 +107,10 @@ async function adoptWorkaroundState( Number(appId), nonSteam, wrapperPath, - integration.originalExecutable, integration.commandTokenAdded, - transport, + directFlatpak, ); } catch { - // Leave the owned integration in place rather than guessing at cleanup. rollbackSucceeded = false; } } @@ -136,7 +125,7 @@ async function adoptWorkaroundState( export function usePerAppWorkarounds( appId: string, nonSteam: boolean, - transport: TargetTransport = { kind: "host" }, + directFlatpak = false, ): PerAppWorkarounds { const [status, setStatus] = useState("loading"); const [snapshot, setSnapshot] = useState(null); @@ -154,12 +143,12 @@ export function usePerAppWorkarounds( return adoptWorkaroundState( appId, nonSteam, - transport, + directFlatpak, result.wrapper_path || getDefaultWrapperPath(), ); } - return makeSnapshot(steam, result, nonSteam, transport); - }, [appId, nonSteam, numericAppId, transport]); + return makeSnapshot(steam, result, nonSteam, directFlatpak); + }, [appId, directFlatpak, nonSteam, numericAppId]); const applySnapshot = useCallback((next: WorkaroundSnapshot) => { setSnapshot(next); @@ -194,7 +183,12 @@ export function usePerAppWorkarounds( setSnapshot((current) => current ? { ...current, steam, - integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, current.transport, current.wrapperPath), + integrationInstalled: isWrapperIntegrationInstalled( + steam, + nonSteam, + current.directFlatpak, + current.wrapperPath, + ), } : current); }, (subscriptionError) => { @@ -229,24 +223,18 @@ export function usePerAppWorkarounds( setError(null); const nextState = { ...current.state, [field]: value } as WorkaroundState; try { - const shortcutExe = current.transport.kind === "flatpak" ? current.shortcutExe ?? null : null; const result = await setWorkaroundState( appId, nextState, - shortcutExe, current.commandTokenAdded, - current.transport, ); if (!result.success || !result.state) throw new Error(result.error || "Could not save workaround state"); - const selectedTransport = result.transport || current.transport; applySnapshot({ ...current, state: result.state, wrapperPath: result.wrapper_path || current.wrapperPath, wrapperOwned: result.wrapper_owned === true, - shortcutExe: selectedTransport.kind === "flatpak" ? result.shortcut_exe : undefined, commandTokenAdded: result.command_token_added === true, - transport: selectedTransport, }); return true; } catch (updateError) { -- cgit v1.2.3 From c46d41b22df8a6830fe4483ba1b71e246b4ae5e6 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:44:26 -0400 Subject: refactor: pass direct flatpak launch shape --- src/components/GameConfigurationControls.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/components/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx index 6bea2e0..a7e3fec 100644 --- a/src/components/GameConfigurationControls.tsx +++ b/src/components/GameConfigurationControls.tsx @@ -10,7 +10,7 @@ interface Props { autoFocusFpsMultiplier?: boolean; onFpsMultiplierFocused?: () => void; showWorkarounds?: boolean; - workaroundTarget?: Pick; + workaroundTarget?: Pick; onRepairWorkaround?: () => Promise; } @@ -36,7 +36,7 @@ export function GameConfigurationControls({ )} -- cgit v1.2.3 From 1ce6d55a1d44eeb0eb04751e124970f2f1f9acbb Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:45:03 -0400 Subject: refactor: decouple workaround controls from flatpak transport --- src/components/WorkaroundsSection.tsx | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/components/WorkaroundsSection.tsx b/src/components/WorkaroundsSection.tsx index 5587392..050992c 100644 --- a/src/components/WorkaroundsSection.tsx +++ b/src/components/WorkaroundsSection.tsx @@ -1,7 +1,6 @@ import { ButtonItem, Field, PanelSectionRow, SliderField, ToggleField } from "@decky/ui"; import { useEffect, useState } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; -import type { TargetTransport } from "../api/lsfgApi"; import { usePerAppWorkarounds } from "../hooks/usePerAppWorkarounds"; import t from "../i18n/i18n"; import type { WorkaroundField } from "../hooks/usePerAppWorkarounds"; @@ -9,7 +8,7 @@ import type { WorkaroundField } from "../hooks/usePerAppWorkarounds"; interface WorkaroundsSectionProps { appId: string; nonSteam: boolean; - transport: TargetTransport; + directFlatpak?: boolean; onRepair?: () => Promise; } @@ -73,17 +72,15 @@ function usePersistentCollapsed() { useEffect(() => { try { localStorage.setItem(WORKAROUNDS_COLLAPSED_KEY, JSON.stringify(collapsed)); - } catch { - // Persisting the view preference is optional. - } + } catch {} }, [collapsed]); return [collapsed, () => setCollapsed((value) => !value)] as const; } -export function WorkaroundsSection({ appId, nonSteam, transport, onRepair }: WorkaroundsSectionProps) { +export function WorkaroundsSection({ appId, nonSteam, directFlatpak = false, onRepair }: WorkaroundsSectionProps) { const [collapsed, toggleCollapsed] = usePersistentCollapsed(); - const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam, transport); + const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam, directFlatpak); const [repairing, setRepairing] = useState(false); const state = snapshot?.state; const controlsDisabled = status !== "ready" || state === undefined || snapshot?.wrapperOwned !== true || snapshot.integrationInstalled !== true; -- cgit v1.2.3 From da9166ca8c6d90f402352e47ec28d67f2a02cf14 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:45:27 -0400 Subject: refactor: remove per-game flatpak support ui --- src/components/ConfigurationTab.tsx | 50 +++++++++++++------------------------ 1 file changed, 18 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 4e2d93d..18575b4 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -100,8 +100,8 @@ export function ConfigurationTab({ const profileLabel = selectedTarget?.name || "Game profile"; const profileTransport = selectedTarget - ? selectedTarget.transport.kind === "flatpak" - ? "Non-Steam · Flatpak" + ? selectedTarget.directFlatpak + ? "Non-Steam · Direct Flatpak" : selectedTarget.nonSteam ? "Non-Steam" : "Steam" : "Game"; const profileDescription = selectedTarget @@ -120,9 +120,7 @@ export function ConfigurationTab({ } else if (detailAppId) { const isRunningUnconfigured = runningGame?.appid === detailAppId && runningGame.nonSteam === false - && runningGame.transport.kind === "host" && selectedTarget?.nonSteam === false - && selectedTarget?.transport.kind === "host" && !runningGame.configured; if (isRunningUnconfigured) { showModal( @@ -147,22 +145,22 @@ export function ConfigurationTab({
- - - + + +
)} - {selectedTarget?.configured && selectedTarget.transport.kind === "flatpak" && selectedTarget.flatpakSupport?.support_status !== "ready" && ( - - - void onRepair(selectedTarget.appid)} - > - Repair Flatpak support - - - - )} {selectedTarget?.configured && ( Date: Thu, 10 Sep 2026 15:45:36 -0400 Subject: refactor: remove per-game flatpak repair state --- src/components/NowPlayingTab.tsx | 37 ++----------------------------------- 1 file changed, 2 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index 57858db..1bc331f 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -1,5 +1,4 @@ -import { ButtonItem, Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; -import { useState } from "react"; +import { Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; import { GameConfigurationControls } from "./GameConfigurationControls"; @@ -11,11 +10,10 @@ interface Props { fieldName: keyof ConfigurationData, value: boolean | number | string | string[], ) => Promise; - onRepair: (appid: string) => Promise; } function targetDescription(game: GameTarget): string { - if (game.transport.kind === "flatpak") return "Non-Steam · Flatpak"; + if (game.directFlatpak) return "Non-Steam · Direct Flatpak"; return game.nonSteam ? "Non-Steam" : "Steam"; } @@ -23,23 +21,7 @@ export function NowPlayingTab({ game, config, onConfigChange, - onRepair, }: Props) { - const [busy, setBusy] = useState(false); - const supportNeedsRepair = - game.transport.kind === "flatpak" && - game.flatpakSupport?.support_status !== "ready"; - - const handleRepair = async () => { - if (busy) return; - setBusy(true); - try { - await onRepair(game.appid); - } finally { - setBusy(false); - } - }; - return ( @@ -47,21 +29,6 @@ export function NowPlayingTab({ - {supportNeedsRepair && ( - - - - - - void handleRepair()}> - {busy ? "Repairing..." : "Repair Flatpak support"} - - - - )} Date: Thu, 10 Sep 2026 15:45:58 -0400 Subject: feat: add explicit flatpak setup --- src/components/FlatpakSetupSection.tsx | 110 +++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 src/components/FlatpakSetupSection.tsx (limited to 'src') diff --git a/src/components/FlatpakSetupSection.tsx b/src/components/FlatpakSetupSection.tsx new file mode 100644 index 0000000..0119250 --- /dev/null +++ b/src/components/FlatpakSetupSection.tsx @@ -0,0 +1,110 @@ +import { ButtonItem, Field, PanelSection, PanelSectionRow } from "@decky/ui"; +import { useCallback, useEffect, useState } from "react"; +import { + getFlatpakApps, + prepareFlatpakApp, + removeFlatpakApp, + type FlatpakApp, +} from "../api/lsfgApi"; +import { showErrorToast } from "../utils/toastUtils"; + +interface Props { + enabled: boolean; +} + +export function FlatpakSetupSection({ enabled }: Props) { + const [apps, setApps] = useState([]); + const [loading, setLoading] = useState(false); + const [busyApp, setBusyApp] = useState(""); + const [error, setError] = useState(null); + + const load = useCallback(async () => { + if (!enabled) { + setApps([]); + setError(null); + return; + } + setLoading(true); + try { + const result = await getFlatpakApps(); + if (!result.success) throw new Error(result.error || "Could not list Flatpak applications"); + setApps(result.apps || []); + setError(null); + } catch (loadError) { + const message = loadError instanceof Error ? loadError.message : String(loadError); + setError(message); + } finally { + setLoading(false); + } + }, [enabled]); + + useEffect(() => { + void load(); + }, [load]); + + const toggle = async (app: FlatpakApp) => { + if (busyApp || (app.prepared && !app.owned)) return; + setBusyApp(app.app_id); + try { + const result = app.prepared + ? await removeFlatpakApp(app.app_id) + : await prepareFlatpakApp(app.app_id); + if (!result.success) throw new Error(result.error || "Flatpak setup failed"); + await load(); + } catch (operationError) { + const message = operationError instanceof Error ? operationError.message : String(operationError); + showErrorToast("Flatpak setup failed", message); + } finally { + setBusyApp(""); + } + }; + + if (!enabled) return null; + + return ( + + + + + {error && ( + + + + )} + {apps.map((app) => { + const busy = busyApp === app.app_id; + const description = [ + app.app_id, + app.runtime_branch ? `runtime ${app.runtime_branch}` : null, + app.error, + ].filter(Boolean).join(" · "); + const label = busy + ? "Working..." + : app.prepared + ? app.owned ? "Remove" : "Prepared externally" + : app.error ? "Unavailable" : "Prepare"; + return ( + + + void toggle(app)} + > + {label} + + + + ); + })} + + void load()}> + {loading ? "Refreshing..." : "Refresh Flatpaks"} + + + + ); +} -- cgit v1.2.3 From 644e624e6e8745f58b4f3bee4a672f180992ad1b Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:46:18 -0400 Subject: feat: add flatpak setup to setup tab --- src/components/SetupTab.tsx | 52 ++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index d769200..1a62c2a 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,6 +1,7 @@ import { ButtonItem, Field, PanelSection, PanelSectionRow } from "@decky/ui"; import { type SteamBranchStatus } from "../api/lsfgApi"; import t from "../i18n/i18n"; +import { FlatpakSetupSection } from "./FlatpakSetupSection"; interface SetupTabProps { isInstalled: boolean; @@ -36,33 +37,36 @@ export function SetupTab(props: SetupTabProps) { : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); return ( - - - - - - - - {steamBranchStatus?.installed && ( + <> + - )} - - - {buttonLabel} - - - + + + + {steamBranchStatus?.installed && ( + + + + )} + + + {buttonLabel} + + + + + ); } -- cgit v1.2.3 From f83e6cacec84ccc8e17be50d68e228aab996cee5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:46:51 -0400 Subject: refactor: remove now-playing flatpak repair coupling --- src/components/Content.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 43720c0..8f83e85 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -32,9 +32,7 @@ function usePersistentBoolean(key: string, defaultValue: boolean) { useEffect(() => { try { localStorage.setItem(key, String(value)); - } catch { - // Persisting the visibility preference is optional. - } + } catch {} }, [key, value]); return [value, setValue] as const; @@ -132,7 +130,6 @@ export function Content() { game={runningGame} config={config} onConfigChange={(field, value) => handleConfigChange(field, value)} - onRepair={repair} /> ), }] : []), -- cgit v1.2.3 From 91365a978911e17097f7363216271b98354399ec Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:50:35 -0400 Subject: refactor: remove flatpak transport labels --- src/components/GameConfigurationSelector.tsx | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 92eacba..1c95820 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -28,16 +28,14 @@ function usePersistentCollapsed(key: string) { useEffect(() => { try { localStorage.setItem(key, String(collapsed)); - } catch { - // Persisting the view preference is optional. - } + } catch {} }, [collapsed, key]); return [collapsed, () => setCollapsed((value) => !value)] as const; } function targetDescription(game: GameTarget): string { - if (game.transport.kind === "flatpak") return "Non-Steam · Flatpak"; + if (game.directFlatpak) return "Non-Steam · Direct Flatpak"; return game.nonSteam ? "Non-Steam" : "Steam"; } @@ -137,7 +135,7 @@ export function GameConfigurationSelector({ showModal( void onEnableAll()} -- cgit v1.2.3 From f6f77d775977ad17cdc73338d0f90d05a13cbfc2 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:53:02 -0400 Subject: fix: normalize released flatpak target paths --- src/utils/steamLaunchOptions.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 08ae136..685dcf9 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -162,7 +162,9 @@ const isWrapperToken = (value: string, wrapperPath: string) => decodeToken(value function flatpakExecutable(value: string): string | undefined { const decoded = decodeToken(value.trim()); - return decoded === "flatpak" || decoded === "/usr/bin/flatpak" ? "/usr/bin/flatpak" : undefined; + return decoded === "flatpak" || decoded === "/usr/bin/flatpak" || decoded === "usr/bin/flatpak" + ? "/usr/bin/flatpak" + : undefined; } function wrappedFlatpakExecutable(target: string, wrapperPath: string, includeLegacy = true): string | undefined { -- cgit v1.2.3 From e00f9ee6268fab5a1fdf46bca435a3f03e07ff53 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 15:56:06 -0400 Subject: refactor: trim flatpak api surface --- src/api/lsfgApi.ts | 17 ----------------- 1 file changed, 17 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index aeaa502..e5ce2bf 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -102,21 +102,6 @@ export interface DebugFileContentsResult extends ApiResult { files?: DebugFileContent[]; } -export interface FlatpakExtensionStatus extends ApiResult { - message: string; - available: boolean; - extension_id: string; - supported_branches: string[]; - installed_branches: string[]; -} - -export interface FlatpakExtensionToggleResult extends ApiResult { - message: string; - runtime_branch: string; - enabled: boolean; - installed: boolean; -} - export interface FlatpakApp { app_id: string; app_name: string; @@ -145,11 +130,9 @@ export const uninstallLsfgVk = callable<[], InstallationResult>("uninstall_lsfg_ export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg_vk_installed"); export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); export const getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); -export const getFlatpakSupportStatus = callable<[], FlatpakExtensionStatus>("get_flatpak_support_status"); export const getFlatpakApps = callable<[], FlatpakAppsResult>("get_flatpak_apps"); export const prepareFlatpakApp = callable<[string], FlatpakAppResult>("prepare_flatpak_app"); export const removeFlatpakApp = callable<[string], FlatpakAppResult>("remove_flatpak_app"); -export const setFlatpakExtensionEnabled = callable<[string, boolean], FlatpakExtensionToggleResult>("set_flatpak_extension_enabled"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); export const updateGameConfig = callable<[string, string, LsfgConfig], GameConfigResult>("update_game_config"); -- cgit v1.2.3 From 33ea22e3e45410c0e099cb8d495c4f2bae05cf34 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:30:52 -0400 Subject: feat: add flatpak profile client APIs --- src/api/lsfgApi.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index e5ce2bf..850efa9 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -63,6 +63,7 @@ export interface WorkaroundState { export interface WorkaroundStateResult extends ApiResult { appid?: string; + app_id?: string; state?: WorkaroundState | null; wrapper_path?: string; wrapper_owned?: boolean; @@ -110,6 +111,12 @@ export interface FlatpakApp { runtime_ready: boolean; prepared: boolean; owned: boolean; + enabled: boolean; + profile: string; + config?: LsfgConfig | null; + workarounds: WorkaroundState; + active?: boolean; + pid?: string; error?: string | null; } @@ -117,12 +124,8 @@ export interface FlatpakAppsResult extends ApiResult { apps?: FlatpakApp[]; } -export interface FlatpakAppResult extends ApiResult { +export interface FlatpakAppResult extends ApiResult, Partial { app_id: string; - runtime?: string | null; - runtime_branch?: string | null; - prepared: boolean; - owned: boolean; } export const installLsfgVk = callable<[], InstallationResult>("install_lsfg_vk"); @@ -131,8 +134,12 @@ export const checkLsfgVkInstalled = callable<[], InstallationStatus>("check_lsfg export const getLosslessScalingBranchStatus = callable<[], SteamBranchStatus>("get_lossless_scaling_branch_status"); export const getConfigFileContent = callable<[], FileContentResult>("get_config_file_content"); export const getFlatpakApps = callable<[], FlatpakAppsResult>("get_flatpak_apps"); -export const prepareFlatpakApp = callable<[string], FlatpakAppResult>("prepare_flatpak_app"); +export const enableFlatpakApp = callable<[string], FlatpakAppResult>("enable_flatpak_app"); +export const updateFlatpakConfig = callable<[string, LsfgConfig], FlatpakAppResult>("update_flatpak_config"); +export const getFlatpakWorkaroundState = callable<[string], WorkaroundStateResult>("get_flatpak_workaround_state"); +export const setFlatpakWorkaroundState = callable<[string, WorkaroundState], WorkaroundStateResult>("set_flatpak_workaround_state"); export const removeFlatpakApp = callable<[string], FlatpakAppResult>("remove_flatpak_app"); +export const getRunningFlatpakApps = callable<[], FlatpakAppsResult>("get_running_flatpak_apps"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); export const updateGameConfig = callable<[string, string, LsfgConfig], GameConfigResult>("update_game_config"); -- cgit v1.2.3 From aac2d9d360592ceaf732419e9fddc758cfd2cb42 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:31:13 -0400 Subject: feat: add flatpak profile state hook --- src/hooks/useFlatpakConfiguration.ts | 105 +++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/hooks/useFlatpakConfiguration.ts (limited to 'src') diff --git a/src/hooks/useFlatpakConfiguration.ts b/src/hooks/useFlatpakConfiguration.ts new file mode 100644 index 0000000..e8fae99 --- /dev/null +++ b/src/hooks/useFlatpakConfiguration.ts @@ -0,0 +1,105 @@ +import { useCallback, useEffect, useMemo, useState } from "react"; +import { + enableFlatpakApp, + getFlatpakApps, + getRunningFlatpakApps, + removeFlatpakApp, + setFlatpakWorkaroundState, + updateFlatpakConfig, + type FlatpakApp, + type LsfgConfig, + type WorkaroundState, +} from "../api/lsfgApi"; +import { showErrorToast } from "../utils/toastUtils"; + +export function useFlatpakConfiguration(enabled: boolean) { + const [apps, setApps] = useState([]); + const [runningApps, setRunningApps] = useState([]); + const [loading, setLoading] = useState(false); + const [busyAppId, setBusyAppId] = useState(""); + + const reload = useCallback(async () => { + if (!enabled) { + setApps([]); + return; + } + setLoading(true); + try { + const result = await getFlatpakApps(); + if (!result.success) throw new Error(result.error || "Could not list Flatpak applications"); + setApps(result.apps || []); + } catch (error) { + showErrorToast("Flatpak unavailable", error instanceof Error ? error.message : String(error)); + } finally { + setLoading(false); + } + }, [enabled]); + + const pollRunning = useCallback(async () => { + if (!enabled) { + setRunningApps([]); + return; + } + try { + const result = await getRunningFlatpakApps(); + if (result.success) setRunningApps(result.apps || []); + } catch {} + }, [enabled]); + + useEffect(() => { + void reload(); + }, [reload]); + + useEffect(() => { + void pollRunning(); + if (!enabled) return; + const interval = window.setInterval(() => void pollRunning(), 2000); + return () => window.clearInterval(interval); + }, [enabled, pollRunning]); + + const operate = useCallback(async (appId: string, operation: () => Promise<{ success: boolean; error?: string | null }>) => { + if (busyAppId) return false; + setBusyAppId(appId); + try { + const result = await operation(); + if (!result.success) throw new Error(result.error || "Flatpak operation failed"); + await reload(); + await pollRunning(); + return true; + } catch (error) { + showErrorToast("Flatpak operation failed", error instanceof Error ? error.message : String(error)); + return false; + } finally { + setBusyAppId(""); + } + }, [busyAppId, pollRunning, reload]); + + const enableApp = useCallback((appId: string) => operate(appId, () => enableFlatpakApp(appId)), [operate]); + const removeApp = useCallback((appId: string) => operate(appId, () => removeFlatpakApp(appId)), [operate]); + const updateConfig = useCallback( + (appId: string, config: LsfgConfig) => operate(appId, () => updateFlatpakConfig(appId, config)), + [operate], + ); + const updateWorkarounds = useCallback( + (appId: string, state: WorkaroundState) => operate(appId, () => setFlatpakWorkaroundState(appId, state)), + [operate], + ); + + const runningApp = useMemo(() => { + if (runningApps.length === 0) return null; + return runningApps.find((app) => app.active) || (runningApps.length === 1 ? runningApps[0] : null); + }, [runningApps]); + + return { + apps, + runningApps, + runningApp, + loading, + busyAppId, + reload, + enableApp, + removeApp, + updateConfig, + updateWorkarounds, + }; +} -- cgit v1.2.3 From 4823f1a17d647d4e6e387107a2260a8ebd3015de Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:31:35 -0400 Subject: feat: add flatpak workaround controls --- src/components/FlatpakWorkaroundsSection.tsx | 144 +++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 src/components/FlatpakWorkaroundsSection.tsx (limited to 'src') diff --git a/src/components/FlatpakWorkaroundsSection.tsx b/src/components/FlatpakWorkaroundsSection.tsx new file mode 100644 index 0000000..7d9d880 --- /dev/null +++ b/src/components/FlatpakWorkaroundsSection.tsx @@ -0,0 +1,144 @@ +import { ButtonItem, PanelSectionRow, SliderField, ToggleField } from "@decky/ui"; +import { useEffect, useRef, useState } from "react"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; +import type { WorkaroundState } from "../api/lsfgApi"; +import t from "../i18n/i18n"; + +interface Props { + state: WorkaroundState; + disabled?: boolean; + onChange: (state: WorkaroundState) => Promise; +} + +const WORKAROUNDS_COLLAPSED_KEY = "lsfg-flatpak-workarounds-collapsed-v1"; + +export function FlatpakWorkaroundsSection({ state, disabled = false, onChange }: Props) { + const [collapsed, setCollapsed] = useState(() => { + try { + return localStorage.getItem(WORKAROUNDS_COLLAPSED_KEY) !== "false"; + } catch { + return true; + } + }); + const [fpsValue, setFpsValue] = useState(state.dxvkFrameRate); + const timer = useRef(null); + + useEffect(() => { + try { + localStorage.setItem(WORKAROUNDS_COLLAPSED_KEY, String(collapsed)); + } catch {} + }, [collapsed]); + + useEffect(() => { + setFpsValue(state.dxvkFrameRate); + }, [state.dxvkFrameRate]); + + useEffect(() => () => { + if (timer.current !== null) window.clearTimeout(timer.current); + }, []); + + const update = (field: keyof WorkaroundState, value: boolean | number) => { + void onChange({ ...state, [field]: value }); + }; + + const updateFps = (value: number) => { + setFpsValue(value); + if (timer.current !== null) window.clearTimeout(timer.current); + timer.current = window.setTimeout(() => { + timer.current = null; + void onChange({ ...state, dxvkFrameRate: value }); + }, 250); + }; + + const fpsLabel = fpsValue > 0 ? `${fpsValue} FPS` : t("CONFIG_BASE_FPS_CAP_OFF", "Off"); + + return ( + <> + +
+ {t("CONFIG_WORKAROUNDS_TITLE", "Workarounds")} +
+
+ + setCollapsed((value) => !value)} + > + {collapsed ? : } + + + {!collapsed && ( + <> + + + + + update("disableSteamdeckMode", value)} + disabled={disabled} + /> + + + update("disableGamescopeWsi", value)} + disabled={disabled} + /> + + + update("disableHdr", value)} + disabled={disabled} + /> + + + update("disableVkbasalt", value)} + disabled={disabled} + /> + + + update("enableZink", value)} + disabled={disabled} + /> + + + )} + + ); +} -- cgit v1.2.3 From 6671a5c51fef98c07369f5e5be5ce498a317e868 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:31:58 -0400 Subject: feat: add flatpak profiles tab --- src/components/FlatpakTab.tsx | 178 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 src/components/FlatpakTab.tsx (limited to 'src') diff --git a/src/components/FlatpakTab.tsx b/src/components/FlatpakTab.tsx new file mode 100644 index 0000000..6392d59 --- /dev/null +++ b/src/components/FlatpakTab.tsx @@ -0,0 +1,178 @@ +import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses } from "@decky/ui"; +import { useCallback, useMemo, useState } from "react"; +import { FaArrowLeft } from "react-icons/fa"; +import type { FlatpakApp, LsfgConfig, WorkaroundState } from "../api/lsfgApi"; +import { ConfigurationSection } from "./ConfigurationSection"; +import { FlatpakWorkaroundsSection } from "./FlatpakWorkaroundsSection"; +import { FpsMultiplierControl } from "./FpsMultiplierControl"; +import { ProfileDetails } from "./ProfileDetails"; + +interface Props { + apps: FlatpakApp[]; + runningApp: FlatpakApp | null; + loading: boolean; + busyAppId: string; + onRefresh: () => Promise; + onEnable: (appId: string) => Promise; + onRemove: (appId: string) => Promise; + onConfigChange: (appId: string, config: LsfgConfig) => Promise; + onWorkaroundChange: (appId: string, state: WorkaroundState) => Promise; +} + +export function FlatpakTab({ + apps, + runningApp, + loading, + busyAppId, + onRefresh, + onEnable, + onRemove, + onConfigChange, + onWorkaroundChange, +}: Props) { + const [selectedAppId, setSelectedAppId] = useState(null); + const selected = useMemo( + () => selectedAppId ? apps.find((app) => app.app_id === selectedAppId) || null : null, + [apps, selectedAppId], + ); + const close = useCallback(() => setSelectedAppId(null), []); + + if (!selectedAppId) { + return ( + + + + + {apps.map((app) => { + const status = app.enabled + ? app.app_id === runningApp?.app_id ? "Enabled · Running" : "Enabled" + : app.prepared && !app.owned ? "Prepared externally" : "Available"; + return ( + + setSelectedAppId(app.app_id)} + highlightOnFocus + /> + + ); + })} + {apps.length === 0 && !loading && ( + + + + )} + + void onRefresh()}> + {loading ? "Refreshing..." : "Refresh Flatpaks"} + + + + ); + } + + if (!selected) { + return ( + + + Back + + + + + + ); + } + + const busy = busyAppId === selected.app_id; + const config = selected.config; + const external = selected.prepared && !selected.owned; + const profileDescription = [ + selected.app_id, + selected.runtime_branch ? `runtime ${selected.runtime_branch}` : null, + selected.enabled ? `profile ${selected.profile}` : null, + selected.app_id === runningApp?.app_id ? "Running" : null, + ].filter(Boolean).join(" · "); + + const changeConfig = async ( + field: keyof LsfgConfig, + value: boolean | number | string | string[], + ) => { + if (!config) return; + await onConfigChange(selected.app_id, { ...config, [field]: value }); + }; + + return ( + + + +
+ + + + + +
+ {selected.app_name} +
+
+
+
+ {!selected.enabled && ( + + + void onEnable(selected.app_id)} + > + {busy ? "Enabling..." : external ? "Prepared externally" : "Enable LSFG-VK"} + + + {selected.error && ( + + + + )} + + )} + {selected.enabled && config && ( + <> + + + onWorkaroundChange(selected.app_id, state)} + /> + + void onRemove(selected.app_id)}> + {busy ? "Removing..." : "Remove Flatpak profile"} + + + + )} + +
+ ); +} -- cgit v1.2.3 From 8090b237a34140343b13efc845f8123730989cbf Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:32:15 -0400 Subject: feat: show running flatpak profiles --- src/components/FlatpakNowPlayingTab.tsx | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/components/FlatpakNowPlayingTab.tsx (limited to 'src') diff --git a/src/components/FlatpakNowPlayingTab.tsx b/src/components/FlatpakNowPlayingTab.tsx new file mode 100644 index 0000000..9e5a0db --- /dev/null +++ b/src/components/FlatpakNowPlayingTab.tsx @@ -0,0 +1,39 @@ +import { Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import type { FlatpakApp, LsfgConfig, WorkaroundState } from "../api/lsfgApi"; +import { ConfigurationSection } from "./ConfigurationSection"; +import { FlatpakWorkaroundsSection } from "./FlatpakWorkaroundsSection"; +import { FpsMultiplierControl } from "./FpsMultiplierControl"; + +interface Props { + app: FlatpakApp; + busy: boolean; + onConfigChange: (appId: string, config: LsfgConfig) => Promise; + onWorkaroundChange: (appId: string, state: WorkaroundState) => Promise; +} + +export function FlatpakNowPlayingTab({ app, busy, onConfigChange, onWorkaroundChange }: Props) { + if (!app.config) return null; + const changeConfig = async ( + field: keyof LsfgConfig, + value: boolean | number | string | string[], + ) => { + await onConfigChange(app.app_id, { ...app.config!, [field]: value }); + }; + + return ( + + + + + + + + + onWorkaroundChange(app.app_id, state)} + /> + + ); +} -- cgit v1.2.3 From 0e51abafa2fed9fc829dceb48728d0e8bbf0dcaf Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:32:25 -0400 Subject: refactor: move flatpak setup into profiles tab --- src/components/SetupTab.tsx | 52 +++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index 1a62c2a..d769200 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,7 +1,6 @@ import { ButtonItem, Field, PanelSection, PanelSectionRow } from "@decky/ui"; import { type SteamBranchStatus } from "../api/lsfgApi"; import t from "../i18n/i18n"; -import { FlatpakSetupSection } from "./FlatpakSetupSection"; interface SetupTabProps { isInstalled: boolean; @@ -37,36 +36,33 @@ export function SetupTab(props: SetupTabProps) { : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); return ( - <> - + + + + + + + + {steamBranchStatus?.installed && ( - - - - {steamBranchStatus?.installed && ( - - - - )} - - - {buttonLabel} - - - - - + )} + + + {buttonLabel} + + + ); } -- cgit v1.2.3 From 64e3a2db3a538b4b538e6b0520943b5a90eff5a5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:32:58 -0400 Subject: feat: add flatpak profiles tab and now playing --- src/components/Content.tsx | 84 ++++++++++++++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 8f83e85..ffb6eef 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,18 +1,22 @@ import { Tabs } from "@decky/ui"; import { useEffect, useRef, useState } from "react"; -import { FaFileAlt, FaGamepad, FaList, FaTools } from "react-icons/fa"; +import { FaCube, FaFileAlt, FaGamepad, FaList, FaTools } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; +import { useFlatpakConfiguration } from "../hooks/useFlatpakConfiguration"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallation } from "../hooks/useLsfgHooks"; import { tabStyles } from "../styles"; import { ConfigFileTab } from "./ConfigFileTab"; import { ConfigurationTab } from "./ConfigurationTab"; +import { FlatpakNowPlayingTab } from "./FlatpakNowPlayingTab"; +import { FlatpakTab } from "./FlatpakTab"; import { NowPlayingTab } from "./NowPlayingTab"; import { SetupTab } from "./SetupTab"; const tabIcons = { nowPlaying: , games: , + flatpak: , configFile: , setup: , }; @@ -63,38 +67,46 @@ export function Content() { install, uninstall, } = useInstallation(reload); - const [tab, setTab] = useState("Setup"); - const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, true); - const previousRunningAppId = useRef(null); const setupComplete = isInstalled && losslessScalingInstalled && steamBranchStatus?.success === true && steamBranchStatus.installed && !steamBranchStatus.needs_switch; + const flatpak = useFlatpakConfiguration(setupComplete); + const [tab, setTab] = useState("Setup"); + const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, true); + const previousRunningWorkload = useRef(null); + const runningFlatpak = flatpak.runningApp; + const hasNowPlaying = Boolean(runningGame?.configured || runningFlatpak); + const runningWorkload = runningGame?.configured + ? `steam:${runningGame.appid}` + : runningFlatpak ? `flatpak:${runningFlatpak.app_id}` : null; useEffect(() => { if (!setupComplete) { setTab("Setup"); return; } - setTab((current) => current === "Setup" ? (runningGame?.configured ? "NowPlaying" : "Games") : current); - }, [runningGame?.appid, runningGame?.configured, setupComplete]); + setTab((current) => current === "Setup" ? (hasNowPlaying ? "NowPlaying" : "Games") : current); + }, [hasNowPlaying, setupComplete]); useEffect(() => { if (!setupComplete) return; - const appid = runningGame?.appid || null; - const previous = previousRunningAppId.current; - previousRunningAppId.current = appid; - if (appid && appid !== previous) setTab(runningGame?.configured ? "NowPlaying" : "Games"); - else if (!appid && previous) { + const previous = previousRunningWorkload.current; + previousRunningWorkload.current = runningWorkload; + if (runningWorkload && runningWorkload !== previous) setTab("NowPlaying"); + else if (!runningWorkload && previous) { setTab((current) => current === "NowPlaying" ? "Games" : current); } - }, [runningGame?.appid, runningGame?.configured, setupComplete]); + }, [runningWorkload, setupComplete]); useEffect(() => { - if (isInstalled) void reload(); - }, [isInstalled, reload]); + if (isInstalled) { + void reload(); + void flatpak.reload(); + } + }, [isInstalled, reload, flatpak.reload]); useEffect(() => { if (!showDebugTab && tab === "ConfigFile") setTab("Games"); @@ -120,19 +132,24 @@ export function Content() { /> ); + const nowPlaying = runningGame?.configured ? ( + handleConfigChange(field, value)} + /> + ) : runningFlatpak ? ( + + ) : null; + const tabs = setupComplete ? [ - ...(runningGame?.configured ? [{ - id: "NowPlaying", - title: tabIcons.nowPlaying, - content: ( - handleConfigChange(field, value)} - /> - ), - }] : []), + ...(nowPlaying ? [{ id: "NowPlaying", title: tabIcons.nowPlaying, content: nowPlaying }] : []), { id: "Games", title: tabIcons.games, @@ -153,6 +170,23 @@ export function Content() { /> ), }, + { + id: "Flatpak", + title: tabIcons.flatpak, + content: ( + + ), + }, ...(showDebugTab ? [{ id: "ConfigFile", title: tabIcons.configFile, content: }] : []), { id: "Setup", title: tabIcons.setup, content: setup }, ] -- cgit v1.2.3 From a6c8f95af3a28a7384d1fd4155bbd1e15cf36334 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:34:37 -0400 Subject: refactor: remove flatpak target integration --- src/utils/steamLaunchOptions.ts | 104 ++++------------------------------------ 1 file changed, 8 insertions(+), 96 deletions(-) (limited to 'src') diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index 685dcf9..f03eeab 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -24,7 +24,6 @@ export interface SteamLaunchOptionsSnapshot { appId: number; nonSteam: boolean; options: string; - target: string; details: SteamAppDetails; } export interface WrapperIntegrationResult { @@ -58,7 +57,6 @@ function snapshot(appId: number, nonSteam: boolean, details: SteamAppDetails): S appId, nonSteam, options: nonSteam ? details.strShortcutLaunchOptions || "" : details.strLaunchOptions || "", - target: nonSteam ? details.strShortcutExe || "" : "", details, }; } @@ -160,31 +158,6 @@ const isAssignment = (token: LaunchToken) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(tok const isLegacyToken = (value: string) => LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); const isWrapperToken = (value: string, wrapperPath: string) => decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); -function flatpakExecutable(value: string): string | undefined { - const decoded = decodeToken(value.trim()); - return decoded === "flatpak" || decoded === "/usr/bin/flatpak" || decoded === "usr/bin/flatpak" - ? "/usr/bin/flatpak" - : undefined; -} - -function wrappedFlatpakExecutable(target: string, wrapperPath: string, includeLegacy = true): string | undefined { - const tokens = tokenize(target); - if (tokens.length !== 2) return undefined; - const wrapper = tokens[0].value; - if (wrapper !== wrapperPath && !(includeLegacy && isLegacyToken(wrapper))) return undefined; - return flatpakExecutable(tokens[1].value); -} - -function directFlatpakExecutable(target: string, wrapperPath: string): string | undefined { - const tokens = tokenize(target); - if (tokens.length === 1) return flatpakExecutable(tokens[0].value); - return wrappedFlatpakExecutable(target, wrapperPath); -} - -function managedFlatpakTarget(wrapperPath: string, executable: string): string { - return `${wrapperPath} "${executable.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; -} - export const normalizeLaunchOptions = (options: string) => serialize(tokenize(options)); export const isLegacyWrapperToken = (value: string) => isLegacyToken(decodeToken(value)); @@ -280,14 +253,9 @@ export function hasWrapperLaunchIntegration(options: string, wrapperPath = DEFAU export function isWrapperIntegrationInstalled( steam: SteamLaunchOptionsSnapshot, - nonSteam: boolean, - directFlatpak = false, + _nonSteam: boolean, wrapperPath = DEFAULT_WRAPPER_PATH, ): boolean { - if (nonSteam && directFlatpak) { - const tokens = tokenize(steam.target); - return tokens.length === 2 && tokens[0].value === wrapperPath && flatpakExecutable(tokens[1].value) !== undefined; - } return hasWrapperLaunchIntegration(steam.options, wrapperPath); } @@ -328,18 +296,16 @@ async function writeVerified( previous: string, next: string, write: (value: string) => Promise, - read: (value: SteamLaunchOptionsSnapshot) => string, message: string, ): Promise { - const normalized = read === readOptions ? normalizeLaunchOptions : (value: string) => normalizeLaunchOptions(value); try { await write(next); - return await waitFor(appId, nonSteam, (value) => normalized(read(value)) === normalized(next), message); + return await waitFor(appId, nonSteam, (value) => normalizeLaunchOptions(value.options) === normalizeLaunchOptions(next), message); } catch (error) { const failure = asError(error); try { await write(previous); - await waitFor(appId, nonSteam, (value) => normalized(read(value)) === normalized(previous), `Steam did not restore the previous ${read === readOptions ? "launch options" : "shortcut Target"}`); + await waitFor(appId, nonSteam, (value) => normalizeLaunchOptions(value.options) === normalizeLaunchOptions(previous), "Steam did not restore the previous launch options"); } catch (rollback) { throw new Error(`${failure.message}; rollback also failed: ${asError(rollback).message}`); } @@ -347,19 +313,11 @@ async function writeVerified( } } -const readOptions = (value: SteamLaunchOptionsSnapshot) => value.options; -const readTarget = (value: SteamLaunchOptionsSnapshot) => value.target; - function writeOptions(appId: number, nonSteam: boolean, value: string): Promise { const setter = nonSteam ? apps()?.SetShortcutLaunchOptions : apps()?.SetAppLaunchOptions; if (!setter) return Promise.reject(new Error(`Steam ${nonSteam ? "shortcut " : ""}launch options API is unavailable`)); return Promise.resolve(setter.call(apps(), appId, value)); } -function writeTarget(appId: number, value: string): Promise { - const setter = apps()?.SetShortcutExe; - if (!setter) return Promise.reject(new Error("Steam shortcut Target API is unavailable")); - return Promise.resolve(setter.call(apps(), appId, value)); -} export function updateSteamLaunchOptions( appId: number, @@ -371,7 +329,7 @@ export function updateSteamLaunchOptions( const next = transform(current.options); return next === current.options ? current : writeVerified( appId, nonSteam, current.options, next, - (value) => writeOptions(appId, nonSteam, value), readOptions, + (value) => writeOptions(appId, nonSteam, value), "Steam did not accept the launch options", ); }); @@ -382,41 +340,16 @@ export function installWrapperIntegration( nonSteam: boolean, wrapperPath: string, commandTokenAdded = false, - directFlatpak = false, ): Promise { return queued(appId, nonSteam, async () => { - let current = await readSteamLaunchOptions(appId, nonSteam); - if (nonSteam && directFlatpak) { - const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); - const launchOptionsChanged = cleaned !== current.options; - if (launchOptionsChanged) { - current = await writeVerified( - appId, true, current.options, cleaned, - (value) => writeOptions(appId, true, value), readOptions, - "Steam did not accept shortcut launch options", - ); - } - const executable = directFlatpakExecutable(current.target, wrapperPath); - if (!executable) throw new Error("Flatpak shortcut Target is not a supported direct Flatpak executable"); - const target = managedFlatpakTarget(wrapperPath, executable); - if (normalizeLaunchOptions(current.target) === normalizeLaunchOptions(target)) { - return { snapshot: current, commandTokenAdded: false, changed: launchOptionsChanged }; - } - const value = await writeVerified( - appId, true, current.target, target, - (next) => writeTarget(appId, next), readTarget, - "Steam did not accept the shortcut Target", - ); - return { snapshot: value, commandTokenAdded: false, changed: true }; - } - + const current = await readSteamLaunchOptions(appId, nonSteam); const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); const alreadyInstalled = hasWrapperLaunchIntegration(current.options, wrapperPath); const rewrite = installLaunchOption(cleaned, wrapperPath, nonSteam); if (rewrite.options === current.options) return { snapshot: current, commandTokenAdded, changed: false }; const value = await writeVerified( appId, nonSteam, current.options, rewrite.options, - (options) => writeOptions(appId, nonSteam, options), readOptions, + (options) => writeOptions(appId, nonSteam, options), "Steam did not accept the launch options", ); return { snapshot: value, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded, changed: true }; @@ -428,34 +361,13 @@ export function removeWrapperIntegration( nonSteam: boolean, wrapperPath: string, commandTokenAdded = false, - directFlatpak = false, ): Promise { return queued(appId, nonSteam, async () => { - let current = await readSteamLaunchOptions(appId, nonSteam); - if (nonSteam && directFlatpak) { - const cleaned = cleanupPluginLaunchOptions(current.options, wrapperPath); - if (cleaned !== current.options) { - current = await writeVerified( - appId, true, current.options, cleaned, - (value) => writeOptions(appId, true, value), readOptions, - "Steam did not clean shortcut launch options", - ); - } - const wrapped = wrappedFlatpakExecutable(current.target, wrapperPath); - if (wrapped) { - return writeVerified( - appId, true, current.target, wrapped, - (target) => writeTarget(appId, target), readTarget, - "Steam did not restore the shortcut Target", - ); - } - if (flatpakExecutable(current.target)) return current; - throw new Error("Shortcut Target changed externally; refusing to restore it"); - } + const current = await readSteamLaunchOptions(appId, nonSteam); const next = cleanupPluginAssignments(removeWrapperLaunchOption(current.options, wrapperPath, commandTokenAdded)); return next === current.options ? current : writeVerified( appId, nonSteam, current.options, next, - (options) => writeOptions(appId, nonSteam, options), readOptions, + (options) => writeOptions(appId, nonSteam, options), "Steam did not clean the launch options", ); }); -- cgit v1.2.3 From 4dc1a3b7cc6b02ed06a8349d85b0eae36af10b0b Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:35:05 -0400 Subject: refactor: remove flatpak mode from steam workarounds --- src/hooks/usePerAppWorkarounds.ts | 35 +++++++---------------------------- 1 file changed, 7 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index 30bbc6b..c2b8904 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -43,7 +43,6 @@ export interface WorkaroundSnapshot { wrapperOwned: boolean; integrationInstalled: boolean; commandTokenAdded: boolean; - directFlatpak: boolean; } interface PerAppWorkarounds { @@ -62,7 +61,6 @@ function makeSnapshot( steam: SteamLaunchOptionsSnapshot, result: Awaited>, nonSteam: boolean, - directFlatpak: boolean, ): WorkaroundSnapshot { if (!result.state) throw new Error("Workaround state is not initialized for this profile"); const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); @@ -71,34 +69,26 @@ function makeSnapshot( state: result.state, wrapperPath, wrapperOwned: result.wrapper_owned === true, - integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, directFlatpak, wrapperPath), + integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, wrapperPath), commandTokenAdded: result.command_token_added === true, - directFlatpak, }; } async function adoptWorkaroundState( appId: string, nonSteam: boolean, - directFlatpak: boolean, wrapperPath: string, ): Promise { let integration: Awaited> | null = null; try { - integration = await installWrapperIntegration( - Number(appId), - nonSteam, - wrapperPath, - false, - directFlatpak, - ); + integration = await installWrapperIntegration(Number(appId), nonSteam, wrapperPath, false); const finalized = await setWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, integration.commandTokenAdded, ); if (!finalized.success) throw new Error(finalized.error || "Could not finalize workaround state"); - return makeSnapshot(integration.snapshot, finalized, nonSteam, directFlatpak); + return makeSnapshot(integration.snapshot, finalized, nonSteam); } catch (error) { let rollbackSucceeded = true; if (integration?.changed) { @@ -108,7 +98,6 @@ async function adoptWorkaroundState( nonSteam, wrapperPath, integration.commandTokenAdded, - directFlatpak, ); } catch { rollbackSucceeded = false; @@ -122,11 +111,7 @@ async function adoptWorkaroundState( } } -export function usePerAppWorkarounds( - appId: string, - nonSteam: boolean, - directFlatpak = false, -): PerAppWorkarounds { +export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWorkarounds { const [status, setStatus] = useState("loading"); const [snapshot, setSnapshot] = useState(null); const [error, setError] = useState(null); @@ -143,12 +128,11 @@ export function usePerAppWorkarounds( return adoptWorkaroundState( appId, nonSteam, - directFlatpak, result.wrapper_path || getDefaultWrapperPath(), ); } - return makeSnapshot(steam, result, nonSteam, directFlatpak); - }, [appId, directFlatpak, nonSteam, numericAppId]); + return makeSnapshot(steam, result, nonSteam); + }, [appId, nonSteam, numericAppId]); const applySnapshot = useCallback((next: WorkaroundSnapshot) => { setSnapshot(next); @@ -183,12 +167,7 @@ export function usePerAppWorkarounds( setSnapshot((current) => current ? { ...current, steam, - integrationInstalled: isWrapperIntegrationInstalled( - steam, - nonSteam, - current.directFlatpak, - current.wrapperPath, - ), + integrationInstalled: isWrapperIntegrationInstalled(steam, nonSteam, current.wrapperPath), } : current); }, (subscriptionError) => { -- cgit v1.2.3 From 1de34909f7caa0afc9c5b2745112ce29173eda69 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:35:25 -0400 Subject: refactor: keep steam workarounds transport agnostic --- src/components/WorkaroundsSection.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/components/WorkaroundsSection.tsx b/src/components/WorkaroundsSection.tsx index 050992c..3de5ec1 100644 --- a/src/components/WorkaroundsSection.tsx +++ b/src/components/WorkaroundsSection.tsx @@ -8,7 +8,6 @@ import type { WorkaroundField } from "../hooks/usePerAppWorkarounds"; interface WorkaroundsSectionProps { appId: string; nonSteam: boolean; - directFlatpak?: boolean; onRepair?: () => Promise; } @@ -78,9 +77,9 @@ function usePersistentCollapsed() { return [collapsed, () => setCollapsed((value) => !value)] as const; } -export function WorkaroundsSection({ appId, nonSteam, directFlatpak = false, onRepair }: WorkaroundsSectionProps) { +export function WorkaroundsSection({ appId, nonSteam, onRepair }: WorkaroundsSectionProps) { const [collapsed, toggleCollapsed] = usePersistentCollapsed(); - const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam, directFlatpak); + const { status, snapshot, refresh, update, error } = usePerAppWorkarounds(appId, nonSteam); const [repairing, setRepairing] = useState(false); const state = snapshot?.state; const controlsDisabled = status !== "ready" || state === undefined || snapshot?.wrapperOwned !== true || snapshot.integrationInstalled !== true; -- cgit v1.2.3 From f4b67511ddbe32948927ce73b5f3e067755a904d Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:35:33 -0400 Subject: refactor: simplify steam workaround target --- src/components/GameConfigurationControls.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/components/GameConfigurationControls.tsx b/src/components/GameConfigurationControls.tsx index a7e3fec..7025f78 100644 --- a/src/components/GameConfigurationControls.tsx +++ b/src/components/GameConfigurationControls.tsx @@ -10,7 +10,7 @@ interface Props { autoFocusFpsMultiplier?: boolean; onFpsMultiplierFocused?: () => void; showWorkarounds?: boolean; - workaroundTarget?: Pick; + workaroundTarget?: Pick; onRepairWorkaround?: () => Promise; } @@ -36,7 +36,6 @@ export function GameConfigurationControls({ )} -- cgit v1.2.3 From e6d6ec2a0944be5f3d348e06c5031c94159910df Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:36:02 -0400 Subject: refactor: keep steam profiles flatpak agnostic --- src/hooks/useGameConfiguration.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 4131d0f..8d56a62 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -23,7 +23,6 @@ async function getSteamShortcuts(): Promise { appid: String(appid >>> 0), name, nonSteam: true, - directFlatpak: false, }]; }); } catch { @@ -91,7 +90,7 @@ export function useGameConfiguration() { const name = app.display_name || installed?.name; if (!name) return setRunningGame(null); setRunningGame((current) => current?.appid === appid ? current : { - ...(installed || { appid, name, nonSteam: false, directFlatpak: false }), + ...(installed || { appid, name, nonSteam: false }), name, configured: games.some((game) => game.appid === appid), }); @@ -111,7 +110,7 @@ export function useGameConfiguration() { const targets = useMemo(() => { 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, directFlatpak: false, configured: true }); + 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]); @@ -137,7 +136,6 @@ export function useGameConfiguration() { target.nonSteam, wrapperPath, commandTokenAdded, - target.directFlatpak === true, ); stateWriteAttempted = true; const saved = await setWorkaroundState( @@ -156,7 +154,6 @@ export function useGameConfiguration() { target.nonSteam, wrapperPath, integration.commandTokenAdded, - target.directFlatpak === true, ); } catch (rollbackError) { showErrorToast("Workaround rollback failed", asError(rollbackError).message); @@ -187,7 +184,6 @@ export function useGameConfiguration() { target.nonSteam, wrapperPath, existing.command_token_added === true, - target.directFlatpak === true, ); const removed = await removeWorkaroundState(target.appid); if (!removed.success) throw new Error(removed.error || "Could not remove workaround state"); -- cgit v1.2.3 From 1949dd018bd7492c77736e19f9a25b14367187ff Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:36:31 -0400 Subject: refactor: separate flatpak from games selector --- src/components/GameConfigurationSelector.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 1c95820..1f0bc73 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -35,7 +35,6 @@ function usePersistentCollapsed(key: string) { } function targetDescription(game: GameTarget): string { - if (game.directFlatpak) return "Non-Steam · Direct Flatpak"; return game.nonSteam ? "Non-Steam" : "Steam"; } @@ -135,7 +134,7 @@ export function GameConfigurationSelector({ showModal( void onEnableAll()} -- cgit v1.2.3 From 59b9148054e2f0c7dcd33b0e5393899d7a92f93e Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:36:50 -0400 Subject: refactor: keep game profiles steam scoped --- src/components/ConfigurationTab.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 18575b4..a6d4c2a 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -99,11 +99,7 @@ export function ConfigurationTab({ } const profileLabel = selectedTarget?.name || "Game profile"; - const profileTransport = selectedTarget - ? selectedTarget.directFlatpak - ? "Non-Steam · Direct Flatpak" - : selectedTarget.nonSteam ? "Non-Steam" : "Steam" - : "Game"; + const profileTransport = selectedTarget?.nonSteam ? "Non-Steam" : "Steam"; const profileDescription = selectedTarget ? `${profileTransport} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}` : "Game is no longer available"; -- cgit v1.2.3 From eb714e77e494e3af8163ffceac7cb6e6d788440c Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:38:30 -0400 Subject: refactor: remove flatpak transport from steam now playing --- src/components/NowPlayingTab.tsx | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index 1bc331f..c067dc0 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -13,7 +13,6 @@ interface Props { } function targetDescription(game: GameTarget): string { - if (game.directFlatpak) return "Non-Steam · Direct Flatpak"; return game.nonSteam ? "Non-Steam" : "Steam"; } -- cgit v1.2.3 From a69ab9976905640f816b3a84d13fbc5848ffae65 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:38:38 -0400 Subject: refactor: remove shortcut target api types --- src/types.d.ts | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/types.d.ts b/src/types.d.ts index e5db40d..ebcf32c 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -16,7 +16,6 @@ declare module "*.jpg" { interface SteamAppDetails { strLaunchOptions?: string; strShortcutLaunchOptions?: string; - strShortcutExe?: string; strShortcutStartDir?: string; } @@ -31,7 +30,6 @@ interface SteamApps { ): SteamAppDetailsRegistration; SetAppLaunchOptions(appId: number, options: string): void | Promise; SetShortcutLaunchOptions(appId: number, options: string): void | Promise; - SetShortcutExe(appId: number, executable: string): void | Promise; TerminateApp(appId: string, param1: boolean): void; GetAllShortcuts?(): Promise; } -- cgit v1.2.3 From 2258a5e5e96ad3c3d2e9eb5a3bdb58e747b2d0ad Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:38:57 -0400 Subject: refactor: remove direct flatpak steam metadata --- src/api/lsfgApi.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 850efa9..3643363 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -41,7 +41,6 @@ export interface InstalledGame { appid: string; name: string; nonSteam: boolean; - directFlatpak?: boolean; executable?: string; arguments?: string; startDir?: string; @@ -115,15 +114,23 @@ export interface FlatpakApp { profile: string; config?: LsfgConfig | null; workarounds: WorkaroundState; - active?: boolean; - pid?: string; error?: string | null; } +export interface RunningFlatpakApp { + app_id: string; + active: boolean; + pid?: string; +} + export interface FlatpakAppsResult extends ApiResult { apps?: FlatpakApp[]; } +export interface RunningFlatpakAppsResult extends ApiResult { + apps?: RunningFlatpakApp[]; +} + export interface FlatpakAppResult extends ApiResult, Partial { app_id: string; } @@ -136,10 +143,9 @@ export const getConfigFileContent = callable<[], FileContentResult>("get_config_ export const getFlatpakApps = callable<[], FlatpakAppsResult>("get_flatpak_apps"); export const enableFlatpakApp = callable<[string], FlatpakAppResult>("enable_flatpak_app"); export const updateFlatpakConfig = callable<[string, LsfgConfig], FlatpakAppResult>("update_flatpak_config"); -export const getFlatpakWorkaroundState = callable<[string], WorkaroundStateResult>("get_flatpak_workaround_state"); export const setFlatpakWorkaroundState = callable<[string, WorkaroundState], WorkaroundStateResult>("set_flatpak_workaround_state"); export const removeFlatpakApp = callable<[string], FlatpakAppResult>("remove_flatpak_app"); -export const getRunningFlatpakApps = callable<[], FlatpakAppsResult>("get_running_flatpak_apps"); +export const getRunningFlatpakApps = callable<[], RunningFlatpakAppsResult>("get_running_flatpak_apps"); export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs"); export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); export const updateGameConfig = callable<[string, string, LsfgConfig], GameConfigResult>("update_game_config"); -- cgit v1.2.3 From 08404e49b9f21c16f3c69cdcd9eefe0250f594e2 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:39:02 -0400 Subject: refactor: remove obsolete flatpak setup section --- src/components/FlatpakSetupSection.tsx | 110 --------------------------------- 1 file changed, 110 deletions(-) delete mode 100644 src/components/FlatpakSetupSection.tsx (limited to 'src') diff --git a/src/components/FlatpakSetupSection.tsx b/src/components/FlatpakSetupSection.tsx deleted file mode 100644 index 0119250..0000000 --- a/src/components/FlatpakSetupSection.tsx +++ /dev/null @@ -1,110 +0,0 @@ -import { ButtonItem, Field, PanelSection, PanelSectionRow } from "@decky/ui"; -import { useCallback, useEffect, useState } from "react"; -import { - getFlatpakApps, - prepareFlatpakApp, - removeFlatpakApp, - type FlatpakApp, -} from "../api/lsfgApi"; -import { showErrorToast } from "../utils/toastUtils"; - -interface Props { - enabled: boolean; -} - -export function FlatpakSetupSection({ enabled }: Props) { - const [apps, setApps] = useState([]); - const [loading, setLoading] = useState(false); - const [busyApp, setBusyApp] = useState(""); - const [error, setError] = useState(null); - - const load = useCallback(async () => { - if (!enabled) { - setApps([]); - setError(null); - return; - } - setLoading(true); - try { - const result = await getFlatpakApps(); - if (!result.success) throw new Error(result.error || "Could not list Flatpak applications"); - setApps(result.apps || []); - setError(null); - } catch (loadError) { - const message = loadError instanceof Error ? loadError.message : String(loadError); - setError(message); - } finally { - setLoading(false); - } - }, [enabled]); - - useEffect(() => { - void load(); - }, [load]); - - const toggle = async (app: FlatpakApp) => { - if (busyApp || (app.prepared && !app.owned)) return; - setBusyApp(app.app_id); - try { - const result = app.prepared - ? await removeFlatpakApp(app.app_id) - : await prepareFlatpakApp(app.app_id); - if (!result.success) throw new Error(result.error || "Flatpak setup failed"); - await load(); - } catch (operationError) { - const message = operationError instanceof Error ? operationError.message : String(operationError); - showErrorToast("Flatpak setup failed", message); - } finally { - setBusyApp(""); - } - }; - - if (!enabled) return null; - - return ( - - - - - {error && ( - - - - )} - {apps.map((app) => { - const busy = busyApp === app.app_id; - const description = [ - app.app_id, - app.runtime_branch ? `runtime ${app.runtime_branch}` : null, - app.error, - ].filter(Boolean).join(" · "); - const label = busy - ? "Working..." - : app.prepared - ? app.owned ? "Remove" : "Prepared externally" - : app.error ? "Unavailable" : "Prepare"; - return ( - - - void toggle(app)} - > - {label} - - - - ); - })} - - void load()}> - {loading ? "Refreshing..." : "Refresh Flatpaks"} - - - - ); -} -- cgit v1.2.3 From 5c7c1c3547a9f298301fb2b3a03c0f76f24a2866 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:40:08 -0400 Subject: perf: map running flatpaks from cached app state --- src/hooks/useFlatpakConfiguration.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/hooks/useFlatpakConfiguration.ts b/src/hooks/useFlatpakConfiguration.ts index e8fae99..d5e6f7e 100644 --- a/src/hooks/useFlatpakConfiguration.ts +++ b/src/hooks/useFlatpakConfiguration.ts @@ -8,13 +8,14 @@ import { updateFlatpakConfig, type FlatpakApp, type LsfgConfig, + type RunningFlatpakApp, type WorkaroundState, } from "../api/lsfgApi"; import { showErrorToast } from "../utils/toastUtils"; export function useFlatpakConfiguration(enabled: boolean) { const [apps, setApps] = useState([]); - const [runningApps, setRunningApps] = useState([]); + const [runningApps, setRunningApps] = useState([]); const [loading, setLoading] = useState(false); const [busyAppId, setBusyAppId] = useState(""); @@ -87,8 +88,10 @@ export function useFlatpakConfiguration(enabled: boolean) { const runningApp = useMemo(() => { if (runningApps.length === 0) return null; - return runningApps.find((app) => app.active) || (runningApps.length === 1 ? runningApps[0] : null); - }, [runningApps]); + const running = runningApps.find((app) => app.active) || (runningApps.length === 1 ? runningApps[0] : null); + if (!running) return null; + return apps.find((app) => app.app_id === running.app_id) || null; + }, [apps, runningApps]); return { apps, -- cgit v1.2.3 From dff6251e620767b28a81915389b16c916aac2cb0 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:44:52 -0400 Subject: refactor: trim unused steam shortcut fields --- src/api/lsfgApi.ts | 3 --- 1 file changed, 3 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 3643363..3d4890e 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -41,9 +41,6 @@ export interface InstalledGame { appid: string; name: string; nonSteam: boolean; - executable?: string; - arguments?: string; - startDir?: string; } export interface GlobalConfig { -- cgit v1.2.3 From 9783834314956ea4765faadff7ae964151a7ff18 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:45:15 -0400 Subject: refactor: trim unused steam detail fields --- src/types.d.ts | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/types.d.ts b/src/types.d.ts index ebcf32c..4adad61 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -16,7 +16,6 @@ declare module "*.jpg" { interface SteamAppDetails { strLaunchOptions?: string; strShortcutLaunchOptions?: string; - strShortcutStartDir?: string; } interface SteamAppDetailsRegistration { -- cgit v1.2.3 From 817cdf3d5344e961df05f408354d0387c731f5ce Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:46:19 -0400 Subject: fix: derive now playing config from running app --- src/hooks/useGameConfiguration.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 8d56a62..17eb867 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -116,6 +116,9 @@ export function useGameConfiguration() { }, [games, installedGames, runningGame]); const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); const config = games.find((game) => game.appid === selectedAppId)?.config || template; + const runningConfig = runningGame + ? games.find((game) => game.appid === runningGame.appid)?.config || template + : template; const ensureTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { if (!installedGames.some((game) => game.appid === target.appid)) return true; @@ -263,5 +266,5 @@ export function useGameConfiguration() { } }, [load, removeTargetWorkarounds, targets]); - return { config, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, repair, resetSelected, resetAll, reload: load }; + return { config, runningConfig, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, repair, resetSelected, resetAll, reload: load }; } -- cgit v1.2.3 From 69f5b6f884064e93f15570d8c7ceda5d610c39dd Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:46:41 -0400 Subject: fix: use running steam config in now playing --- src/components/Content.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index ffb6eef..241ab92 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -45,6 +45,7 @@ function usePersistentBoolean(key: string, defaultValue: boolean) { export function Content() { const { config, + runningConfig, targets, runningGame, setSelectedAppId, @@ -135,8 +136,10 @@ export function Content() { const nowPlaying = runningGame?.configured ? ( handleConfigChange(field, value)} + config={runningConfig} + onConfigChange={async (field, value) => { + await save({ ...runningConfig, [field]: value }, true); + }} /> ) : runningFlatpak ? ( Date: Thu, 10 Sep 2026 16:47:17 -0400 Subject: fix: make steam profile saves app scoped --- src/hooks/useGameConfiguration.ts | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 17eb867..2e39f5e 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -89,11 +89,19 @@ export function useGameConfiguration() { const installed = installedGames.find((game) => game.appid === appid); const name = app.display_name || installed?.name; if (!name) return setRunningGame(null); - setRunningGame((current) => current?.appid === appid ? current : { + const next: GameTarget = { ...(installed || { appid, name, nonSteam: false }), name, configured: games.some((game) => game.appid === appid), - }); + }; + setRunningGame((current) => ( + current?.appid === next.appid + && current.name === next.name + && current.nonSteam === next.nonSteam + && current.configured === next.configured + ? current + : next + )); }; poll(); const interval = window.setInterval(poll, 2000); @@ -197,13 +205,22 @@ export function useGameConfiguration() { } }, [installedGames]); - const save = useCallback(async (next: ConfigurationData, cleanupLaunchOptions = false) => { - const selectedTarget = targets.find((target) => target.appid === selectedAppId); - if (!selectedTarget?.name) return; - if (cleanupLaunchOptions && !(await ensureTargetWorkarounds(selectedTarget))) return; - const result = await updateGameConfig(selectedAppId, selectedTarget.name, next); + const saveFor = useCallback(async (appid: string, next: ConfigurationData, cleanupLaunchOptions = false) => { + const target = targets.find((item) => item.appid === appid); + if (!target?.name) return false; + if (cleanupLaunchOptions && !(await ensureTargetWorkarounds(target))) return false; + const result = await updateGameConfig(appid, target.name, next); if (result.success) await load(); - }, [ensureTargetWorkarounds, load, selectedAppId, targets]); + return result.success; + }, [ensureTargetWorkarounds, load, targets]); + + const save = useCallback( + async (next: ConfigurationData, cleanupLaunchOptions = false) => { + if (!selectedAppId) return false; + return saveFor(selectedAppId, next, cleanupLaunchOptions); + }, + [saveFor, selectedAppId], + ); const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); @@ -266,5 +283,5 @@ export function useGameConfiguration() { } }, [load, removeTargetWorkarounds, targets]); - return { config, runningConfig, games, targets, runningGame, selectedAppId, setSelectedAppId, save, enable, enableAll, repair, resetSelected, resetAll, reload: load }; + return { config, runningConfig, games, targets, runningGame, selectedAppId, setSelectedAppId, save, saveFor, enable, enableAll, repair, resetSelected, resetAll, reload: load }; } -- cgit v1.2.3 From 912237e98462eaa22084809c11446f5e031d08b9 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:47:38 -0400 Subject: fix: save now playing steam profile by app id --- src/components/Content.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 241ab92..a300f6f 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -50,6 +50,7 @@ export function Content() { runningGame, setSelectedAppId, save, + saveFor, enable, enableAll, repair, @@ -138,7 +139,7 @@ export function Content() { game={runningGame} config={runningConfig} onConfigChange={async (field, value) => { - await save({ ...runningConfig, [field]: value }, true); + await saveFor(runningGame.appid, { ...runningConfig, [field]: value }, true); }} /> ) : runningFlatpak ? ( -- cgit v1.2.3 From c3778706ab420494479740e19df08c0c3c5b2693 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 10 Sep 2026 16:48:39 -0400 Subject: fix: preserve config callback return type --- src/components/Content.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index a300f6f..ce3c018 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -118,7 +118,9 @@ export function Content() { fieldName: keyof ConfigurationData, value: boolean | number | string | string[], cleanupLaunchOptions = false, - ) => save({ ...config, [fieldName]: value }, cleanupLaunchOptions); + ) => { + await save({ ...config, [fieldName]: value }, cleanupLaunchOptions); + }; const setup = ( Date: Thu, 10 Sep 2026 20:49:05 -0400 Subject: fix; correct flatpak extension sources --- src/components/FlatpakTab.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/components/FlatpakTab.tsx b/src/components/FlatpakTab.tsx index 6392d59..c5e27f5 100644 --- a/src/components/FlatpakTab.tsx +++ b/src/components/FlatpakTab.tsx @@ -40,12 +40,12 @@ export function FlatpakTab({ if (!selectedAppId) { return ( - + {/* - + */} {apps.map((app) => { const status = app.enabled ? app.app_id === runningApp?.app_id ? "Enabled · Running" : "Enabled" -- cgit v1.2.3 From d2bfdafa92f3d31cc5392bf8a5a1f1df5c2358ce Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 09:05:14 -0400 Subject: flatpak correctness, ui alignment, tests --- src/api/lsfgApi.ts | 1 + src/components/CollapsibleItemGroup.tsx | 79 ++++++++++++++++++++++++++ src/components/Content.tsx | 56 +++++++++++++----- src/components/FlatpakNowPlayingTab.tsx | 26 +++++---- src/components/FlatpakTab.tsx | 79 +++++++++++++++++++------- src/components/GameConfigurationSelector.tsx | 85 ++++------------------------ src/hooks/useFlatpakConfiguration.ts | 59 ++++++++++++++----- src/utils/nowPlaying.ts | 54 ++++++++++++++++++ 8 files changed, 304 insertions(+), 135 deletions(-) create mode 100644 src/components/CollapsibleItemGroup.tsx create mode 100644 src/utils/nowPlaying.ts (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 3d4890e..f3b7fa1 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -118,6 +118,7 @@ export interface RunningFlatpakApp { app_id: string; active: boolean; pid?: string; + start_time?: number | null; } export interface FlatpakAppsResult extends ApiResult { diff --git a/src/components/CollapsibleItemGroup.tsx b/src/components/CollapsibleItemGroup.tsx new file mode 100644 index 0000000..a66a8ba --- /dev/null +++ b/src/components/CollapsibleItemGroup.tsx @@ -0,0 +1,79 @@ +import { ButtonItem, Field, PanelSectionRow } from "@decky/ui"; +import { type RefObject } from "react"; +import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; + +export interface CollapsibleItem { + id: string; + label: string; + description: string; +} + +export const collapsibleItemGroupStyles = ` + .LSFG_GameGroupCollapseButton_Container > div > div > div > button, + .LSFG_GameGroupCollapseButton_Container > div > div > div > div > button { + height: 24px !important; + min-height: 24px !important; + padding: 0 !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + } + + .LSFG_GameGroupCollapseButton_Container svg { + display: block; + margin: 0; + } +`; + +interface Props { + title: string; + items: CollapsibleItem[]; + collapsed: boolean; + onToggle: () => void; + onSelect: (id: string) => void; + toggleRef?: RefObject; +} + +export function CollapsibleItemGroup({ + title, + items, + collapsed, + onToggle, + onSelect, + toggleRef, +}: Props) { + if (items.length === 0) return null; + + return ( + <> + + + + +
+ + {collapsed ? : } + +
+
+ {!collapsed && items.map((item) => ( + + onSelect(item.id)} + highlightOnFocus + /> + + ))} + + ); +} diff --git a/src/components/Content.tsx b/src/components/Content.tsx index ce3c018..0d49f89 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,4 +1,4 @@ -import { Tabs } from "@decky/ui"; +import { Field, PanelSection, PanelSectionRow, Tabs } from "@decky/ui"; import { useEffect, useRef, useState } from "react"; import { FaCube, FaFileAlt, FaGamepad, FaList, FaTools } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; @@ -6,6 +6,7 @@ import { useFlatpakConfiguration } from "../hooks/useFlatpakConfiguration"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallation } from "../hooks/useLsfgHooks"; import { tabStyles } from "../styles"; +import { resolveNowPlayingTarget } from "../utils/nowPlaying"; import { ConfigFileTab } from "./ConfigFileTab"; import { ConfigurationTab } from "./ConfigurationTab"; import { FlatpakNowPlayingTab } from "./FlatpakNowPlayingTab"; @@ -80,10 +81,13 @@ export function Content() { const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, true); const previousRunningWorkload = useRef(null); const runningFlatpak = flatpak.runningApp; - const hasNowPlaying = Boolean(runningGame?.configured || runningFlatpak); - const runningWorkload = runningGame?.configured - ? `steam:${runningGame.appid}` - : runningFlatpak ? `flatpak:${runningFlatpak.app_id}` : null; + const nowPlayingTarget = resolveNowPlayingTarget(runningGame, runningFlatpak); + const hasNowPlaying = Boolean(nowPlayingTarget); + const runningWorkload = nowPlayingTarget + ? nowPlayingTarget.kind === "flatpak" + ? `flatpak:${nowPlayingTarget.app.app_id}` + : `steam:${nowPlayingTarget.game.appid}` + : null; useEffect(() => { if (!setupComplete) { @@ -136,26 +140,27 @@ export function Content() { /> ); - const nowPlaying = runningGame?.configured ? ( + const nowPlaying = nowPlayingTarget?.kind === "steam" ? ( { - await saveFor(runningGame.appid, { ...runningConfig, [field]: value }, true); + await saveFor(nowPlayingTarget.game.appid, { ...runningConfig, [field]: value }, true); }} /> - ) : runningFlatpak ? ( + ) : nowPlayingTarget?.kind === "flatpak" ? ( - ) : null; + ) : ( + + ); const tabs = setupComplete ? [ - ...(nowPlaying ? [{ id: "NowPlaying", title: tabIcons.nowPlaying, content: nowPlaying }] : []), + { id: "NowPlaying", title: tabIcons.nowPlaying, content: nowPlaying }, { id: "Games", title: tabIcons.games, @@ -198,13 +203,34 @@ export function Content() { ] : [{ id: "Setup", title: tabIcons.setup, content: setup }]; + const availableTabIds = new Set(tabs.map(({ id }) => id)); + const activeTab = availableTabIds.has(tab) ? tab : setupComplete ? "Games" : "Setup"; + return (
- + { + if (availableTabIds.has(nextTab)) setTab(nextTab); + }} + tabs={tabs} + /> +
+ ); +} + +function NowPlayingTabPlaceholder() { + return ( +
+ + + + +
); } diff --git a/src/components/FlatpakNowPlayingTab.tsx b/src/components/FlatpakNowPlayingTab.tsx index 9e5a0db..9623b11 100644 --- a/src/components/FlatpakNowPlayingTab.tsx +++ b/src/components/FlatpakNowPlayingTab.tsx @@ -1,17 +1,16 @@ import { Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; -import type { FlatpakApp, LsfgConfig, WorkaroundState } from "../api/lsfgApi"; +import type { FlatpakApp, LsfgConfig } from "../api/lsfgApi"; +import type { GameTarget } from "../hooks/useGameConfiguration"; import { ConfigurationSection } from "./ConfigurationSection"; -import { FlatpakWorkaroundsSection } from "./FlatpakWorkaroundsSection"; import { FpsMultiplierControl } from "./FpsMultiplierControl"; interface Props { app: FlatpakApp; - busy: boolean; + launcher: GameTarget | null; onConfigChange: (appId: string, config: LsfgConfig) => Promise; - onWorkaroundChange: (appId: string, state: WorkaroundState) => Promise; } -export function FlatpakNowPlayingTab({ app, busy, onConfigChange, onWorkaroundChange }: Props) { +export function FlatpakNowPlayingTab({ app, launcher, onConfigChange }: Props) { if (!app.config) return null; const changeConfig = async ( field: keyof LsfgConfig, @@ -24,16 +23,21 @@ export function FlatpakNowPlayingTab({ app, busy, onConfigChange, onWorkaroundCh - + + {launcher && ( + + + + )} - onWorkaroundChange(app.app_id, state)} - /> ); } diff --git a/src/components/FlatpakTab.tsx b/src/components/FlatpakTab.tsx index c5e27f5..31bfc2d 100644 --- a/src/components/FlatpakTab.tsx +++ b/src/components/FlatpakTab.tsx @@ -1,7 +1,8 @@ import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses } from "@decky/ui"; -import { useCallback, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import type { FlatpakApp, LsfgConfig, WorkaroundState } from "../api/lsfgApi"; +import { CollapsibleItemGroup, collapsibleItemGroupStyles } from "./CollapsibleItemGroup"; import { ConfigurationSection } from "./ConfigurationSection"; import { FlatpakWorkaroundsSection } from "./FlatpakWorkaroundsSection"; import { FpsMultiplierControl } from "./FpsMultiplierControl"; @@ -19,6 +20,24 @@ interface Props { onWorkaroundChange: (appId: string, state: WorkaroundState) => Promise; } +function usePersistentCollapsed(key: string) { + const [collapsed, setCollapsed] = useState(() => { + try { + return localStorage.getItem(key) !== "false"; + } catch { + return true; + } + }); + + useEffect(() => { + try { + localStorage.setItem(key, String(collapsed)); + } catch {} + }, [collapsed, key]); + + return [collapsed, () => setCollapsed((value) => !value)] as const; +} + export function FlatpakTab({ apps, runningApp, @@ -36,31 +55,47 @@ export function FlatpakTab({ [apps, selectedAppId], ); const close = useCallback(() => setSelectedAppId(null), []); + const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed("lsfg-flatpak-enabled-collapsed-v1"); + const [availableCollapsed, toggleAvailable] = usePersistentCollapsed("lsfg-flatpak-available-collapsed-v1"); + const enabledToggleRef = useRef(null); + + const enabledApps = useMemo( + () => apps.filter((app) => app.enabled).sort((a, b) => a.app_name.localeCompare(b.app_name)), + [apps], + ); + const availableApps = useMemo( + () => apps.filter((app) => !app.enabled).sort((a, b) => a.app_name.localeCompare(b.app_name)), + [apps], + ); + const itemFor = (app: FlatpakApp) => ({ + id: app.app_id, + label: app.app_name, + description: `${app.app_id} · ${app.prepared && !app.owned ? "Prepared externally" : "Available"}`, + }); if (!selectedAppId) { return ( - {/* - - */} - {apps.map((app) => { - const status = app.enabled - ? app.app_id === runningApp?.app_id ? "Enabled · Running" : "Enabled" - : app.prepared && !app.owned ? "Prepared externally" : "Available"; - return ( - - setSelectedAppId(app.app_id)} - highlightOnFocus - /> - - ); - })} + + ({ + id: app.app_id, + label: app.app_name, + description: `${app.app_id}${app.app_id === runningApp?.app_id ? " · Running" : ""}`, + }))} + collapsed={enabledCollapsed} + onToggle={toggleEnabled} + onSelect={setSelectedAppId} + toggleRef={enabledToggleRef} + /> + {apps.length === 0 && !loading && ( diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index 1f0bc73..ee87423 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -1,7 +1,7 @@ import { ButtonItem, ConfirmModal, Field, PanelSectionRow, showModal } from "@decky/ui"; -import { useEffect, useRef, useState, type RefObject } from "react"; -import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; +import { useEffect, useRef, useState } from "react"; import { GameTarget } from "../hooks/useGameConfiguration"; +import { CollapsibleItemGroup, collapsibleItemGroupStyles } from "./CollapsibleItemGroup"; interface Props { targets: GameTarget[]; @@ -38,57 +38,6 @@ function targetDescription(game: GameTarget): string { return game.nonSteam ? "Non-Steam" : "Steam"; } -function GameGroup({ - title, - games, - collapsed, - onToggle, - onSelect, - toggleRef, -}: { - title: string; - games: GameTarget[]; - collapsed: boolean; - onToggle: () => void; - onSelect: (appid: string) => void; - toggleRef?: RefObject; -}) { - if (games.length === 0) return null; - - return ( - <> - - - - -
- - {collapsed ? : } - -
-
- {!collapsed && games.map((game) => ( - - onSelect(game.appid)} - highlightOnFocus - /> - - ))} - - ); -} - export function GameConfigurationSelector({ targets, runningGame, @@ -105,6 +54,11 @@ export function GameConfigurationSelector({ }); const enabledGames = sortGames(targets.filter((game) => game.configured)); const availableGames = sortGames(targets.filter((game) => !game.configured)); + const toItem = (game: GameTarget) => ({ + id: game.appid, + label: game.name, + description: targetDescription(game), + }); const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(ENABLED_COLLAPSED_KEY); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); const enabledToggleRef = useRef(null); @@ -146,39 +100,24 @@ export function GameConfigurationSelector({ return ( <> {targets.length === 0 && ( )} - - ([]); const [runningApps, setRunningApps] = useState([]); @@ -58,39 +66,62 @@ export function useFlatpakConfiguration(enabled: boolean) { return () => window.clearInterval(interval); }, [enabled, pollRunning]); - const operate = useCallback(async (appId: string, operation: () => Promise<{ success: boolean; error?: string | null }>) => { - if (busyAppId) return false; + const operate = useCallback(async ( + appId: string, + operation: () => Promise, + refresh = true, + ): Promise => { + if (busyAppId) return { success: false }; setBusyAppId(appId); try { const result = await operation(); if (!result.success) throw new Error(result.error || "Flatpak operation failed"); - await reload(); - await pollRunning(); - return true; + if (refresh) { + await reload(); + await pollRunning(); + } + return result; } catch (error) { showErrorToast("Flatpak operation failed", error instanceof Error ? error.message : String(error)); - return false; + return { success: false, error: error instanceof Error ? error.message : String(error) }; } finally { setBusyAppId(""); } }, [busyAppId, pollRunning, reload]); - const enableApp = useCallback((appId: string) => operate(appId, () => enableFlatpakApp(appId)), [operate]); - const removeApp = useCallback((appId: string) => operate(appId, () => removeFlatpakApp(appId)), [operate]); + const enableApp = useCallback(async (appId: string) => ( + await operate(appId, () => enableFlatpakApp(appId)) + ).success, [operate]); + const removeApp = useCallback(async (appId: string) => ( + await operate(appId, () => removeFlatpakApp(appId)) + ).success, [operate]); const updateConfig = useCallback( - (appId: string, config: LsfgConfig) => operate(appId, () => updateFlatpakConfig(appId, config)), + async (appId: string, config: LsfgConfig) => { + const result = await operate(appId, () => updateFlatpakConfig(appId, config), false); + if (result.success) { + setApps((current) => current.map((app) => ( + app.app_id === appId ? { ...app, config: result.config || config } : app + ))); + } + return result.success; + }, [operate], ); const updateWorkarounds = useCallback( - (appId: string, state: WorkaroundState) => operate(appId, () => setFlatpakWorkaroundState(appId, state)), + async (appId: string, state: WorkaroundState) => { + const result = await operate(appId, () => setFlatpakWorkaroundState(appId, state), false); + if (result.success) { + setApps((current) => current.map((app) => ( + app.app_id === appId ? { ...app, workarounds: result.state || state } : app + ))); + } + return result.success; + }, [operate], ); const runningApp = useMemo(() => { - if (runningApps.length === 0) return null; - const running = runningApps.find((app) => app.active) || (runningApps.length === 1 ? runningApps[0] : null); - if (!running) return null; - return apps.find((app) => app.app_id === running.app_id) || null; + return selectMostRecentRunningFlatpak(apps, runningApps); }, [apps, runningApps]); return { diff --git a/src/utils/nowPlaying.ts b/src/utils/nowPlaying.ts new file mode 100644 index 0000000..a207321 --- /dev/null +++ b/src/utils/nowPlaying.ts @@ -0,0 +1,54 @@ +import type { FlatpakApp, RunningFlatpakApp } from "../api/lsfgApi"; +import type { GameTarget } from "../hooks/useGameConfiguration"; + +export type NowPlayingTarget = + | { + kind: "flatpak"; + app: FlatpakApp; + launcher: GameTarget | null; + } + | { + kind: "steam"; + game: GameTarget; + }; + +function numericValue(value: number | null | undefined): number { + return typeof value === "number" && Number.isFinite(value) ? value : -1; +} + +function numericPid(value: string | undefined): number { + return value && /^\d+$/.test(value) ? Number(value) : -1; +} + +export function selectMostRecentRunningFlatpak( + apps: FlatpakApp[], + runningApps: RunningFlatpakApp[], +): FlatpakApp | null { + const candidates = runningApps + .map((running) => ({ + running, + app: apps.find((app) => app.app_id === running.app_id) || null, + })) + .filter((candidate): candidate is { running: RunningFlatpakApp; app: FlatpakApp } => candidate.app !== null) + .sort((a, b) => { + if (a.running.active !== b.running.active) return a.running.active ? -1 : 1; + const startDifference = numericValue(b.running.start_time) - numericValue(a.running.start_time); + if (startDifference !== 0) return startDifference; + const pidDifference = numericPid(b.running.pid) - numericPid(a.running.pid); + if (pidDifference !== 0) return pidDifference; + return a.running.app_id.localeCompare(b.running.app_id); + }); + + return candidates[0]?.app || null; +} + +export function resolveNowPlayingTarget( + runningGame: GameTarget | null, + runningFlatpak: FlatpakApp | null, +): NowPlayingTarget | null { + if (runningFlatpak) { + return { kind: "flatpak", app: runningFlatpak, launcher: runningGame }; + } + if (runningGame?.configured) return { kind: "steam", game: runningGame }; + return null; +} -- cgit v1.2.3 From 18af8d1de5c7d12af674018ce819cc91480cf51a Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 09:09:29 -0400 Subject: fix tab change jutter --- src/components/ConfigurationTab.tsx | 1 - src/components/Content.tsx | 30 +++++++++++------------------- src/styles.ts | 13 +++++++++++++ 3 files changed, 24 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index a6d4c2a..12f36a5 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -88,7 +88,6 @@ export function ConfigurationTab({ diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 0d49f89..dc8c54f 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,5 +1,5 @@ -import { Field, PanelSection, PanelSectionRow, Tabs } from "@decky/ui"; -import { useEffect, useRef, useState } from "react"; +import { Tabs } from "@decky/ui"; +import { useEffect, useRef, useState, type FocusEvent } from "react"; import { FaCube, FaFileAlt, FaGamepad, FaList, FaTools } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; import { useFlatpakConfiguration } from "../hooks/useFlatpakConfiguration"; @@ -79,6 +79,7 @@ export function Content() { const flatpak = useFlatpakConfiguration(setupComplete); const [tab, setTab] = useState("Setup"); const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, true); + const [contentFocused, setContentFocused] = useState(false); const previousRunningWorkload = useRef(null); const runningFlatpak = flatpak.runningApp; const nowPlayingTarget = resolveNowPlayingTarget(runningGame, runningFlatpak); @@ -154,13 +155,11 @@ export function Content() { launcher={nowPlayingTarget.launcher} onConfigChange={flatpak.updateConfig} /> - ) : ( - - ); + ) : null; const tabs = setupComplete ? [ - { id: "NowPlaying", title: tabIcons.nowPlaying, content: nowPlaying }, + ...(nowPlaying ? [{ id: "NowPlaying", title: tabIcons.nowPlaying, content: nowPlaying }] : []), { id: "Games", title: tabIcons.games, @@ -205,11 +204,16 @@ export function Content() { const availableTabIds = new Set(tabs.map(({ id }) => id)); const activeTab = availableTabIds.has(tab) ? tab : setupComplete ? "Games" : "Setup"; + const handleFocusCapture = (event: FocusEvent) => { + const focusedElement = event.target as HTMLElement | null; + setContentFocused(!focusedElement?.closest?.('[role="tab"]')); + }; return (
); } - -function NowPlayingTabPlaceholder() { - return ( -
- - - - - -
- ); -} diff --git a/src/styles.ts b/src/styles.ts index 1bc089b..d197451 100644 --- a/src/styles.ts +++ b/src/styles.ts @@ -31,4 +31,17 @@ export const tabStyles = ` display: block; margin: 0; } + + .lsfg-vk-tabs--content-focused [role="tablist"][aria-orientation="horizontal"], + .lsfg-vk-tabs--content-focused [role="tablist"][aria-orientation="horizontal"] > div, + .lsfg-vk-tabs--content-focused [role="tablist"][aria-orientation="horizontal"] > div > div, + .lsfg-vk-tabs--content-focused [role="tablist"][aria-orientation="horizontal"] [role="tab"] { + animation: none !important; + transition: none !important; + } + + .lsfg-vk-tabs--content-focused [role="tablist"][aria-orientation="horizontal"] > div > div { + scroll-behavior: auto !important; + scroll-snap-type: none !important; + } `; -- cgit v1.2.3 From 9138886fd5315eb0e8c6a4a549a9d44f93ba3cde Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 09:30:30 -0400 Subject: consistent tab collapsed toggles on flatpak --- src/components/FlatpakTab.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/components/FlatpakTab.tsx b/src/components/FlatpakTab.tsx index 31bfc2d..b46eb28 100644 --- a/src/components/FlatpakTab.tsx +++ b/src/components/FlatpakTab.tsx @@ -20,6 +20,9 @@ interface Props { onWorkaroundChange: (appId: string, state: WorkaroundState) => Promise; } +const ENABLED_COLLAPSED_KEY = "lsfg-flatpak-enabled-collapsed-v2"; +const AVAILABLE_COLLAPSED_KEY = "lsfg-flatpak-available-collapsed-v2"; + function usePersistentCollapsed(key: string) { const [collapsed, setCollapsed] = useState(() => { try { @@ -55,8 +58,8 @@ export function FlatpakTab({ [apps, selectedAppId], ); const close = useCallback(() => setSelectedAppId(null), []); - const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed("lsfg-flatpak-enabled-collapsed-v1"); - const [availableCollapsed, toggleAvailable] = usePersistentCollapsed("lsfg-flatpak-available-collapsed-v1"); + const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(ENABLED_COLLAPSED_KEY); + const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); const enabledToggleRef = useRef(null); const enabledApps = useMemo( -- cgit v1.2.3 From a8388009b2ba141caafe7f2e35f7029d93e7811f Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 09:38:35 -0400 Subject: handle edge cases on flatpaks and ordering --- src/components/CollapsibleItemGroup.tsx | 20 +++++++++++++++++- src/components/Content.tsx | 2 +- src/components/FlatpakTab.tsx | 24 ++------------------- src/components/GameConfigurationSelector.tsx | 22 ++------------------ src/hooks/useFlatpakConfiguration.ts | 4 +--- src/utils/nowPlaying.ts | 31 ++++++++++++++++++---------- 6 files changed, 45 insertions(+), 58 deletions(-) (limited to 'src') diff --git a/src/components/CollapsibleItemGroup.tsx b/src/components/CollapsibleItemGroup.tsx index a66a8ba..037b34f 100644 --- a/src/components/CollapsibleItemGroup.tsx +++ b/src/components/CollapsibleItemGroup.tsx @@ -1,5 +1,5 @@ import { ButtonItem, Field, PanelSectionRow } from "@decky/ui"; -import { type RefObject } from "react"; +import { useEffect, useState, type RefObject } from "react"; import { RiArrowDownSFill, RiArrowUpSFill } from "react-icons/ri"; export interface CollapsibleItem { @@ -25,6 +25,24 @@ export const collapsibleItemGroupStyles = ` } `; +export function usePersistentCollapsed(key: string) { + const [collapsed, setCollapsed] = useState(() => { + try { + return localStorage.getItem(key) !== "false"; + } catch { + return true; + } + }); + + useEffect(() => { + try { + localStorage.setItem(key, String(collapsed)); + } catch {} + }, [collapsed, key]); + + return [collapsed, () => setCollapsed((value) => !value)] as const; +} + interface Props { title: string; items: CollapsibleItem[]; diff --git a/src/components/Content.tsx b/src/components/Content.tsx index dc8c54f..422eec8 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -86,7 +86,7 @@ export function Content() { const hasNowPlaying = Boolean(nowPlayingTarget); const runningWorkload = nowPlayingTarget ? nowPlayingTarget.kind === "flatpak" - ? `flatpak:${nowPlayingTarget.app.app_id}` + ? `flatpak:${nowPlayingTarget.app.app_id}:${nowPlayingTarget.launcher?.appid ?? ""}` : `steam:${nowPlayingTarget.game.appid}` : null; diff --git a/src/components/FlatpakTab.tsx b/src/components/FlatpakTab.tsx index b46eb28..0b20da0 100644 --- a/src/components/FlatpakTab.tsx +++ b/src/components/FlatpakTab.tsx @@ -1,8 +1,8 @@ import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses } from "@decky/ui"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import type { FlatpakApp, LsfgConfig, WorkaroundState } from "../api/lsfgApi"; -import { CollapsibleItemGroup, collapsibleItemGroupStyles } from "./CollapsibleItemGroup"; +import { CollapsibleItemGroup, collapsibleItemGroupStyles, usePersistentCollapsed } from "./CollapsibleItemGroup"; import { ConfigurationSection } from "./ConfigurationSection"; import { FlatpakWorkaroundsSection } from "./FlatpakWorkaroundsSection"; import { FpsMultiplierControl } from "./FpsMultiplierControl"; @@ -23,24 +23,6 @@ interface Props { const ENABLED_COLLAPSED_KEY = "lsfg-flatpak-enabled-collapsed-v2"; const AVAILABLE_COLLAPSED_KEY = "lsfg-flatpak-available-collapsed-v2"; -function usePersistentCollapsed(key: string) { - const [collapsed, setCollapsed] = useState(() => { - try { - return localStorage.getItem(key) !== "false"; - } catch { - return true; - } - }); - - useEffect(() => { - try { - localStorage.setItem(key, String(collapsed)); - } catch {} - }, [collapsed, key]); - - return [collapsed, () => setCollapsed((value) => !value)] as const; -} - export function FlatpakTab({ apps, runningApp, @@ -60,7 +42,6 @@ export function FlatpakTab({ const close = useCallback(() => setSelectedAppId(null), []); const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(ENABLED_COLLAPSED_KEY); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); - const enabledToggleRef = useRef(null); const enabledApps = useMemo( () => apps.filter((app) => app.enabled).sort((a, b) => a.app_name.localeCompare(b.app_name)), @@ -90,7 +71,6 @@ export function FlatpakTab({ collapsed={enabledCollapsed} onToggle={toggleEnabled} onSelect={setSelectedAppId} - toggleRef={enabledToggleRef} /> { - try { - return localStorage.getItem(key) !== "false"; - } catch { - return true; - } - }); - - useEffect(() => { - try { - localStorage.setItem(key, String(collapsed)); - } catch {} - }, [collapsed, key]); - - return [collapsed, () => setCollapsed((value) => !value)] as const; -} - function targetDescription(game: GameTarget): string { return game.nonSteam ? "Non-Steam" : "Steam"; } diff --git a/src/hooks/useFlatpakConfiguration.ts b/src/hooks/useFlatpakConfiguration.ts index ce881f0..6ff7a79 100644 --- a/src/hooks/useFlatpakConfiguration.ts +++ b/src/hooks/useFlatpakConfiguration.ts @@ -120,9 +120,7 @@ export function useFlatpakConfiguration(enabled: boolean) { [operate], ); - const runningApp = useMemo(() => { - return selectMostRecentRunningFlatpak(apps, runningApps); - }, [apps, runningApps]); + const runningApp = useMemo(() => selectMostRecentRunningFlatpak(apps, runningApps), [apps, runningApps]); return { apps, diff --git a/src/utils/nowPlaying.ts b/src/utils/nowPlaying.ts index a207321..2e0a876 100644 --- a/src/utils/nowPlaying.ts +++ b/src/utils/nowPlaying.ts @@ -29,25 +29,34 @@ export function selectMostRecentRunningFlatpak( running, app: apps.find((app) => app.app_id === running.app_id) || null, })) - .filter((candidate): candidate is { running: RunningFlatpakApp; app: FlatpakApp } => candidate.app !== null) - .sort((a, b) => { - if (a.running.active !== b.running.active) return a.running.active ? -1 : 1; - const startDifference = numericValue(b.running.start_time) - numericValue(a.running.start_time); - if (startDifference !== 0) return startDifference; - const pidDifference = numericPid(b.running.pid) - numericPid(a.running.pid); - if (pidDifference !== 0) return pidDifference; - return a.running.app_id.localeCompare(b.running.app_id); - }); + .filter((candidate): candidate is { running: RunningFlatpakApp; app: FlatpakApp } => candidate.app !== null); + const activeCandidates = candidates.filter(({ running }) => running.active); + const eligibleCandidates = activeCandidates.length > 0 + ? activeCandidates + : candidates.length === 1 + ? candidates + : []; - return candidates[0]?.app || null; + eligibleCandidates.sort((a, b) => { + const startDifference = numericValue(b.running.start_time) - numericValue(a.running.start_time); + if (startDifference !== 0) return startDifference; + const pidDifference = numericPid(b.running.pid) - numericPid(a.running.pid); + if (pidDifference !== 0) return pidDifference; + return a.running.app_id.localeCompare(b.running.app_id); + }); + + return eligibleCandidates[0]?.app || null; } export function resolveNowPlayingTarget( runningGame: GameTarget | null, runningFlatpak: FlatpakApp | null, ): NowPlayingTarget | null { + if (runningGame && !runningGame.nonSteam) { + return runningGame.configured ? { kind: "steam", game: runningGame } : null; + } if (runningFlatpak) { - return { kind: "flatpak", app: runningFlatpak, launcher: runningGame }; + return { kind: "flatpak", app: runningFlatpak, launcher: runningGame?.nonSteam ? runningGame : null }; } if (runningGame?.configured) return { kind: "steam", game: runningGame }; return null; -- cgit v1.2.3 From bc2669b6050da7acdf9e1dda2b77444734852559 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 10:00:19 -0400 Subject: workaround for new client update, ui cuts off in game --- src/components/Content.tsx | 22 +++++++++++++--------- src/styles.ts | 4 ++++ 2 files changed, 17 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 422eec8..32e9bf8 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,5 +1,5 @@ import { Tabs } from "@decky/ui"; -import { useEffect, useRef, useState, type FocusEvent } from "react"; +import { useEffect, useRef, useState, type FocusEvent, type ReactNode } from "react"; import { FaCube, FaFileAlt, FaGamepad, FaList, FaTools } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; import { useFlatpakConfiguration } from "../hooks/useFlatpakConfiguration"; @@ -141,6 +141,10 @@ export function Content() { /> ); + const tabContent = (content: ReactNode) => ( +
{content}
+ ); + const nowPlaying = nowPlayingTarget?.kind === "steam" ? ( + />, ), }, { id: "Flatpak", title: tabIcons.flatpak, - content: ( + content: tabContent( + />, ), }, - ...(showDebugTab ? [{ id: "ConfigFile", title: tabIcons.configFile, content: }] : []), - { id: "Setup", title: tabIcons.setup, content: setup }, + ...(showDebugTab ? [{ id: "ConfigFile", title: tabIcons.configFile, content: tabContent() }] : []), + { id: "Setup", title: tabIcons.setup, content: tabContent(setup) }, ] - : [{ id: "Setup", title: tabIcons.setup, content: setup }]; + : [{ id: "Setup", title: tabIcons.setup, content: tabContent(setup) }]; const availableTabIds = new Set(tabs.map(({ id }) => id)); const activeTab = availableTabIds.has(tab) ? tab : setupComplete ? "Games" : "Setup"; diff --git a/src/styles.ts b/src/styles.ts index d197451..58c6b01 100644 --- a/src/styles.ts +++ b/src/styles.ts @@ -10,6 +10,10 @@ export const tabStyles = ` padding-right: 8px !important; } + .lsfg-vk-tabs .lsfg-vk-tab-content { + padding-bottom: 96px; // workaround for in-game bottom bar padding behaving differently than in launcher, remove later? + } + .lsfg-vk-tabs [role="tablist"] { display: flex; flex-wrap: nowrap; -- cgit v1.2.3 From 0be6ccdd1a8ecfe386281451cf4c49d052f6dda4 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 10:13:22 -0400 Subject: move inline styping --- src/components/CollapsibleItemGroup.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/components/CollapsibleItemGroup.tsx b/src/components/CollapsibleItemGroup.tsx index 037b34f..29fe945 100644 --- a/src/components/CollapsibleItemGroup.tsx +++ b/src/components/CollapsibleItemGroup.tsx @@ -9,6 +9,11 @@ export interface CollapsibleItem { } export const collapsibleItemGroupStyles = ` + .LSFG_GameGroupCollapseButton_Container { + margin-top: -2px; + margin-bottom: 4px; + } + .LSFG_GameGroupCollapseButton_Container > div > div > div > button, .LSFG_GameGroupCollapseButton_Container > div > div > div > div > button { height: 24px !important; @@ -71,7 +76,6 @@ export function CollapsibleItemGroup({
Date: Fri, 11 Sep 2026 10:23:23 -0400 Subject: compact now playing info --- src/components/FlatpakNowPlayingTab.tsx | 27 +++++++++++---------------- src/components/NowPlayingSummary.tsx | 16 ++++++++++++++++ src/components/NowPlayingTab.tsx | 12 ++++++------ 3 files changed, 33 insertions(+), 22 deletions(-) create mode 100644 src/components/NowPlayingSummary.tsx (limited to 'src') diff --git a/src/components/FlatpakNowPlayingTab.tsx b/src/components/FlatpakNowPlayingTab.tsx index 9623b11..89f7f49 100644 --- a/src/components/FlatpakNowPlayingTab.tsx +++ b/src/components/FlatpakNowPlayingTab.tsx @@ -1,8 +1,9 @@ -import { Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import { Focusable } from "@decky/ui"; import type { FlatpakApp, LsfgConfig } from "../api/lsfgApi"; import type { GameTarget } from "../hooks/useGameConfiguration"; import { ConfigurationSection } from "./ConfigurationSection"; import { FpsMultiplierControl } from "./FpsMultiplierControl"; +import { NowPlayingSummary } from "./NowPlayingSummary"; interface Props { app: FlatpakApp; @@ -21,21 +22,15 @@ export function FlatpakNowPlayingTab({ app, launcher, onConfigChange }: Props) { return ( - - - - - {launcher && ( - - - - )} - + detail !== null)} + /> diff --git a/src/components/NowPlayingSummary.tsx b/src/components/NowPlayingSummary.tsx new file mode 100644 index 0000000..adc5d10 --- /dev/null +++ b/src/components/NowPlayingSummary.tsx @@ -0,0 +1,16 @@ +import { Field, PanelSection, PanelSectionRow } from "@decky/ui"; + +interface Props { + title: string; + details: string[]; +} + +export function NowPlayingSummary({ title, details }: Props) { + return ( + + + + + + ); +} diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index c067dc0..4c22fb7 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -1,7 +1,8 @@ -import { Field, Focusable, PanelSection, PanelSectionRow } from "@decky/ui"; +import { Focusable } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; import { GameTarget } from "../hooks/useGameConfiguration"; import { GameConfigurationControls } from "./GameConfigurationControls"; +import { NowPlayingSummary } from "./NowPlayingSummary"; interface Props { game: GameTarget; @@ -23,11 +24,10 @@ export function NowPlayingTab({ }: Props) { return ( - - - - - + Date: Fri, 11 Sep 2026 11:08:12 -0400 Subject: better uninstall cleanup --- src/api/lsfgApi.ts | 19 ++++++++ src/components/ConfigurationSection.tsx | 5 +- src/components/ConfigurationTab.tsx | 15 +----- src/components/Content.tsx | 13 ++++-- src/components/SetupTab.tsx | 82 +++++++++++++++++++++++---------- src/hooks/useGameConfiguration.ts | 46 +++++++++++++++++- src/hooks/useLsfgHooks.ts | 9 +++- src/hooks/usePerAppWorkarounds.ts | 2 + 8 files changed, 141 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index f3b7fa1..e050f62 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -64,6 +64,18 @@ export interface WorkaroundStateResult extends ApiResult { wrapper_path?: string; wrapper_owned?: boolean; command_token_added?: boolean; + non_steam?: boolean; +} + +export interface WorkaroundApp { + appid: string; + non_steam: boolean; + command_token_added: boolean; +} + +export interface WorkaroundAppsResult extends ApiResult { + apps?: WorkaroundApp[]; + wrapper_path?: string; } export interface GameConfigsResult extends ApiResult { @@ -71,6 +83,10 @@ export interface GameConfigsResult extends ApiResult { games?: GameConfigEntry[]; } +export interface GlobalConfigResult extends ApiResult { + global_config?: GlobalConfig; +} + export interface GameConfigResult extends ApiResult { appid?: string; exists?: boolean; @@ -149,11 +165,14 @@ export const getInstalledGames = callable<[], InstalledGamesResult>("get_install 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"); +export const updateGlobalConfig = callable<[GlobalConfig], GlobalConfigResult>("update_global_config"); export const getWorkaroundState = callable<[string], WorkaroundStateResult>("get_workaround_state"); export const setWorkaroundState = callable<[ string, WorkaroundState, boolean, + boolean, ], WorkaroundStateResult>("set_workaround_state"); export const removeWorkaroundState = callable<[string], WorkaroundStateResult>("remove_workaround_state"); +export const getWorkaroundApps = callable<[], WorkaroundAppsResult>("get_workaround_apps"); export const getDebugFileContents = callable<[], DebugFileContentsResult>("get_debug_file_contents"); diff --git a/src/components/ConfigurationSection.tsx b/src/components/ConfigurationSection.tsx index 1f17264..6996bcd 100644 --- a/src/components/ConfigurationSection.tsx +++ b/src/components/ConfigurationSection.tsx @@ -1,6 +1,6 @@ import { PanelSectionRow, ToggleField, SliderField } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; -import { FLOW_SCALE, PERFORMANCE_MODE, OVERRIDE_PRESENT_MODE, PRESERVE_SWAPCHAIN_IMAGE_COUNT, NO_FP16 } from "../config/configSchema"; +import { FLOW_SCALE, PERFORMANCE_MODE, OVERRIDE_PRESENT_MODE, PRESERVE_SWAPCHAIN_IMAGE_COUNT } from "../config/configSchema"; interface ConfigurationSectionProps { config: ConfigurationData; @@ -12,9 +12,6 @@ export function ConfigurationSection({ config, onConfigChange }: ConfigurationSe onConfigChange(FLOW_SCALE, value)} /> - - onConfigChange(NO_FP16, !value)} /> - onConfigChange(PERFORMANCE_MODE, value)} /> diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 12f36a5..37a7867 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,4 +1,4 @@ -import { ButtonItem, ConfirmModal, DialogButton, Focusable, PanelSection, PanelSectionRow, ToggleField, gamepadDialogClasses, showModal } from "@decky/ui"; +import { ButtonItem, ConfirmModal, DialogButton, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses, showModal } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; @@ -11,8 +11,6 @@ interface ConfigurationTabProps { config: ConfigurationData; targets: GameTarget[]; runningGame: GameTarget | null; - showDebugTab: boolean; - onShowDebugTabChange: (value: boolean) => void; onSelect: (appid: string) => void; onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; onEnable: (appid: string) => Promise; @@ -26,8 +24,6 @@ export function ConfigurationTab({ config, targets, runningGame, - showDebugTab, - onShowDebugTabChange, onSelect, onConfigChange, onEnable, @@ -84,15 +80,6 @@ export function ConfigurationTab({ onConfiguredToggleFocused={clearConfiguredToggleFocusRequest} /> - - - - - ); } diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 32e9bf8..91775df 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -47,16 +47,19 @@ export function Content() { const { config, runningConfig, + globalConfig, targets, runningGame, setSelectedAppId, save, saveFor, + updateGlobal, enable, enableAll, repair, resetSelected, resetAll, + cleanupAllWorkarounds, reload, } = useGameConfiguration(); const { @@ -69,7 +72,7 @@ export function Content() { isUninstalling, install, uninstall, - } = useInstallation(reload); + } = useInstallation(reload, cleanupAllWorkarounds); const setupComplete = isInstalled && losslessScalingInstalled && @@ -78,7 +81,7 @@ export function Content() { !steamBranchStatus.needs_switch; const flatpak = useFlatpakConfiguration(setupComplete); const [tab, setTab] = useState("Setup"); - const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, true); + const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, false); const [contentFocused, setContentFocused] = useState(false); const previousRunningWorkload = useRef(null); const runningFlatpak = flatpak.runningApp; @@ -136,6 +139,10 @@ export function Content() { steamBranchStatus={steamBranchStatus} isInstalling={isInstalling} isUninstalling={isUninstalling} + globalConfig={globalConfig} + showDebugTab={showDebugTab} + onGlobalConfigChange={updateGlobal} + onShowDebugTabChange={setShowDebugTab} onInstall={() => void install()} onUninstall={() => void uninstall()} /> @@ -172,8 +179,6 @@ export function Content() { config={config} targets={targets} runningGame={runningGame} - showDebugTab={showDebugTab} - onShowDebugTabChange={setShowDebugTab} onSelect={setSelectedAppId} onConfigChange={(field, value) => handleConfigChange(field, value, true)} onEnable={enable} diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx index d769200..ff072cb 100644 --- a/src/components/SetupTab.tsx +++ b/src/components/SetupTab.tsx @@ -1,5 +1,5 @@ -import { ButtonItem, Field, PanelSection, PanelSectionRow } from "@decky/ui"; -import { type SteamBranchStatus } from "../api/lsfgApi"; +import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; +import { type GlobalConfig, type SteamBranchStatus } from "../api/lsfgApi"; import t from "../i18n/i18n"; interface SetupTabProps { @@ -10,6 +10,10 @@ interface SetupTabProps { steamBranchStatus: SteamBranchStatus | null; isInstalling: boolean; isUninstalling: boolean; + globalConfig: GlobalConfig; + showDebugTab: boolean; + onGlobalConfigChange: (config: GlobalConfig) => Promise; + onShowDebugTabChange: (value: boolean) => void; onInstall: () => void; onUninstall: () => void; } @@ -23,6 +27,10 @@ export function SetupTab(props: SetupTabProps) { steamBranchStatus, isInstalling, isUninstalling, + globalConfig, + showDebugTab, + onGlobalConfigChange, + onShowDebugTabChange, onInstall, onUninstall, } = props; @@ -36,33 +44,57 @@ export function SetupTab(props: SetupTabProps) { : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); return ( - - - - - - - - {steamBranchStatus?.installed && ( + <> + + + + + {steamBranchStatus?.installed && ( + + + + )} + + + {buttonLabel} + + + + {isInstalled && ( + <> + + + void onGlobalConfigChange({ ...globalConfig, no_fp16: !value })} + /> + + + + + + + + )} - - - {buttonLabel} - - - + ); } diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index 2e39f5e..fd8dfb1 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; -import { getGameConfigs, getInstalledGames, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; +import { getGameConfigs, getInstalledGames, getWorkaroundApps, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, updateGlobalConfig as saveGlobalConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; import { getDefaultWrapperPath, installWrapperIntegration, removeWrapperIntegration } from "../utils/steamLaunchOptions"; import { showErrorToast } from "../utils/toastUtils"; @@ -153,6 +153,7 @@ export function useGameConfiguration() { target.appid, state, integration.commandTokenAdded, + target.nonSteam, ); if (!saved.success) throw new Error(saved.error || "Could not save workaround state"); return true; @@ -205,6 +206,40 @@ export function useGameConfiguration() { } }, [installedGames]); + const cleanupAllWorkarounds = useCallback(async (): Promise => { + try { + const result = await getWorkaroundApps(); + if (!result.success) throw new Error(result.error || "Could not read workaround state"); + const targetsByAppId = new Map(targets.map((target) => [target.appid, target])); + const cleaned = new Set(); + const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); + + for (const entry of result.apps || []) { + const target = targetsByAppId.get(entry.appid); + const nonSteam = target?.nonSteam ?? entry.non_steam; + await removeWrapperIntegration( + Number(entry.appid), + nonSteam, + wrapperPath, + entry.command_token_added, + ); + const removed = await removeWorkaroundState(entry.appid); + if (!removed.success) throw new Error(removed.error || "Could not remove workaround state"); + cleaned.add(entry.appid); + } + + // Also clean configured targets whose sidecar entry was lost. This + // removes an old wrapper and only the plugin-managed launch pieces. + for (const target of targets.filter((item) => item.configured && installedGames.some((game) => game.appid === item.appid))) { + if (!cleaned.has(target.appid) && !(await removeTargetWorkarounds(target))) return false; + } + return true; + } catch (error) { + showErrorToast("Could not clean up game launch options", asError(error).message); + return false; + } + }, [installedGames, removeTargetWorkarounds, targets]); + const saveFor = useCallback(async (appid: string, next: ConfigurationData, cleanupLaunchOptions = false) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; @@ -222,6 +257,13 @@ export function useGameConfiguration() { [saveFor, selectedAppId], ); + const updateGlobal = useCallback(async (next: GlobalConfig): Promise => { + const result = await saveGlobalConfig(next); + if (!result.success) return false; + setGlobalConfig(result.global_config || next); + return true; + }, []); + const enable = useCallback(async (appid: string) => { const target = targets.find((item) => item.appid === appid); if (!target?.name) return false; @@ -283,5 +325,5 @@ export function useGameConfiguration() { } }, [load, removeTargetWorkarounds, targets]); - return { config, runningConfig, games, targets, runningGame, selectedAppId, setSelectedAppId, save, saveFor, enable, enableAll, repair, resetSelected, resetAll, reload: load }; + return { config, runningConfig, globalConfig, targets, runningGame, selectedAppId, setSelectedAppId, save, saveFor, updateGlobal, enable, enableAll, repair, resetSelected, resetAll, cleanupAllWorkarounds, reload: load }; } diff --git a/src/hooks/useLsfgHooks.ts b/src/hooks/useLsfgHooks.ts index 9beb749..0f51e90 100644 --- a/src/hooks/useLsfgHooks.ts +++ b/src/hooks/useLsfgHooks.ts @@ -13,7 +13,10 @@ import { showUninstallSuccessToast, } from "../utils/toastUtils"; -export function useInstallation(reloadConfig?: () => Promise) { +export function useInstallation( + reloadConfig?: () => Promise, + beforeUninstall?: () => Promise, +) { const [isInstalled, setIsInstalled] = useState(false); const [installationStatus, setInstallationStatus] = useState(""); const [losslessScalingInstalled, setLosslessScalingInstalled] = useState(false); @@ -77,6 +80,10 @@ export function useInstallation(reloadConfig?: () => Promise) { setIsUninstalling(true); setInstallationStatus("Uninstalling lsfg-vk..."); try { + if (beforeUninstall && !(await beforeUninstall())) { + setInstallationStatus("Uninstallation cancelled: could not clean up launch options"); + return; + } const result = await uninstallLsfgVk(); if (!result.success) { setInstallationStatus(`Uninstallation failed: ${result.error}`); diff --git a/src/hooks/usePerAppWorkarounds.ts b/src/hooks/usePerAppWorkarounds.ts index c2b8904..ab33bb2 100644 --- a/src/hooks/usePerAppWorkarounds.ts +++ b/src/hooks/usePerAppWorkarounds.ts @@ -86,6 +86,7 @@ async function adoptWorkaroundState( appId, DEFAULT_WORKAROUND_STATE, integration.commandTokenAdded, + nonSteam, ); if (!finalized.success) throw new Error(finalized.error || "Could not finalize workaround state"); return makeSnapshot(integration.snapshot, finalized, nonSteam); @@ -206,6 +207,7 @@ export function usePerAppWorkarounds(appId: string, nonSteam: boolean): PerAppWo appId, nextState, current.commandTokenAdded, + nonSteam, ); if (!result.success || !result.state) throw new Error(result.error || "Could not save workaround state"); applySnapshot({ -- cgit v1.2.3 From 4b7852b153106a487ad8fac654ea59f00aa8a8e4 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 11:40:53 -0400 Subject: handle multiple flatpak actives --- src/utils/nowPlaying.ts | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/utils/nowPlaying.ts b/src/utils/nowPlaying.ts index 2e0a876..380c9f5 100644 --- a/src/utils/nowPlaying.ts +++ b/src/utils/nowPlaying.ts @@ -20,11 +20,26 @@ function numericPid(value: string | undefined): number { return value && /^\d+$/.test(value) ? Number(value) : -1; } +function compareRunningProcesses(a: RunningFlatpakApp, b: RunningFlatpakApp): number { + if (a.active !== b.active) return a.active ? -1 : 1; + const startDifference = numericValue(b.start_time) - numericValue(a.start_time); + if (startDifference !== 0) return startDifference; + return numericPid(b.pid) - numericPid(a.pid); +} + export function selectMostRecentRunningFlatpak( apps: FlatpakApp[], runningApps: RunningFlatpakApp[], ): FlatpakApp | null { - const candidates = runningApps + const newestProcessByApp = new Map(); + for (const running of runningApps) { + const current = newestProcessByApp.get(running.app_id); + if (!current || compareRunningProcesses(running, current) < 0) { + newestProcessByApp.set(running.app_id, running); + } + } + + const candidates = Array.from(newestProcessByApp.values()) .map((running) => ({ running, app: apps.find((app) => app.app_id === running.app_id) || null, @@ -38,10 +53,8 @@ export function selectMostRecentRunningFlatpak( : []; eligibleCandidates.sort((a, b) => { - const startDifference = numericValue(b.running.start_time) - numericValue(a.running.start_time); - if (startDifference !== 0) return startDifference; - const pidDifference = numericPid(b.running.pid) - numericPid(a.running.pid); - if (pidDifference !== 0) return pidDifference; + const processDifference = compareRunningProcesses(a.running, b.running); + if (processDifference !== 0) return processDifference; return a.running.app_id.localeCompare(b.running.app_id); }); -- cgit v1.2.3 From 4d14bc1086a1ba05acd01d7466749ff3cffba75f Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 12:58:16 -0400 Subject: enable all and disable all for flatpak --- src/components/Content.tsx | 2 ++ src/components/FlatpakTab.tsx | 53 +++++++++++++++++++++++++++++++++++- src/hooks/useFlatpakConfiguration.ts | 23 ++++++++++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 91775df..3f25320 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -200,7 +200,9 @@ export function Content() { busyAppId={flatpak.busyAppId} onRefresh={flatpak.reload} onEnable={flatpak.enableApp} + onEnableAll={flatpak.enableAll} onRemove={flatpak.removeApp} + onRemoveAll={flatpak.removeAll} onConfigChange={flatpak.updateConfig} onWorkaroundChange={flatpak.updateWorkarounds} />, diff --git a/src/components/FlatpakTab.tsx b/src/components/FlatpakTab.tsx index 0b20da0..35721f6 100644 --- a/src/components/FlatpakTab.tsx +++ b/src/components/FlatpakTab.tsx @@ -1,4 +1,4 @@ -import { ButtonItem, DialogButton, Field, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses } from "@decky/ui"; +import { ButtonItem, ConfirmModal, DialogButton, Field, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses, showModal } from "@decky/ui"; import { useCallback, useMemo, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import type { FlatpakApp, LsfgConfig, WorkaroundState } from "../api/lsfgApi"; @@ -15,7 +15,9 @@ interface Props { busyAppId: string; onRefresh: () => Promise; onEnable: (appId: string) => Promise; + onEnableAll: () => Promise; onRemove: (appId: string) => Promise; + onRemoveAll: () => Promise; onConfigChange: (appId: string, config: LsfgConfig) => Promise; onWorkaroundChange: (appId: string, state: WorkaroundState) => Promise; } @@ -30,7 +32,9 @@ export function FlatpakTab({ busyAppId, onRefresh, onEnable, + onEnableAll, onRemove, + onRemoveAll, onConfigChange, onWorkaroundChange, }: Props) { @@ -51,6 +55,33 @@ export function FlatpakTab({ () => apps.filter((app) => !app.enabled).sort((a, b) => a.app_name.localeCompare(b.app_name)), [apps], ); + const enableableApps = useMemo( + () => availableApps.filter((app) => !(app.prepared && !app.owned) && !app.error), + [availableApps], + ); + const confirmEnableAll = () => { + showModal( + void onEnableAll()} + onCancel={() => {}} + />, + ); + }; + const confirmRemoveAll = () => { + showModal( + void onRemoveAll()} + onCancel={() => {}} + />, + ); + }; const itemFor = (app: FlatpakApp) => ({ id: app.app_id, label: app.app_name, @@ -79,6 +110,26 @@ export function FlatpakTab({ onToggle={toggleAvailable} onSelect={setSelectedAppId} /> + {enableableApps.length > 0 && ( + + + Enable all available Flatpaks + + + )} + + + Remove all profiles + + {apps.length === 0 && !loading && ( diff --git a/src/hooks/useFlatpakConfiguration.ts b/src/hooks/useFlatpakConfiguration.ts index 6ff7a79..f936271 100644 --- a/src/hooks/useFlatpakConfiguration.ts +++ b/src/hooks/useFlatpakConfiguration.ts @@ -95,6 +95,27 @@ export function useFlatpakConfiguration(enabled: boolean) { const removeApp = useCallback(async (appId: string) => ( await operate(appId, () => removeFlatpakApp(appId)) ).success, [operate]); + const enableAll = useCallback(async (): Promise => { + if (busyAppId) return; + const available = apps.filter((app) => ( + !app.enabled && !(app.prepared && !app.owned) && !app.error + )); + for (const app of available) { + const result = await operate(app.app_id, () => enableFlatpakApp(app.app_id), false); + if (!result.success) break; + } + await reload(); + await pollRunning(); + }, [apps, busyAppId, operate, pollRunning, reload]); + const removeAll = useCallback(async (): Promise => { + if (busyAppId) return; + for (const app of apps.filter((item) => item.enabled)) { + const result = await operate(app.app_id, () => removeFlatpakApp(app.app_id), false); + if (!result.success) break; + } + await reload(); + await pollRunning(); + }, [apps, busyAppId, operate, pollRunning, reload]); const updateConfig = useCallback( async (appId: string, config: LsfgConfig) => { const result = await operate(appId, () => updateFlatpakConfig(appId, config), false); @@ -130,7 +151,9 @@ export function useFlatpakConfiguration(enabled: boolean) { busyAppId, reload, enableApp, + enableAll, removeApp, + removeAll, updateConfig, updateWorkarounds, }; -- cgit v1.2.3 From f3074fbe1427411dc3b5597d2e87918383299e3f Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 13:47:52 -0400 Subject: feat: non steam tab, faster bulk actions --- src/api/lsfgApi.ts | 1 + src/components/ConfigFileTab.tsx | 4 +- src/components/ConfigurationTab.tsx | 56 +++++++---- src/components/Content.tsx | 98 +++++++++++++------ src/components/FlatpakNowPlayingTab.tsx | 4 +- src/components/GameConfigurationSelector.tsx | 47 +++++---- src/components/NowPlayingTab.tsx | 5 +- src/components/SettingsTab.tsx | 100 +++++++++++++++++++ src/components/SetupTab.tsx | 100 ------------------- src/components/index.ts | 2 +- src/hooks/useGameConfiguration.ts | 139 ++++++++++++++++++--------- src/utils/gameTargets.ts | 75 +++++++++++++++ src/utils/nowPlaying.ts | 18 +++- 13 files changed, 429 insertions(+), 220 deletions(-) create mode 100644 src/components/SettingsTab.tsx delete mode 100644 src/components/SetupTab.tsx create mode 100644 src/utils/gameTargets.ts (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index e050f62..883f56e 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -164,6 +164,7 @@ export const getGameConfigs = callable<[], GameConfigsResult>("get_game_configs" export const getInstalledGames = callable<[], InstalledGamesResult>("get_installed_games"); export const updateGameConfig = callable<[string, string, LsfgConfig], GameConfigResult>("update_game_config"); export const resetGameConfig = callable<[string], GameConfigResult>("reset_game_config"); +export const resetGameConfigs = callable<[string[]], GameConfigsResult>("reset_game_configs"); export const resetAllGameConfigs = callable<[], GameConfigsResult>("reset_all_game_configs"); export const updateGlobalConfig = callable<[GlobalConfig], GlobalConfigResult>("update_global_config"); export const getWorkaroundState = callable<[string], WorkaroundStateResult>("get_workaround_state"); diff --git a/src/components/ConfigFileTab.tsx b/src/components/ConfigFileTab.tsx index 07408d7..fd6d716 100644 --- a/src/components/ConfigFileTab.tsx +++ b/src/components/ConfigFileTab.tsx @@ -80,7 +80,7 @@ export function ConfigFileTab() { if (!result) { return ( - + @@ -108,7 +108,7 @@ export function ConfigFileTab() { } `} - + {result.error && ( diff --git a/src/components/ConfigurationTab.tsx b/src/components/ConfigurationTab.tsx index 37a7867..37555e0 100644 --- a/src/components/ConfigurationTab.tsx +++ b/src/components/ConfigurationTab.tsx @@ -1,26 +1,36 @@ -import { ButtonItem, ConfirmModal, DialogButton, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses, showModal } from "@decky/ui"; +import { ButtonItem, ConfirmModal, DialogButton, Field, Focusable, PanelSection, PanelSectionRow, gamepadDialogClasses, showModal } from "@decky/ui"; import { useCallback, useEffect, useRef, useState } from "react"; import { FaArrowLeft } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; -import { GameTarget } from "../hooks/useGameConfiguration"; +import type { GameTarget, KnownGameSource } from "../utils/gameTargets"; +import { sourceLabel } from "../utils/gameTargets"; import { GameConfigurationControls } from "./GameConfigurationControls"; import { GameConfigurationSelector } from "./GameConfigurationSelector"; import { ProfileDetails } from "./ProfileDetails"; interface ConfigurationTabProps { + title: string; + source: KnownGameSource; config: ConfigurationData; targets: GameTarget[]; runningGame: GameTarget | null; onSelect: (appid: string) => void; - onConfigChange: (fieldName: keyof ConfigurationData, value: boolean | number | string | string[]) => Promise; + onConfigChange: ( + fieldName: keyof ConfigurationData, + value: boolean | number | string | string[], + cleanupLaunchOptions?: boolean, + ) => Promise; onEnable: (appid: string) => Promise; - onEnableAll: () => Promise; + onEnableAll: (source: KnownGameSource) => Promise; + bulkOperationBusy: boolean; onRepair: (appid: string) => Promise; onReset: () => Promise; - onResetAll: () => Promise; + onResetAll: (source: KnownGameSource) => Promise; } export function ConfigurationTab({ + title, + source, config, targets, runningGame, @@ -28,6 +38,7 @@ export function ConfigurationTab({ onConfigChange, onEnable, onEnableAll, + bulkOperationBusy, onRepair, onReset, onResetAll, @@ -64,10 +75,12 @@ export function ConfigurationTab({ if (detailAppId === null) { return ( <> - + { setFocusConfiguredToggle(false); setFocusDetailAction(targets.find((target) => target.appid === appid)?.configured ? "fps" : "enable"); @@ -85,9 +98,9 @@ export function ConfigurationTab({ } const profileLabel = selectedTarget?.name || "Game profile"; - const profileTransport = selectedTarget?.nonSteam ? "Non-Steam" : "Steam"; + const profileTransport = selectedTarget ? sourceLabel(selectedTarget.source) : sourceLabel(source); const profileDescription = selectedTarget - ? `${profileTransport} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}` + ? `${profileTransport} · App ID ${selectedTarget.appid} · ${selectedTarget.configured ? "LSFG-VK Enabled" : "LSFG-VK not enabled"}${selectedTarget.source === "unknown" ? " · Bulk actions exclude this profile" : ""}` : "Game is no longer available"; const enableProfile = async (appid: string, quitRunningGame = false) => { if (!(await onEnable(appid))) return; @@ -101,8 +114,8 @@ export function ConfigurationTab({ closeDetails(); } else if (detailAppId) { const isRunningUnconfigured = runningGame?.appid === detailAppId - && runningGame.nonSteam === false - && selectedTarget?.nonSteam === false + && runningGame.source === "steam" + && selectedTarget?.source === "steam" && !runningGame.configured; if (isRunningUnconfigured) { showModal( @@ -128,7 +141,7 @@ export function ConfigurationTab({
{!selectedTarget?.configured && selectedTarget && ( - - Enable for next launch - + {selectedTarget.source === "unknown" ? ( + + ) : ( + + Enable for next launch + + )} )} {selectedTarget?.configured && ( onConfigChange(field, value, selectedTarget?.source !== "unknown")} autoFocusFpsMultiplier={focusFpsMultiplier} onFpsMultiplierFocused={clearFpsFocusRequest} - showWorkarounds - workaroundTarget={selectedTarget || undefined} - onRepairWorkaround={selectedTarget ? () => onRepair(selectedTarget.appid) : undefined} + showWorkarounds={selectedTarget.source !== "unknown"} + workaroundTarget={selectedTarget.source !== "unknown" ? selectedTarget : undefined} + onRepairWorkaround={selectedTarget.source !== "unknown" ? () => onRepair(selectedTarget.appid) : undefined} /> )} {selectedTarget?.configured && ( diff --git a/src/components/Content.tsx b/src/components/Content.tsx index 3f25320..470db95 100644 --- a/src/components/Content.tsx +++ b/src/components/Content.tsx @@ -1,28 +1,37 @@ import { Tabs } from "@decky/ui"; import { useEffect, useRef, useState, type FocusEvent, type ReactNode } from "react"; -import { FaCube, FaFileAlt, FaGamepad, FaList, FaTools } from "react-icons/fa"; +import { FaCube, FaExternalLinkAlt, FaFileAlt, FaGamepad, FaSteam, FaTools } from "react-icons/fa"; import { ConfigurationData } from "../config/configSchema"; import { useFlatpakConfiguration } from "../hooks/useFlatpakConfiguration"; import { useGameConfiguration } from "../hooks/useGameConfiguration"; import { useInstallation } from "../hooks/useLsfgHooks"; import { tabStyles } from "../styles"; -import { resolveNowPlayingTarget } from "../utils/nowPlaying"; +import { targetsForSource } from "../utils/gameTargets"; +import { resolveNowPlayingTarget, type NowPlayingTarget } from "../utils/nowPlaying"; import { ConfigFileTab } from "./ConfigFileTab"; import { ConfigurationTab } from "./ConfigurationTab"; import { FlatpakNowPlayingTab } from "./FlatpakNowPlayingTab"; import { FlatpakTab } from "./FlatpakTab"; import { NowPlayingTab } from "./NowPlayingTab"; -import { SetupTab } from "./SetupTab"; +import { SettingsTab } from "./SettingsTab"; const tabIcons = { nowPlaying: , - games: , + steam: , + nonSteam: , flatpak: , configFile: , - setup: , + settings: , }; const DEBUG_TAB_VISIBILITY_KEY = "lsfg-debug-tab-visible-v1"; +type GameTabId = "Steam" | "NonSteam" | "Flatpak"; + +function tabForNowPlaying(target: NowPlayingTarget | null): GameTabId { + if (!target) return "Steam"; + if (target.kind === "flatpak") return target.launcher?.source === "nonSteam" ? "NonSteam" : "Flatpak"; + return target.game.source === "nonSteam" ? "NonSteam" : "Steam"; +} function usePersistentBoolean(key: string, defaultValue: boolean) { const [value, setValue] = useState(() => { @@ -56,6 +65,7 @@ export function Content() { updateGlobal, enable, enableAll, + bulkOperationBusy, repair, resetSelected, resetAll, @@ -80,34 +90,40 @@ export function Content() { steamBranchStatus.installed && !steamBranchStatus.needs_switch; const flatpak = useFlatpakConfiguration(setupComplete); - const [tab, setTab] = useState("Setup"); + const [tab, setTab] = useState("Settings"); const [showDebugTab, setShowDebugTab] = usePersistentBoolean(DEBUG_TAB_VISIBILITY_KEY, false); const [contentFocused, setContentFocused] = useState(false); const previousRunningWorkload = useRef(null); + const previousNowPlayingTab = useRef("Steam"); const runningFlatpak = flatpak.runningApp; const nowPlayingTarget = resolveNowPlayingTarget(runningGame, runningFlatpak); const hasNowPlaying = Boolean(nowPlayingTarget); const runningWorkload = nowPlayingTarget ? nowPlayingTarget.kind === "flatpak" ? `flatpak:${nowPlayingTarget.app.app_id}:${nowPlayingTarget.launcher?.appid ?? ""}` - : `steam:${nowPlayingTarget.game.appid}` + : `${nowPlayingTarget.game.source}:${nowPlayingTarget.game.appid}` : null; + const steamTargets = targetsForSource(targets, "steam"); + const nonSteamTargets = targetsForSource(targets, "nonSteam"); useEffect(() => { if (!setupComplete) { - setTab("Setup"); + setTab("Settings"); return; } - setTab((current) => current === "Setup" ? (hasNowPlaying ? "NowPlaying" : "Games") : current); + setTab((current) => current === "Settings" ? (hasNowPlaying ? "NowPlaying" : "Steam") : current); }, [hasNowPlaying, setupComplete]); useEffect(() => { if (!setupComplete) return; const previous = previousRunningWorkload.current; previousRunningWorkload.current = runningWorkload; - if (runningWorkload && runningWorkload !== previous) setTab("NowPlaying"); + if (runningWorkload && runningWorkload !== previous) { + previousNowPlayingTab.current = tabForNowPlaying(nowPlayingTarget); + setTab("NowPlaying"); + } else if (!runningWorkload && previous) { - setTab((current) => current === "NowPlaying" ? "Games" : current); + setTab((current) => current === "NowPlaying" ? previousNowPlayingTab.current : current); } }, [runningWorkload, setupComplete]); @@ -119,8 +135,8 @@ export function Content() { }, [isInstalled, reload, flatpak.reload]); useEffect(() => { - if (!showDebugTab && tab === "ConfigFile") setTab("Games"); - }, [showDebugTab, tab]); + if (!showDebugTab && tab === "ConfigFile") setTab(setupComplete ? "Steam" : "Settings"); + }, [setupComplete, showDebugTab, tab]); const handleConfigChange = async ( fieldName: keyof ConfigurationData, @@ -130,8 +146,8 @@ export function Content() { await save({ ...config, [fieldName]: value }, cleanupLaunchOptions); }; - const setup = ( - {content}
); - const nowPlaying = nowPlayingTarget?.kind === "steam" ? ( + const nowPlaying = nowPlayingTarget?.kind === "flatpak" ? ( + + ) : nowPlayingTarget ? ( - ) : nowPlayingTarget?.kind === "flatpak" ? ( - ) : null; const tabs = setupComplete ? [ ...(nowPlaying ? [{ id: "NowPlaying", title: tabIcons.nowPlaying, content: tabContent(nowPlaying) }] : []), { - id: "Games", - title: tabIcons.games, + id: "Steam", + title: tabIcons.steam, content: tabContent( handleConfigChange(field, value, true)} + onConfigChange={handleConfigChange} onEnable={enable} onEnableAll={enableAll} + bulkOperationBusy={bulkOperationBusy} onRepair={repair} onReset={resetSelected} onResetAll={resetAll} />, ), }, + { + id: "NonSteam", + title: tabIcons.nonSteam, + content: tabContent( + + ), + }, { id: "Flatpak", title: tabIcons.flatpak, @@ -209,12 +249,12 @@ export function Content() { ), }, ...(showDebugTab ? [{ id: "ConfigFile", title: tabIcons.configFile, content: tabContent() }] : []), - { id: "Setup", title: tabIcons.setup, content: tabContent(setup) }, + { id: "Settings", title: tabIcons.settings, content: tabContent(settings) }, ] - : [{ id: "Setup", title: tabIcons.setup, content: tabContent(setup) }]; + : [{ id: "Settings", title: tabIcons.settings, content: tabContent(settings) }]; const availableTabIds = new Set(tabs.map(({ id }) => id)); - const activeTab = availableTabIds.has(tab) ? tab : setupComplete ? "Games" : "Setup"; + const activeTab = availableTabIds.has(tab) ? tab : setupComplete ? "Steam" : "Settings"; const handleFocusCapture = (event: FocusEvent) => { const focusedElement = event.target as HTMLElement | null; setContentFocused(!focusedElement?.closest?.('[role="tab"]')); diff --git a/src/components/FlatpakNowPlayingTab.tsx b/src/components/FlatpakNowPlayingTab.tsx index 89f7f49..449e4b5 100644 --- a/src/components/FlatpakNowPlayingTab.tsx +++ b/src/components/FlatpakNowPlayingTab.tsx @@ -1,6 +1,6 @@ import { Focusable } from "@decky/ui"; import type { FlatpakApp, LsfgConfig } from "../api/lsfgApi"; -import type { GameTarget } from "../hooks/useGameConfiguration"; +import type { GameTarget } from "../utils/gameTargets"; import { ConfigurationSection } from "./ConfigurationSection"; import { FpsMultiplierControl } from "./FpsMultiplierControl"; import { NowPlayingSummary } from "./NowPlayingSummary"; @@ -25,7 +25,7 @@ export function FlatpakNowPlayingTab({ app, launcher, onConfigChange }: Props) { void; - onEnableAll: () => Promise; - onResetAll: () => Promise; + onEnableAll: (source: KnownGameSource) => Promise; + onResetAll: (source: KnownGameSource) => Promise; focusConfiguredToggle?: boolean; onConfiguredToggleFocused?: () => void; } @@ -17,12 +20,16 @@ const ENABLED_COLLAPSED_KEY = "lsfg-enabled-games-collapsed-v4"; const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed-v3"; function targetDescription(game: GameTarget): string { - return game.nonSteam ? "Non-Steam" : "Steam"; + return game.source === "unknown" + ? "Unknown source · excluded from bulk actions" + : sourceLabel(game.source); } export function GameConfigurationSelector({ targets, runningGame, + source, + bulkOperationBusy, onSelect, onEnableAll, onResetAll, @@ -36,13 +43,19 @@ export function GameConfigurationSelector({ }); const enabledGames = sortGames(targets.filter((game) => game.configured)); const availableGames = sortGames(targets.filter((game) => !game.configured)); + const enableableGames = availableGames.filter((game) => game.source === source); + const removableGames = enabledGames.filter((game) => game.source === source); + const sourceName = source === "nonSteam" ? "non-Steam shortcuts" : "Steam games"; + const emptyDescription = source === "nonSteam" + ? "Steam has not reported any eligible non-Steam shortcuts" + : "Steam has not reported any eligible installed games"; const toItem = (game: GameTarget) => ({ id: game.appid, label: game.name, description: targetDescription(game), }); - const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(ENABLED_COLLAPSED_KEY); - const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(AVAILABLE_COLLAPSED_KEY); + const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(`${ENABLED_COLLAPSED_KEY}-${source}`); + const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(`${AVAILABLE_COLLAPSED_KEY}-${source}`); const enabledToggleRef = useRef(null); useEffect(() => { @@ -57,10 +70,10 @@ export function GameConfigurationSelector({ const confirmResetAll = () => { showModal( void onResetAll()} + onOK={() => void onResetAll(source)} onCancel={() => {}} />, ); @@ -69,11 +82,11 @@ export function GameConfigurationSelector({ const confirmEnableAll = () => { showModal( void onEnableAll()} + onOK={() => void onEnableAll(source)} onCancel={() => {}} />, ); @@ -86,7 +99,7 @@ export function GameConfigurationSelector({ {targets.length === 0 && ( - + )} - {availableGames.length > 0 && ( + {enableableGames.length > 0 && ( - - Enable all available games + + {`Enable all ${sourceName}`} )} @@ -115,9 +128,9 @@ export function GameConfigurationSelector({ target.configured)} + disabled={bulkOperationBusy || removableGames.length === 0} > - Remove all profiles + {`Remove all ${sourceLabel(source)} profiles`}
diff --git a/src/components/NowPlayingTab.tsx b/src/components/NowPlayingTab.tsx index 4c22fb7..69e72d7 100644 --- a/src/components/NowPlayingTab.tsx +++ b/src/components/NowPlayingTab.tsx @@ -1,6 +1,7 @@ import { Focusable } from "@decky/ui"; import { ConfigurationData } from "../config/configSchema"; -import { GameTarget } from "../hooks/useGameConfiguration"; +import type { GameTarget } from "../utils/gameTargets"; +import { sourceLabel } from "../utils/gameTargets"; import { GameConfigurationControls } from "./GameConfigurationControls"; import { NowPlayingSummary } from "./NowPlayingSummary"; @@ -14,7 +15,7 @@ interface Props { } function targetDescription(game: GameTarget): string { - return game.nonSteam ? "Non-Steam" : "Steam"; + return sourceLabel(game.source); } export function NowPlayingTab({ diff --git a/src/components/SettingsTab.tsx b/src/components/SettingsTab.tsx new file mode 100644 index 0000000..35a74cc --- /dev/null +++ b/src/components/SettingsTab.tsx @@ -0,0 +1,100 @@ +import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; +import { type GlobalConfig, type SteamBranchStatus } from "../api/lsfgApi"; +import t from "../i18n/i18n"; + +interface SettingsTabProps { + isInstalled: boolean; + installationStatus: string; + losslessScalingInstalled: boolean; + losslessScalingStatus: string; + steamBranchStatus: SteamBranchStatus | null; + isInstalling: boolean; + isUninstalling: boolean; + globalConfig: GlobalConfig; + showDebugTab: boolean; + onGlobalConfigChange: (config: GlobalConfig) => Promise; + onShowDebugTabChange: (value: boolean) => void; + onInstall: () => void; + onUninstall: () => void; +} + +export function SettingsTab(props: SettingsTabProps) { + const { + isInstalled, + installationStatus, + losslessScalingInstalled, + losslessScalingStatus, + steamBranchStatus, + isInstalling, + isUninstalling, + globalConfig, + showDebugTab, + onGlobalConfigChange, + onShowDebugTabChange, + onInstall, + onUninstall, + } = props; + const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; + const buttonLabel = isInstalling + ? t("INSTALL_INSTALLING", "Installing...") + : isUninstalling + ? t("INSTALL_UNINSTALLING", "Uninstalling...") + : isInstalled + ? t("INSTALL_UNINSTALL_BTN", "Uninstall LSFG-VK") + : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); + + return ( + <> + + + + + + + + {steamBranchStatus?.installed && ( + + + + )} + + + {buttonLabel} + + + + {isInstalled && ( + <> + + + void onGlobalConfigChange({ ...globalConfig, no_fp16: !value })} + /> + + + + + + + + + )} + + ); +} diff --git a/src/components/SetupTab.tsx b/src/components/SetupTab.tsx deleted file mode 100644 index ff072cb..0000000 --- a/src/components/SetupTab.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import { ButtonItem, Field, PanelSection, PanelSectionRow, ToggleField } from "@decky/ui"; -import { type GlobalConfig, type SteamBranchStatus } from "../api/lsfgApi"; -import t from "../i18n/i18n"; - -interface SetupTabProps { - isInstalled: boolean; - installationStatus: string; - losslessScalingInstalled: boolean; - losslessScalingStatus: string; - steamBranchStatus: SteamBranchStatus | null; - isInstalling: boolean; - isUninstalling: boolean; - globalConfig: GlobalConfig; - showDebugTab: boolean; - onGlobalConfigChange: (config: GlobalConfig) => Promise; - onShowDebugTabChange: (value: boolean) => void; - onInstall: () => void; - onUninstall: () => void; -} - -export function SetupTab(props: SetupTabProps) { - const { - isInstalled, - installationStatus, - losslessScalingInstalled, - losslessScalingStatus, - steamBranchStatus, - isInstalling, - isUninstalling, - globalConfig, - showDebugTab, - onGlobalConfigChange, - onShowDebugTabChange, - onInstall, - onUninstall, - } = props; - const losslessScalingAppInstalled = losslessScalingInstalled || steamBranchStatus?.installed === true; - const buttonLabel = isInstalling - ? t("INSTALL_INSTALLING", "Installing...") - : isUninstalling - ? t("INSTALL_UNINSTALLING", "Uninstalling...") - : isInstalled - ? t("INSTALL_UNINSTALL_BTN", "Uninstall LSFG-VK") - : t("INSTALL_INSTALL_BTN", "Install LSFG-VK"); - - return ( - <> - - - - - - - - {steamBranchStatus?.installed && ( - - - - )} - - - {buttonLabel} - - - - {isInstalled && ( - <> - - - void onGlobalConfigChange({ ...globalConfig, no_fp16: !value })} - /> - - - - - - - - - )} - - ); -} diff --git a/src/components/index.ts b/src/components/index.ts index bca6f6f..5459974 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -3,7 +3,7 @@ export { ConfigurationSection } from "./ConfigurationSection"; export { FpsMultiplierControl } from "./FpsMultiplierControl"; export { ConfigurationTab } from "./ConfigurationTab"; export { ConfigFileTab } from "./ConfigFileTab"; -export { SetupTab } from "./SetupTab"; +export { SettingsTab } from "./SettingsTab"; export { GameConfigurationSelector } from "./GameConfigurationSelector"; export { GameConfigurationControls } from "./GameConfigurationControls"; export { NowPlayingTab } from "./NowPlayingTab"; diff --git a/src/hooks/useGameConfiguration.ts b/src/hooks/useGameConfiguration.ts index fd8dfb1..deb68ff 100644 --- a/src/hooks/useGameConfiguration.ts +++ b/src/hooks/useGameConfiguration.ts @@ -1,12 +1,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useQuickAccessVisible } from "@decky/api"; import { Router } from "@decky/ui"; -import { getGameConfigs, getInstalledGames, getWorkaroundApps, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetAllGameConfigs, setWorkaroundState, updateGameConfig, updateGlobalConfig as saveGlobalConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundState } from "../api/lsfgApi"; +import { getGameConfigs, getInstalledGames, getWorkaroundApps, getWorkaroundState, removeWorkaroundState, resetGameConfig, resetGameConfigs, setWorkaroundState, updateGameConfig, updateGlobalConfig as saveGlobalConfig, type GameConfigEntry, type GlobalConfig, type InstalledGame, type WorkaroundApp, type WorkaroundState } from "../api/lsfgApi"; import { ConfigurationData, getDefaults } from "../config/configSchema"; import { getDefaultWrapperPath, installWrapperIntegration, removeWrapperIntegration } from "../utils/steamLaunchOptions"; +import { getTargetSource, mergeGameTargets, type GameTarget, type KnownGameSource } from "../utils/gameTargets"; import { showErrorToast } from "../utils/toastUtils"; -export interface GameTarget extends InstalledGame { configured: boolean; } +export type { GameSource, GameTarget, KnownGameSource } from "../utils/gameTargets"; async function getSteamShortcuts(): Promise { const apps = (globalThis as any).SteamClient?.Apps; @@ -56,20 +57,29 @@ export function useGameConfiguration() { const [games, setGames] = useState([]); const [globalConfig, setGlobalConfig] = useState({ dll: "", no_fp16: false }); const [installedGames, setInstalledGames] = useState([]); + const [workaroundApps, setWorkaroundApps] = useState([]); const [configsLoaded, setConfigsLoaded] = useState(false); const [selectedAppId, setSelectedAppId] = useState(""); const [runningGame, setRunningGame] = useState(null); + const [bulkOperationBusy, setBulkOperationBusy] = useState(false); + const bulkOperationLock = useRef(false); const previousRunningAppId = useRef(null); const previousQuickAccessVisible = useRef(null); const quickAccessVisible = useQuickAccessVisible(); const load = useCallback(async () => { - const [result, installed, shortcuts] = await Promise.all([getGameConfigs(), getInstalledGames(), getSteamShortcuts()]); + const [result, installed, shortcuts, workaroundResult] = await Promise.all([ + getGameConfigs(), + getInstalledGames(), + getSteamShortcuts(), + getWorkaroundApps(), + ]); if (result.success) { setGlobalConfig(result.global_config || { dll: "", no_fp16: false }); setGames(result.games || []); } setInstalledGames(mergeInstalledGames(installed.success ? installed.games || [] : [], shortcuts)); + setWorkaroundApps(workaroundResult.success ? workaroundResult.apps || [] : []); setConfigsLoaded(true); }, []); @@ -89,15 +99,19 @@ export function useGameConfiguration() { const installed = installedGames.find((game) => game.appid === appid); const name = app.display_name || installed?.name; if (!name) return setRunningGame(null); + const source = getTargetSource(appid, installedGames, workaroundApps); const next: GameTarget = { - ...(installed || { appid, name, nonSteam: false }), + ...(installed || { appid, name, nonSteam: source === "nonSteam" }), name, + nonSteam: source === "nonSteam", + source, configured: games.some((game) => game.appid === appid), }; setRunningGame((current) => ( current?.appid === next.appid && current.name === next.name && current.nonSteam === next.nonSteam + && current.source === next.source && current.configured === next.configured ? current : next @@ -106,7 +120,7 @@ export function useGameConfiguration() { poll(); const interval = window.setInterval(poll, 2000); return () => window.clearInterval(interval); - }, [configsLoaded, games, installedGames]); + }, [configsLoaded, games, installedGames, workaroundApps]); useEffect(() => { const appid = runningGame?.appid || null; @@ -117,11 +131,8 @@ export function useGameConfiguration() { }, [runningGame?.appid]); const targets = useMemo(() => { - 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]); + return mergeGameTargets(games, installedGames, workaroundApps, runningGame); + }, [games, installedGames, runningGame, workaroundApps]); const template = useMemo(() => ({ ...getDefaults(), ...globalConfig }), [globalConfig]); const config = games.find((game) => game.appid === selectedAppId)?.config || template; const runningConfig = runningGame @@ -129,6 +140,10 @@ export function useGameConfiguration() { : template; const ensureTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { + if (target.source === "unknown") { + showErrorToast("Could not initialize workarounds", "The target source is unknown; re-discover the game before enabling it"); + return false; + } if (!installedGames.some((game) => game.appid === target.appid)) return true; const appId = Number(target.appid); let integration: Awaited> | null = null; @@ -185,18 +200,21 @@ export function useGameConfiguration() { }, [installedGames]); const removeTargetWorkarounds = useCallback(async (target: GameTarget): Promise => { - if (!installedGames.some((game) => game.appid === target.appid)) return true; + const installed = installedGames.some((game) => game.appid === target.appid); + if (target.source === "unknown" && installed) return true; const appId = Number(target.appid); try { const existing = await getWorkaroundState(target.appid); if (!existing.success) throw new Error(existing.error || "Could not read workaround state"); const wrapperPath = existing.wrapper_path || getDefaultWrapperPath(); - await removeWrapperIntegration( - appId, - target.nonSteam, - wrapperPath, - existing.command_token_added === true, - ); + if (installed) { + await removeWrapperIntegration( + appId, + target.nonSteam, + wrapperPath, + existing.command_token_added === true, + ); + } const removed = await removeWorkaroundState(target.appid); if (!removed.success) throw new Error(removed.error || "Could not remove workaround state"); return true; @@ -206,20 +224,29 @@ export function useGameConfiguration() { } }, [installedGames]); + const acquireBulkOperation = useCallback(() => { + if (bulkOperationLock.current) return false; + bulkOperationLock.current = true; + setBulkOperationBusy(true); + return true; + }, []); + + const releaseBulkOperation = useCallback(() => { + bulkOperationLock.current = false; + setBulkOperationBusy(false); + }, []); + const cleanupAllWorkarounds = useCallback(async (): Promise => { try { const result = await getWorkaroundApps(); if (!result.success) throw new Error(result.error || "Could not read workaround state"); - const targetsByAppId = new Map(targets.map((target) => [target.appid, target])); const cleaned = new Set(); const wrapperPath = result.wrapper_path || getDefaultWrapperPath(); for (const entry of result.apps || []) { - const target = targetsByAppId.get(entry.appid); - const nonSteam = target?.nonSteam ?? entry.non_steam; await removeWrapperIntegration( Number(entry.appid), - nonSteam, + entry.non_steam, wrapperPath, entry.command_token_added, ); @@ -274,23 +301,32 @@ export function useGameConfiguration() { return result.success; }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); - const enableAll = useCallback(async (): Promise => { - const available = targets.filter((target) => !target.configured && target.name); - if (available.length === 0) return; - for (const target of available) { - if (!(await ensureTargetWorkarounds(target))) return; - const result = await updateGameConfig(target.appid, target.name, template); - if (!result.success) { - await removeTargetWorkarounds(target); - showErrorToast( - "Could not enable all games", - result.error || `Could not create a profile for ${target.name}`, - ); - return; + const enableAll = useCallback(async (source: KnownGameSource): Promise => { + if (!acquireBulkOperation()) return; + try { + const available = targets.filter((target) => target.source === source && !target.configured && target.name); + if (available.length === 0) return; + for (const target of available) { + if (!(await ensureTargetWorkarounds(target))) { + await load(); + return; + } + const result = await updateGameConfig(target.appid, target.name, template); + if (!result.success) { + await removeTargetWorkarounds(target); + showErrorToast( + "Could not enable all games", + result.error || `Could not create a profile for ${target.name}`, + ); + await load(); + return; + } } + await load(); + } finally { + releaseBulkOperation(); } - await load(); - }, [ensureTargetWorkarounds, load, removeTargetWorkarounds, targets, template]); + }, [acquireBulkOperation, ensureTargetWorkarounds, load, removeTargetWorkarounds, releaseBulkOperation, targets, template]); const repair = useCallback(async (appid: string): Promise => { const target = targets.find((item) => item.appid === appid); @@ -313,17 +349,30 @@ export function useGameConfiguration() { } }, [load, removeTargetWorkarounds, selectedAppId, targets]); - const resetAll = useCallback(async () => { - for (const target of targets.filter((item) => item.configured)) { - if (!(await removeTargetWorkarounds(target))) return; - } - const result = await resetAllGameConfigs(); - if (result.success) { - setRunningGame((current) => current ? { ...current, configured: false } : current); + const resetAll = useCallback(async (source: KnownGameSource) => { + if (!acquireBulkOperation()) return; + try { + const selectedTargets = targets.filter((item) => item.configured && item.source === source); + if (selectedTargets.length === 0) return; + for (const target of selectedTargets) { + if (!(await removeTargetWorkarounds(target))) { + await load(); + return; + } + } + const result = await resetGameConfigs(selectedTargets.map((target) => target.appid)); + if (!result.success) { + showErrorToast("Could not remove all profiles", result.error || "Could not remove the selected profiles"); + await load(); + return; + } + setRunningGame((current) => current?.source === source ? { ...current, configured: false } : current); setSelectedAppId(""); await load(); + } finally { + releaseBulkOperation(); } - }, [load, removeTargetWorkarounds, targets]); + }, [acquireBulkOperation, load, removeTargetWorkarounds, releaseBulkOperation, targets]); - return { config, runningConfig, globalConfig, targets, runningGame, selectedAppId, setSelectedAppId, save, saveFor, updateGlobal, enable, enableAll, repair, resetSelected, resetAll, cleanupAllWorkarounds, reload: load }; + return { config, runningConfig, globalConfig, targets, runningGame, selectedAppId, setSelectedAppId, save, saveFor, updateGlobal, enable, enableAll, repair, resetSelected, resetAll, bulkOperationBusy, cleanupAllWorkarounds, reload: load }; } diff --git a/src/utils/gameTargets.ts b/src/utils/gameTargets.ts new file mode 100644 index 0000000..8922e98 --- /dev/null +++ b/src/utils/gameTargets.ts @@ -0,0 +1,75 @@ +import type { GameConfigEntry, InstalledGame, WorkaroundApp } from "../api/lsfgApi"; + +export type GameSource = "steam" | "nonSteam" | "unknown"; +export type KnownGameSource = Exclude; + +export interface GameTarget extends InstalledGame { + configured: boolean; + source: GameSource; +} + +export function sourceFromNonSteam(nonSteam: boolean): KnownGameSource { + return nonSteam ? "nonSteam" : "steam"; +} + +export function getTargetSource( + appid: string, + installedGames: InstalledGame[], + workaroundApps: WorkaroundApp[], +): GameSource { + const workaround = workaroundApps.find((item) => item.appid === appid); + if (workaround) return sourceFromNonSteam(workaround.non_steam); + + const installed = installedGames.find((game) => game.appid === appid); + return installed ? sourceFromNonSteam(installed.nonSteam) : "unknown"; +} + +export function mergeGameTargets( + configs: GameConfigEntry[], + installedGames: InstalledGame[], + workaroundApps: WorkaroundApp[], + runningGame: GameTarget | null = null, +): GameTarget[] { + const configuredIds = new Set(configs.map((game) => game.appid)); + const targets = installedGames.map((game) => { + const source = getTargetSource(game.appid, installedGames, workaroundApps); + return { + ...game, + nonSteam: source === "nonSteam", + source, + configured: configuredIds.has(game.appid), + }; + }); + + for (const game of configs) { + if (targets.some((target) => target.appid === game.appid)) continue; + const source = getTargetSource(game.appid, installedGames, workaroundApps); + targets.push({ + appid: game.appid, + name: game.profile || `App ${game.appid}`, + nonSteam: source === "nonSteam", + source, + configured: true, + }); + } + + if ( + runningGame + && !targets.some((target) => target.appid === runningGame.appid) + && (runningGame.configured || runningGame.source !== "unknown") + ) { + targets.unshift(runningGame); + } + + return targets; +} + +export function targetsForSource(targets: GameTarget[], source: KnownGameSource): GameTarget[] { + return targets.filter((target) => target.source === source || (target.source === "unknown" && target.configured)); +} + +export function sourceLabel(source: GameSource): string { + if (source === "nonSteam") return "Non-Steam"; + if (source === "steam") return "Steam"; + return "Unknown source"; +} diff --git a/src/utils/nowPlaying.ts b/src/utils/nowPlaying.ts index 380c9f5..a307f5c 100644 --- a/src/utils/nowPlaying.ts +++ b/src/utils/nowPlaying.ts @@ -1,5 +1,5 @@ import type { FlatpakApp, RunningFlatpakApp } from "../api/lsfgApi"; -import type { GameTarget } from "../hooks/useGameConfiguration"; +import type { GameTarget } from "./gameTargets"; export type NowPlayingTarget = | { @@ -10,6 +10,10 @@ export type NowPlayingTarget = | { kind: "steam"; game: GameTarget; + } + | { + kind: "nonSteam"; + game: GameTarget; }; function numericValue(value: number | null | undefined): number { @@ -65,12 +69,18 @@ export function resolveNowPlayingTarget( runningGame: GameTarget | null, runningFlatpak: FlatpakApp | null, ): NowPlayingTarget | null { - if (runningGame && !runningGame.nonSteam) { + if (runningGame?.source === "steam") { return runningGame.configured ? { kind: "steam", game: runningGame } : null; } if (runningFlatpak) { - return { kind: "flatpak", app: runningFlatpak, launcher: runningGame?.nonSteam ? runningGame : null }; + return { + kind: "flatpak", + app: runningFlatpak, + launcher: runningGame?.source === "nonSteam" ? runningGame : null, + }; + } + if (runningGame?.source === "nonSteam" && runningGame.configured) { + return { kind: "nonSteam", game: runningGame }; } - if (runningGame?.configured) return { kind: "steam", game: runningGame }; return null; } -- cgit v1.2.3 From f185d26f4d37894183cdfa8c3e6ffc718cb3b103 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 14:16:06 -0400 Subject: labeled slider for multiplier --- src/components/FpsMultiplierControl.tsx | 81 ++++++++++----------------------- 1 file changed, 25 insertions(+), 56 deletions(-) (limited to 'src') diff --git a/src/components/FpsMultiplierControl.tsx b/src/components/FpsMultiplierControl.tsx index 2c50be1..523e8b3 100644 --- a/src/components/FpsMultiplierControl.tsx +++ b/src/components/FpsMultiplierControl.tsx @@ -1,4 +1,4 @@ -import { DialogButton, Focusable, PanelSectionRow } from "@decky/ui"; +import { Focusable, PanelSectionRow, SliderField } from "@decky/ui"; import { useEffect, useRef } from "react"; import { ConfigurationData } from "../config/configSchema"; import { MULTIPLIER } from "../config/generatedConfigSchema"; @@ -31,63 +31,32 @@ export function FpsMultiplierControl({ return () => cancelAnimationFrame(frame); }, [autoFocus, onAutoFocus]); + const multiplierLabel = config.multiplier === 1 + ? t("MULTIPLIER_OFF", "Off") + : `${config.multiplier}x`; + return ( - - void onConfigChange(MULTIPLIER, Math.max(1, config.multiplier - 1))} - disabled={config.multiplier <= 1} - > - − - -
4 ? "red" : "white", - minWidth: "60px", - textAlign: "center", - }} - > - {config.multiplier < 2 ? t("MULTIPLIER_OFF", "OFF") : `${config.multiplier}X`} -
- void onConfigChange(MULTIPLIER, Math.min(4, config.multiplier + 1))} - disabled={config.multiplier >= 4} - > - + - + + void onConfigChange(MULTIPLIER, value)} + />
); -- cgit v1.2.3 From 81feb03288166755545401b9df2ff2c9bc3ae7d7 Mon Sep 17 00:00:00 2001 From: xXJSONDeruloXx Date: Fri, 11 Sep 2026 16:48:35 -0400 Subject: handle flatpak grey, id proton and exclusions --- src/api/lsfgApi.ts | 1 + src/components/CollapsibleItemGroup.tsx | 4 ++- src/components/GameConfigurationSelector.tsx | 6 ++-- src/utils/steamLaunchOptions.ts | 41 +++++++++++++++++++++++----- 4 files changed, 42 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/api/lsfgApi.ts b/src/api/lsfgApi.ts index 883f56e..44b72b5 100644 --- a/src/api/lsfgApi.ts +++ b/src/api/lsfgApi.ts @@ -41,6 +41,7 @@ export interface InstalledGame { appid: string; name: string; nonSteam: boolean; + isFlatpakShortcut?: boolean; } export interface GlobalConfig { diff --git a/src/components/CollapsibleItemGroup.tsx b/src/components/CollapsibleItemGroup.tsx index 29fe945..a4e4092 100644 --- a/src/components/CollapsibleItemGroup.tsx +++ b/src/components/CollapsibleItemGroup.tsx @@ -6,6 +6,7 @@ export interface CollapsibleItem { id: string; label: string; description: string; + disabled?: boolean; } export const collapsibleItemGroupStyles = ` @@ -91,7 +92,8 @@ export function CollapsibleItemGroup({ onSelect(item.id)} + disabled={item.disabled} + onActivate={item.disabled ? undefined : () => onSelect(item.id)} highlightOnFocus />
diff --git a/src/components/GameConfigurationSelector.tsx b/src/components/GameConfigurationSelector.tsx index ad3537d..91dc3df 100644 --- a/src/components/GameConfigurationSelector.tsx +++ b/src/components/GameConfigurationSelector.tsx @@ -20,6 +20,7 @@ const ENABLED_COLLAPSED_KEY = "lsfg-enabled-games-collapsed-v4"; const AVAILABLE_COLLAPSED_KEY = "lsfg-available-games-collapsed-v3"; function targetDescription(game: GameTarget): string { + if (game.isFlatpakShortcut) return "Non-Steam | Use Flatpak Tab"; return game.source === "unknown" ? "Unknown source · excluded from bulk actions" : sourceLabel(game.source); @@ -43,8 +44,8 @@ export function GameConfigurationSelector({ }); const enabledGames = sortGames(targets.filter((game) => game.configured)); const availableGames = sortGames(targets.filter((game) => !game.configured)); - const enableableGames = availableGames.filter((game) => game.source === source); - const removableGames = enabledGames.filter((game) => game.source === source); + const enableableGames = availableGames.filter((game) => game.source === source && !game.isFlatpakShortcut); + const removableGames = enabledGames.filter((game) => game.source === source && !game.isFlatpakShortcut); const sourceName = source === "nonSteam" ? "non-Steam shortcuts" : "Steam games"; const emptyDescription = source === "nonSteam" ? "Steam has not reported any eligible non-Steam shortcuts" @@ -53,6 +54,7 @@ export function GameConfigurationSelector({ id: game.appid, label: game.name, description: targetDescription(game), + disabled: game.isFlatpakShortcut, }); const [enabledCollapsed, toggleEnabled] = usePersistentCollapsed(`${ENABLED_COLLAPSED_KEY}-${source}`); const [availableCollapsed, toggleAvailable] = usePersistentCollapsed(`${AVAILABLE_COLLAPSED_KEY}-${source}`); diff --git a/src/utils/steamLaunchOptions.ts b/src/utils/steamLaunchOptions.ts index f03eeab..83c46f2 100644 --- a/src/utils/steamLaunchOptions.ts +++ b/src/utils/steamLaunchOptions.ts @@ -153,7 +153,25 @@ function tokenize(options: string): LaunchToken[] { } const serialize = (tokens: readonly LaunchToken[]) => tokens.map(({ raw }) => raw).join(" "); -const commandIndex = (tokens: readonly LaunchToken[]) => tokens.findIndex((token) => token.raw.toLowerCase() === COMMAND_TOKEN); +function isCommandToken(token: LaunchToken): boolean { + return token.value.toLowerCase() === COMMAND_TOKEN; +} + +function isMalformedCommandToken(token: LaunchToken): boolean { + const value = token.value.toLowerCase(); + return value === "%command" || value === "command%"; +} + +function normalizeCommandTokens(tokens: LaunchToken[]): void { + for (const token of tokens) { + if (isCommandToken(token) || isMalformedCommandToken(token)) { + token.raw = COMMAND_TOKEN; + token.value = COMMAND_TOKEN; + } + } +} + +const commandIndex = (tokens: readonly LaunchToken[]) => tokens.findIndex(isCommandToken); const isAssignment = (token: LaunchToken) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(token.value); const isLegacyToken = (value: string) => LEGACY_WRAPPER_TOKENS.has(value) || LEGACY_ABSOLUTE_WRAPPER.test(value); const isWrapperToken = (value: string, wrapperPath: string) => decodeToken(value) === wrapperPath || isLegacyWrapperToken(value); @@ -173,9 +191,9 @@ function removeMatchingWrappers(tokens: LaunchToken[], predicate: (value: string function installLaunchOption( options: string, wrapperPath = DEFAULT_WRAPPER_PATH, - shortcutLaunchOptions = false, ) { const tokens = tokenize(options); + normalizeCommandTokens(tokens); removeMatchingWrappers(tokens, isLegacyToken); let command = commandIndex(tokens); if (command >= 0) { @@ -185,11 +203,15 @@ function installLaunchOption( tokens.splice(command, 0, { raw: wrapperPath, value: wrapperPath }); return { options: serialize(tokens), commandTokenAdded: false }; } + + const existingWrapper = tokens.findIndex((token) => decodeToken(token.value) === wrapperPath); + if (existingWrapper >= 0) { + tokens.splice(existingWrapper + 1, 0, { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }); + return { options: serialize(tokens), commandTokenAdded: true }; + } + let insertion = 0; while (insertion < tokens.length && isAssignment(tokens[insertion])) insertion++; - if (!shortcutLaunchOptions && insertion < tokens.length && !tokens[insertion].value.startsWith("-")) { - throw new Error("Launch options do not contain %command%; refusing to guess a launcher command"); - } tokens.splice(insertion, 0, { raw: wrapperPath, value: wrapperPath }, { raw: COMMAND_TOKEN, value: COMMAND_TOKEN }, @@ -207,6 +229,7 @@ export function removeWrapperLaunchOption( commandTokenAdded = false, ): string { const tokens = tokenize(options); + normalizeCommandTokens(tokens); if (removeMatchingWrappers(tokens, (value) => isWrapperToken(value, wrapperPath)) && commandTokenAdded) { const command = commandIndex(tokens); if (command >= 0) tokens.splice(command, 1); @@ -345,14 +368,18 @@ export function installWrapperIntegration( const current = await readSteamLaunchOptions(appId, nonSteam); const cleaned = cleanupPluginAssignments(cleanupLegacyLaunchOptions(current.options)); const alreadyInstalled = hasWrapperLaunchIntegration(current.options, wrapperPath); - const rewrite = installLaunchOption(cleaned, wrapperPath, nonSteam); + const rewrite = installLaunchOption(cleaned, wrapperPath); if (rewrite.options === current.options) return { snapshot: current, commandTokenAdded, changed: false }; const value = await writeVerified( appId, nonSteam, current.options, rewrite.options, (options) => writeOptions(appId, nonSteam, options), "Steam did not accept the launch options", ); - return { snapshot: value, commandTokenAdded: alreadyInstalled ? commandTokenAdded : rewrite.commandTokenAdded, changed: true }; + return { + snapshot: value, + commandTokenAdded: alreadyInstalled ? commandTokenAdded : commandTokenAdded || rewrite.commandTokenAdded, + changed: true, + }; }); } -- cgit v1.2.3