summaryrefslogtreecommitdiff
path: root/src/components/InstalledGamesSection.tsx
blob: eb750c8df92a256de0e27ef52d22fa5f52fbb555 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { useEffect, useState } from "react";
import {
  ButtonItem,
  ConfirmModal,
  DropdownItem,
  PanelSection,
  PanelSectionRow,
  showModal,
} from "@decky/ui";
import { cleanupManagedGame, listInstalledGames, logError } from "../api";
import { safeAsyncOperation } from "../utils";
import { GameInfo } from "../types/index";
import { STYLES } from "../utils/constants";

const DEFAULT_LAUNCH_COMMAND = 'OPTISCALER_PROXY=winmm ~/fgmod/fgmod %COMMAND%';

interface InstalledGamesSectionProps {
  isAvailable: boolean;
}

export function InstalledGamesSection({ isAvailable }: InstalledGamesSectionProps) {
  const [games, setGames] = useState<GameInfo[]>([]);
  const [selectedGame, setSelectedGame] = useState<GameInfo | null>(null);
  const [result, setResult] = useState<string>("");
  const [loadingGames, setLoadingGames] = useState(false);
  const [enabling, setEnabling] = useState(false);
  const [disabling, setDisabling] = useState(false);

  useEffect(() => {
    if (!isAvailable) return;

    let cancelled = false;

    const fetchGames = async () => {
      setLoadingGames(true);
      const response = await safeAsyncOperation(async () => await listInstalledGames(), "InstalledGamesSection.fetchGames");

      if (cancelled || !response) {
        setLoadingGames(false);
        return;
      }

      if (response.status === "success") {
        const sortedGames = [...response.games]
          .map((game) => ({
            ...game,
            appid: parseInt(String(game.appid), 10),
          }))
          .sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
        setGames(sortedGames);
      } else {
        logError(`InstalledGamesSection.fetchGames: ${JSON.stringify(response)}`);
      }

      setLoadingGames(false);
    };

    fetchGames();

    return () => {
      cancelled = true;
    };
  }, [isAvailable]);

  const handleEnable = async () => {
    if (!selectedGame) return;

    showModal(
      <ConfirmModal
        strTitle={`Enable prefix-managed OptiScaler for ${selectedGame.name}?`}
        strDescription={
          "This only changes the Steam launch option for the selected game. OptiScaler itself is staged into compatdata/pfx/system32 at launch time and does not write into the game install directory."
        }
        strOKButtonText="Enable"
        strCancelButtonText="Cancel"
        onOK={async () => {
          setEnabling(true);
          try {
            await SteamClient.Apps.SetAppLaunchOptions(selectedGame.appid, DEFAULT_LAUNCH_COMMAND);
            setResult(`✓ Enabled prefix-managed OptiScaler for ${selectedGame.name}. Launch the game, enable DLSS if needed, then press Insert for the OptiScaler menu.`);
          } catch (error) {
            logError(`InstalledGamesSection.handleEnable: ${String(error)}`);
            setResult(error instanceof Error ? `Error: ${error.message}` : "Error enabling prefix-managed OptiScaler");
          } finally {
            setEnabling(false);
          }
        }}
      />
    );
  };

  const handleDisable = async () => {
    if (!selectedGame) return;

    setDisabling(true);
    try {
      const cleanupResult = await cleanupManagedGame(String(selectedGame.appid));
      if (cleanupResult?.status !== "success") {
        setResult(`Error: ${cleanupResult?.message || cleanupResult?.output || "Failed to clean managed compatdata prefix"}`);
        return;
      }

      await SteamClient.Apps.SetAppLaunchOptions(selectedGame.appid, "");
      setResult(`✓ Cleared launch options and cleaned the managed compatdata prefix for ${selectedGame.name}.`);
    } catch (error) {
      logError(`InstalledGamesSection.handleDisable: ${String(error)}`);
      setResult(error instanceof Error ? `Error: ${error.message}` : "Error disabling prefix-managed OptiScaler");
    } finally {
      setDisabling(false);
    }
  };

  if (!isAvailable) return null;

  return (
    <PanelSection title="Steam game integration">
      <PanelSectionRow>
        <DropdownItem
          rgOptions={games.map((game) => ({
            data: game.appid,
            label: game.name,
          }))}
          selectedOption={selectedGame?.appid}
          onChange={(option) => {
            const game = games.find((entry) => entry.appid === option.data);
            setSelectedGame(game || null);
            setResult("");
          }}
          strDefaultLabel={loadingGames ? "Loading installed games..." : "Choose a game"}
          menuLabel="Installed Steam games"
          disabled={loadingGames || games.length === 0}
        />
      </PanelSectionRow>

      <PanelSectionRow>
        <div style={STYLES.instructionCard}>
          Enable writes the launch option automatically. Disable clears launch options and removes staged files from the selected game's compatdata prefix.
        </div>
      </PanelSectionRow>

      {result ? (
        <PanelSectionRow>
          <div
            style={{
              ...STYLES.preWrap,
              ...(result.startsWith("Error") ? STYLES.statusNotInstalled : STYLES.statusInstalled),
            }}
          >
            {result.startsWith("Error") ? "❌" : "✅"} {result}
          </div>
        </PanelSectionRow>
      ) : null}

      {selectedGame ? (
        <>
          <PanelSectionRow>
            <ButtonItem layout="below" onClick={handleEnable} disabled={enabling || disabling}>
              {enabling ? "Enabling..." : "Enable for selected game"}
            </ButtonItem>
          </PanelSectionRow>
          <PanelSectionRow>
            <ButtonItem layout="below" onClick={handleDisable} disabled={enabling || disabling}>
              {disabling ? "Cleaning..." : "Disable and clean selected game"}
            </ButtonItem>
          </PanelSectionRow>
        </>
      ) : null}
    </PanelSection>
  );
}