summaryrefslogtreecommitdiff
path: root/src/components/SteamGamePatcher.tsx
blob: 06c373c2a46f17e2d4bd914604c2ab9f4127aa54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import { useCallback, useEffect, useMemo, useState } from "react";
import { ButtonItem, DropdownItem, Field, PanelSectionRow } from "@decky/ui";
import { listInstalledGames } from "../api";
import { createAutoCleanupTimer } from "../utils";
import { TIMEOUTS } from "../utils/constants";

// ─── SteamClient helpers ─────────────────────────────────────────────────────

/**
 * Wrap the callback-based RegisterForAppDetails in a Promise.
 * Resolves with the current launch options string, or "" if SteamClient is
 * unavailable (e.g. desktop / dev mode).  Times out after 5 seconds.
 */
const getSteamLaunchOptions = (appId: number): Promise<string> =>
  new Promise((resolve, reject) => {
    if (
      typeof SteamClient === "undefined" ||
      !SteamClient?.Apps?.RegisterForAppDetails
    ) {
      resolve("");
      return;
    }

    let settled = false;
    let unregister = () => {};

    const timeout = window.setTimeout(() => {
      if (settled) return;
      settled = true;
      unregister();
      reject(new Error("Timed out reading launch options."));
    }, 5000);

    const registration = SteamClient.Apps.RegisterForAppDetails(
      appId,
      (details: { strLaunchOptions?: string }) => {
        if (settled) return;
        settled = true;
        window.clearTimeout(timeout);
        unregister();
        resolve(details?.strLaunchOptions ?? "");
      }
    );

    unregister = registration.unregister;
  });

const setSteamLaunchOptions = (appId: number, options: string): void => {
  if (
    typeof SteamClient === "undefined" ||
    !SteamClient?.Apps?.SetAppLaunchOptions
  ) {
    throw new Error("SteamClient.Apps.SetAppLaunchOptions is not available.");
  }
  SteamClient.Apps.SetAppLaunchOptions(appId, options);
};

// ─── Helpers ─────────────────────────────────────────────────────────────────

/** Remove any fgmod invocation from a launch options string, keeping the rest. */
const stripFgmod = (opts: string): string =>
  opts
    .replace(/DLL=\S+\s+~\/fgmod\/fgmod\s+%command%/g, "")
    .replace(/~\/fgmod\/fgmod\s+%command%/g, "")
    .trim();

/** Extract the DLL= value from a launch options string, if present. */
const extractDllName = (opts: string): string | null => {
  const m = opts.match(/DLL=(\S+)\s+~\/fgmod\/fgmod/);
  return m ? m[1] : null;
};

// ─── Component ───────────────────────────────────────────────────────────────

interface SteamGamePatcherProps {
  dllName: string;
}

type GameEntry = { appid: string; name: string };

export function SteamGamePatcher({ dllName }: SteamGamePatcherProps) {
  const [games, setGames] = useState<GameEntry[]>([]);
  const [gamesLoading, setGamesLoading] = useState(true);
  const [selectedAppId, setSelectedAppId] = useState<string>("");
  const [launchOptions, setLaunchOptions] = useState<string>("");
  const [launchOptionsLoading, setLaunchOptionsLoading] = useState(false);
  const [busy, setBusy] = useState(false);
  const [resultMessage, setResultMessage] = useState<string>("");

  // Auto-clear result message
  useEffect(() => {
    if (resultMessage) {
      return createAutoCleanupTimer(
        () => setResultMessage(""),
        TIMEOUTS.resultDisplay
      );
    }
    return undefined;
  }, [resultMessage]);

  // Load game list on mount
  useEffect(() => {
    let cancelled = false;
    (async () => {
      setGamesLoading(true);
      try {
        const result = await listInstalledGames();
        if (cancelled) return;
        if (result.status === "success" && result.games.length > 0) {
          setGames(result.games);
          setSelectedAppId(result.games[0].appid);
        }
      } catch (e) {
        console.error("SteamGamePatcher: failed to load games", e);
      } finally {
        if (!cancelled) setGamesLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  // Reload launch options when selected game changes
  useEffect(() => {
    if (!selectedAppId) {
      setLaunchOptions("");
      return;
    }
    let cancelled = false;
    (async () => {
      setLaunchOptionsLoading(true);
      try {
        const opts = await getSteamLaunchOptions(Number(selectedAppId));
        if (!cancelled) setLaunchOptions(opts);
      } catch {
        if (!cancelled) setLaunchOptions("");
      } finally {
        if (!cancelled) setLaunchOptionsLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [selectedAppId]);

  const targetCommand = `DLL=${dllName} ~/fgmod/fgmod %command%`;
  const isManaged = launchOptions.includes("fgmod/fgmod");
  const activeDll = useMemo(() => extractDllName(launchOptions), [launchOptions]);
  const selectedGame = useMemo(
    () => games.find((g) => g.appid === selectedAppId) ?? null,
    [games, selectedAppId]
  );

  const handleSet = useCallback(() => {
    if (!selectedAppId || busy) return;
    setBusy(true);
    try {
      setSteamLaunchOptions(Number(selectedAppId), targetCommand);
      setLaunchOptions(targetCommand);
      setResultMessage(
        `Launch options set for ${selectedGame?.name ?? selectedAppId}`
      );
    } catch (e) {
      setResultMessage(`Error: ${e instanceof Error ? e.message : String(e)}`);
    } finally {
      setBusy(false);
    }
  }, [selectedAppId, targetCommand, selectedGame, busy]);

  const handleRemove = useCallback(() => {
    if (!selectedAppId || busy) return;
    setBusy(true);
    try {
      const stripped = stripFgmod(launchOptions);
      setSteamLaunchOptions(Number(selectedAppId), stripped);
      setLaunchOptions(stripped);
      setResultMessage(
        `Removed fgmod from ${selectedGame?.name ?? selectedAppId}`
      );
    } catch (e) {
      setResultMessage(`Error: ${e instanceof Error ? e.message : String(e)}`);
    } finally {
      setBusy(false);
    }
  }, [selectedAppId, launchOptions, selectedGame, busy]);

  // ── Status display ──────────────────────────────────────────────────────────
  const statusText = useMemo(() => {
    if (!selectedGame) return "—";
    if (launchOptionsLoading) return "Loading...";
    if (!isManaged) return "Not set";
    if (activeDll && activeDll !== dllName)
      return `Active — ${activeDll} · switch to apply ${dllName}`;
    return `Active — ${activeDll ?? dllName}`;
  }, [selectedGame, launchOptionsLoading, isManaged, activeDll, dllName]);

  const statusColor = useMemo(() => {
    if (!isManaged || launchOptionsLoading) return undefined;
    if (activeDll && activeDll !== dllName) return "#ffd866"; // yellow — different DLL selected
    return "#3fb950"; // green — active and matching
  }, [isManaged, launchOptionsLoading, activeDll, dllName]);

  const setButtonLabel = useMemo(() => {
    if (busy) return "Applying...";
    if (!isManaged) return "Enable for this game";
    if (activeDll && activeDll !== dllName) return `Switch to ${dllName}`;
    return "Re-apply";
  }, [busy, isManaged, activeDll, dllName]);

  return (
    <>
      <PanelSectionRow>
        <DropdownItem
          label="Steam game"
          menuLabel="Select a Steam game"
          strDefaultLabel={
            gamesLoading ? "Loading games..." : "Choose a game"
          }
          disabled={gamesLoading || games.length === 0}
          selectedOption={selectedAppId}
          rgOptions={games.map((g) => ({ data: g.appid, label: g.name }))}
          onChange={(option) => {
            setSelectedAppId(String(option.data));
            setResultMessage("");
          }}
        />
      </PanelSectionRow>

      {selectedGame && (
        <>
          <PanelSectionRow>
            <Field focusable label="Launch options status">
              {statusColor ? (
                <span style={{ color: statusColor, fontWeight: 600 }}>
                  {statusText}
                </span>
              ) : (
                statusText
              )}
            </Field>
          </PanelSectionRow>

          <PanelSectionRow>
            <ButtonItem
              layout="below"
              disabled={busy || launchOptionsLoading}
              onClick={handleSet}
            >
              {setButtonLabel}
            </ButtonItem>
          </PanelSectionRow>

          {isManaged && (
            <PanelSectionRow>
              <ButtonItem
                layout="below"
                disabled={busy}
                onClick={handleRemove}
              >
                {busy ? "Removing..." : "Remove from launch options"}
              </ButtonItem>
            </PanelSectionRow>
          )}

          {resultMessage && (
            <PanelSectionRow>
              <Field focusable label="Result">
                {resultMessage}
              </Field>
            </PanelSectionRow>
          )}
        </>
      )}
    </>
  );
}