A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.
TypeScript amazon-primeelectronepic-games-launcherepic-games-storeepic-storegaminggoggog-galaxyheroic-games-launcherlinuxplay-gamesprotonsteamwine
[Feat] Add Sideload Presets and Auto Game detection for their Games (#6192)
Flávio Fearn55f63bb49847
diff --git a/.storybook/mocks/electronApi.ts b/.storybook/mocks/electronApi.tsindex bb603b884..8d90d9ca6 100644--- a/.storybook/mocks/electronApi.ts+++ b/.storybook/mocks/electronApi.ts@@ -53,6 +53,22 @@ const defaults: Record<string, unknown> = {readFile: () => Promise.resolve(''),winetricksListInstalled: () => Promise.resolve([]),winetricksListAvailable: () => Promise.resolve([]),+ getSideloadPresetStatuses: () => Promise.resolve({}),+ scanSideloadPresetGames: () => Promise.resolve({ games: [] }),+ addScannedSideloadGames: () => Promise.resolve({ added: [] }),+ getSideloadPresetArtwork: (presetId: string) => {+ const artwork: Record<string, string> = {+ battlenet: 'battlenet',+ 'ea-app': 'ea',+ 'ubisoft-connect': 'ubisoft',+ 'xbox-cloud': 'xbox'+ }+ const file = artwork[presetId]+ return Promise.resolve({+ square: file ? `/presets/${file}-square.jpg` : '',+ hero: file ? `/presets/${file}-hero.jpg` : ''+ })+ },steamgriddb: {hasApiKey: () => Promise.resolve(false),setApiKey: () => Promise.resolve(),diff --git a/e2e/sideload_presets.spec.ts b/e2e/sideload_presets.spec.tsnew file mode 100644index 000000000..b80537d20--- /dev/null+++ b/e2e/sideload_presets.spec.ts@@ -0,0 +1,71 @@+import { expect, test } from '@playwright/test'+import { electronTest } from './helpers'++electronTest('Add game presets', async (app, page) => {+ await test.step('shows the preset picker', async () => {+ await page+ .getByRole('button', { name: /add game/i })+ .first()+ .click()+ await expect(page.locator('.presetPicker')).toBeVisible()+ await expect(page.getByTestId('preset-battlenet')).toBeVisible()+ await expect(page.getByTestId('preset-xbox-cloud')).toBeVisible()+ })++ await test.step('returns to the picker from a launcher preset', async () => {+ await page.getByTestId('preset-battlenet').click()+ await expect(page.locator('.sideloadCompatForm')).toBeVisible()+ await expect(page.locator('.sideloadFooterMetadata')).toContainText(+ 'Battle.net'+ )++ await page.getByText('Advanced', { exact: true }).click()+ await expect(+ page.getByRole('button', { name: /run winetricks/i })+ ).toBeVisible()+ await expect(+ page.getByText('Environment variables', { exact: true })+ ).toBeVisible()++ await page.getByRole('button', { name: /^back$/i }).click()+ await expect(page.locator('.presetPicker')).toBeVisible()+ })++ await test.step('offers a silent install for Ubisoft Connect', async () => {+ await page.getByTestId('preset-ubisoft-connect').click()+ await expect(page.locator('.sideloadCompatForm')).toBeVisible()+ await expect(+ page.getByText('Silent installation', { exact: true })+ ).toBeVisible()+ await page.getByRole('button', { name: /^back$/i }).click()+ await expect(page.locator('.presetPicker')).toBeVisible()+ })++ await test.step('adds a web app preset in one click', async () => {+ await page.getByTestId('preset-xbox-cloud').click()+ await expect(page.locator('#sideload-game-url')).toHaveValue(+ 'https://www.xbox.com/play'+ )+ await expect(page.locator('#launch-fullscreen')).toBeChecked()++ await page.getByRole('button', { name: /^finish$/i }).click()+ await expect(page.locator('.presetPicker')).toBeHidden()+ await expect(+ page.getByText('Xbox Cloud Gaming', { exact: true }).first()+ ).toBeVisible()+ })++ await test.step('marks installed presets and warns before reuse', async () => {+ await page+ .getByRole('button', { name: /add game/i })+ .first()+ .click()+ const xboxCard = page.getByTestId('preset-xbox-cloud')+ await expect(xboxCard).toHaveClass(/presetCard--installed/)++ await xboxCard.click()+ await expect(page.getByText(/is already installed/i)).toBeVisible()+ await page.getByRole('button', { name: /^continue anyway$/i }).click()+ await expect(page.locator('#sideload-game-url')).toBeVisible()+ })+})diff --git a/public/locales/en/gamepage.json b/public/locales/en/gamepage.jsonindex ae9d982b1..b54017c4f 100644--- a/public/locales/en/gamepage.json+++ b/public/locales/en/gamepage.json@@ -1,5 +1,6 @@{"box": {+ "cancel": "Cancel","change": {"message": "This will change the install location of this game, are you sure?","path": "Choose a new install path",@@ -48,7 +49,8 @@"title": "Select Launch Option ({{seconds}}s)"},"sideload": {- "exe": "Select Executable"+ "exe": "Select Executable",+ "launcher-exe": "Select the launcher executable"},"stopInstall": {"keepInstalling": "Keep installing",@@ -72,6 +74,7 @@"message": "Do you want to uninstall \"{{title}}\"?","prefix_warning": "The Wine prefix for this game is the default prefix. If you really want to delete it, you have to do it manually.","settingcheckbox": "Erase settings and remove log{{newLine}}Note: This can't be undone. Any modified settings will be forgotten and log will be deleted.",+ "shared_prefix_warning": "This game uses the launcher prefix, which may be shared by other scanned games. Remove the launcher itself to delete that prefix.","title": "Uninstall"},"update": {@@ -358,6 +361,45 @@}},"report_problem": "Report a problem running this game",+ "scan-games": {+ "add-selected": "Add selected",+ "added": "Added",+ "adding": "Adding…",+ "button": "Scan installed games",+ "button-short": "Scan games",+ "cancel": "Cancel",+ "empty": "No installed games were found. Install a game through {{launcher}}, then use Rescan.",+ "error": {+ "add": "Could not add the selected games: {{error}}",+ "generic": "Could not scan the launcher prefix: {{error}}",+ "prefix-not-found": "The Wine prefix used by {{launcher}} was not found.",+ "registry-not-found": "Could not read the Wine registry for this prefix.",+ "title": "Could not add games",+ "unsupported-platform": "Scanning installed games is only available for Wine/Proton prefixes."+ },+ "launch-direct": "Direct executable",+ "launch-via": "Launches via {{launcher}}",+ "loading": "Scanning the prefix…",+ "missing": {+ "banner": "Still in your Heroic library, but no longer installed by {{launcher}}:",+ "confirm-message": "These games were removed from {{launcher}} but are still in your Heroic library:",+ "confirm-title": "Remove from Heroic?",+ "failed": "Could not remove the games from Heroic: {{error}}",+ "remove": "Remove from Heroic",+ "removing": "Removing…",+ "title": "Games no longer installed"+ },+ "rescan": "Rescan",+ "select": "Select {{title}}",+ "subtitle": "Games installed by {{launcher}} in this prefix:",+ "success": {+ "message_one": "The game was added to your library.",+ "message_other": "{{count}} games were added to your library.",+ "none": "No new games were added; they are already in your library.",+ "title": "Added to your library"+ },+ "title": "Scan installed games"+ },"sdl": {"title": "Select components to Install"},@@ -368,6 +410,15 @@"winecrossoverbottle": "CrossOver Bottle"},"sideload": {+ "advanced": {+ "hint": "Optional. Configure Wine dependencies, the UMU GAMEID and environment variables before installing.",+ "title": "Advanced",+ "umu-id": "UMU GAMEID",+ "umu-info": "UMU uses GAMEID to apply Proton fixes and store metadata. Set it when the game or launcher is missing from the UMU database.",+ "umu-placeholder": "Leave blank to use the default",+ "winetricks": "Run winetricks",+ "winetricks-description": "Install Wine dependencies in the selected prefix. They are used by the installer and by the app after it is added."+ },"field": {"title": "Title"},@@ -385,7 +436,13 @@"cover-hint": "Cover/Hero Art (click on the image to search on SteamGridDB)","exe": "Select Executable","fullscreen": "Launch Fullscreen (F11 to exit)",+ "game-executable": "Game executable","image-hint": "Square Art (click on the image to search on SteamGridDB)",+ "launcher-exe": "Heroic identified the executables in this prefix, but this entry must launch the launcher itself ({{title}}). Do not select a game executable here; installed games can be added later with Scan games on the launcher page.",+ "launcher-exe-label": "Launcher executable",+ "launcher-exe-placeholder": "Launcher executable",+ "launcher-shortcuts-hint": "Heroic found the executables below. Keep the launcher ({{title}}) selected; game executables are added later with Scan games.",+ "launcher-shortcuts-title": "Detected software — choose the launcher","no-proton-shortcuts": {"subtitle": "Heroic didn't detect any installed software. Please select the executable manually instead.","title": "No shortcuts found"@@ -404,6 +461,99 @@"url": "Paste the Game URL here","useragent": "Write a custom user agent here to be used on this browser app/game"},+ "presets": {+ "add": "Add",+ "add-again": "Add again",+ "badge-launcher": "Launcher",+ "badge-web": "Web app",+ "battlenet": {+ "description": "Blizzard's launcher for World of Warcraft, Diablo, Overwatch and more."+ },+ "cancel": "Cancel",+ "check-again": "Check again",+ "closing": {+ "cancel": "Keep installing",+ "continue": "Close anyway",+ "message": "The installer is still running. Close the window anyway? The installer may keep running in the background.",+ "title": "Installation is still running"+ },+ "continue": "Continue anyway",+ "custom": {+ "action": "Custom",+ "description": "Use any executable, script or web URL.",+ "store-hint": "Epic, GOG and Amazon games should be imported from your library after logging in, not added here.",+ "title": "Add a custom app, game or script"+ },+ "detecting": "Looking for the installed application…",+ "disclaimer-short": "Presets download the official installer directly from the vendor. No third-party software is bundled.",+ "done": "Executable found, you can finish the setup.",+ "downloading": "Downloading the installer…",+ "downloading-hint": "Heroic downloads {{title}} directly from the official vendor endpoint. Nothing is bundled with the app.",+ "ea-app": {+ "description": "Electronic Arts' launcher for EA games.",+ "note": "The EA app needs a recent Wine version. If the installer fails, try a different Wine or Proton version in the setup step."+ },+ "error": {+ "description": "Heroic could not finish setting up {{title}}. You can try again or select the executable manually.",+ "title": "Something went wrong"+ },+ "installed": "Installed",+ "installed-warning": {+ "message": "Continuing will run the preset again and may reinstall or overwrite files in {{prefix}}. You can change the prefix in the next step.",+ "no-prefix-message": "Continuing will run the preset again. You can adjust the setup in the next step.",+ "title": "{{title}} is already installed"+ },+ "macos-installer-notice": "macOS: the installer starts {{title}} at the end. That window can stay blank because the installer doesn't use Heroic's graphics settings. Close it, finish the setup, and start {{title}} from Heroic.",+ "macos-requires-crossover": "macOS: this launcher needs the commercial CrossOver version. Free Wine builds can install it, but its window does not open.",+ "next-steps": "Open {{title}}, sign in, install a game there, then return to this page and use \"Scan games\" to add it to Heroic.",+ "not-found": {+ "description": "The installer finished, but Heroic couldn't locate {{title}} in the Wine prefix. You can try again, or select the executable manually.",+ "title": "We couldn't find the installed app"+ },+ "or-use-presets": "Or use one of our presets",+ "prefix-warning": {+ "message": "Heroic found an existing prefix at {{prefix}}. Continuing will reuse it. You can change it in the next step.",+ "title": "A Wine prefix already exists"+ },+ "preparing": "Preparing the installer…",+ "retry": "Try again",+ "retry-interactive": "Run installer interactively",+ "running": {+ "description": "Finish the installer in the window that just opened. If the installer launches {{title}} at the end, close it so Heroic can continue. You can also continue now and pick the executable manually.",+ "title": "Complete the {{title}} installation",+ "waiting-log": "Waiting for installer output…"+ },+ "scan-platform-note": "Scanning installed games is currently available on Linux and macOS only. On Windows, add games with the custom flow for now.",+ "select-manually": "Select executable manually",+ "silent-install": {+ "description": "Run the installer without showing its window. Turn this off if the silent install fails.",+ "title": "Silent installation"+ },+ "step": {+ "install": "Installation",+ "install-desc": "Download and run the installer",+ "install-options": "Installation options",+ "install-options-desc": "Silent installation",+ "options": "Options",+ "options-desc": "Executable and launch options",+ "setup": "Setup",+ "setup-desc": "Wine prefix and version"+ },+ "subtitle": "Start from a preset, or add your own executable or web URL.",+ "title": "Add a game or app",+ "ubisoft-connect": {+ "description": "Ubisoft's launcher for Assassin's Creed, Far Cry and more.",+ "note": "Ubisoft Connect can be picky about Wine versions. If it does not start, check Heroic's wiki page for Ubisoft Connect."+ },+ "warning": {+ "cancel": "Cancel",+ "continue": "Continue anyway"+ },+ "xbox-cloud": {+ "description": "Stream Xbox games from the cloud in a dedicated fullscreen window.",+ "note": "Xbox Cloud Gaming is officially supported in Edge and Chrome on Windows and macOS. On Linux, Microsoft may block streaming, and gamepad support depends on your setup."+ }+ },"step": {"compat": "Compatibility","compat-desc": "Wine / Proton setup",diff --git a/public/presets/ATTRIBUTION.md b/public/presets/ATTRIBUTION.mdnew file mode 100644index 000000000..15c61c441--- /dev/null+++ b/public/presets/ATTRIBUTION.md@@ -0,0 +1,14 @@+# Preset artwork++The brand marks used by the Add Game presets are trademarks of their respective+owners and are used only to identify the application they belong to.++- Battle.net, EA and Ubisoft marks: [Simple Icons](https://simpleicons.org)+ (CC0 1.0), rasterized and composed by Heroic.+- Xbox Cloud Gaming cover: from [SteamGridDB](https://www.steamgriddb.com),+ retrieved through the SteamGrid USBottles API+ (`https://steamgrid.usebottles.com/api/search/Xbox%20Cloud%20Gaming`).+ All rights belong to the original author.+- Backgrounds and compositions: original Heroic artwork.++If you are a rights holder and want an asset changed or removed, open an issue.diff --git a/public/presets/battlenet-hero.jpg b/public/presets/battlenet-hero.jpgnew file mode 100644index 000000000..e4ef85ca8Binary files /dev/null and b/public/presets/battlenet-hero.jpg differdiff --git a/public/presets/battlenet-square.jpg b/public/presets/battlenet-square.jpgnew file mode 100644index 000000000..ff4a872e5Binary files /dev/null and b/public/presets/battlenet-square.jpg differdiff --git a/public/presets/ea-hero.jpg b/public/presets/ea-hero.jpgnew file mode 100644index 000000000..82121df2cBinary files /dev/null and b/public/presets/ea-hero.jpg differdiff --git a/public/presets/ea-square.jpg b/public/presets/ea-square.jpgnew file mode 100644index 000000000..b720c9e1eBinary files /dev/null and b/public/presets/ea-square.jpg differdiff --git a/public/presets/ubisoft-hero.jpg b/public/presets/ubisoft-hero.jpgnew file mode 100644index 000000000..9ce9b4e3fBinary files /dev/null and b/public/presets/ubisoft-hero.jpg differdiff --git a/public/presets/ubisoft-square.jpg b/public/presets/ubisoft-square.jpgnew file mode 100644index 000000000..139fadd83Binary files /dev/null and b/public/presets/ubisoft-square.jpg differdiff --git a/public/presets/xbox-hero.jpg b/public/presets/xbox-hero.jpgnew file mode 100644index 000000000..9539019aeBinary files /dev/null and b/public/presets/xbox-hero.jpg differdiff --git a/public/presets/xbox-square.jpg b/public/presets/xbox-square.jpgnew file mode 100644index 000000000..8249a4719Binary files /dev/null and b/public/presets/xbox-square.jpg differdiff --git a/src/backend/__tests__/sideload_presets.test.ts b/src/backend/__tests__/sideload_presets.test.tsnew file mode 100644index 000000000..1c06f7f5a--- /dev/null+++ b/src/backend/__tests__/sideload_presets.test.ts@@ -0,0 +1,228 @@+import { existsSync } from 'graceful-fs'+import { join, resolve } from 'path'++import {+ SIDELOAD_PRESETS,+ getPresetInstallerArgs,+ getSideloadPreset,+ getSideloadPresetAppName,+ getSideloadPresetLaunchArgs,+ getSideloadPresetLaunchEnv,+ getSideloadPresetPlatform+} from 'common/sideload_presets'+import {+ getPresetCandidatePaths,+ getPresetSearchRoots+} from 'backend/storeManagers/sideload/preset_paths'+import { getPresetWinePrefix } from 'backend/storeManagers/sideload/presets'++const publicPresetsFolder = resolve(__dirname, '../../..', 'public', 'presets')++function normalize(path: string) {+ return path.replaceAll('\\', '/')+}++describe('sideload preset catalog', () => {+ it('has unique ids', () => {+ const ids = SIDELOAD_PRESETS.map((preset) => preset.id)+ expect(new Set(ids).size).toBe(ids.length)+ })++ it('ships the bundled artwork for every preset', () => {+ for (const preset of SIDELOAD_PRESETS) {+ expect(existsSync(join(publicPresetsFolder, preset.artwork.square))).toBe(+ true+ )+ expect(existsSync(join(publicPresetsFolder, preset.artwork.hero))).toBe(+ true+ )+ }+ })++ it('only points launcher installers to HTTPS and executable files', () => {+ for (const preset of SIDELOAD_PRESETS) {+ if (!preset.launcher) {+ continue+ }+ expect(preset.launcher.installer.url).toMatch(/^https:\/\//)+ expect(preset.launcher.installer.fileName).toMatch(/\.exe$/)+ expect(preset.launcher.exeCandidates.length).toBeGreaterThan(0)+ }+ })++ it('only gives web presets a browser URL', () => {+ for (const preset of SIDELOAD_PRESETS) {+ if (preset.kind === 'web') {+ expect(preset.web?.url).toMatch(/^https:\/\//)+ expect(preset.launcher).toBeUndefined()+ } else {+ expect(preset.launcher).toBeDefined()+ expect(preset.web).toBeUndefined()+ }+ }+ })++ it('only advertises silent installs where the vendor supports them', () => {+ const ea = getSideloadPreset('ea-app')+ const ubisoft = getSideloadPreset('ubisoft-connect')+ const battlenet = getSideloadPreset('battlenet')++ expect(ea?.launcher?.installer.silentArgs).toBeUndefined()+ expect(ubisoft?.launcher?.installer.silentArgs).toEqual(['/S'])+ expect(battlenet?.launcher?.installer.silentArgs).toBeUndefined()+ expect(battlenet?.launcher?.installer.env?.WINE_SIMULATE_WRITECOPY).toBe(+ '1'+ )+ })++ it('uses silent args only when the preset supports them', () => {+ const ubisoft = getSideloadPreset('ubisoft-connect')!+ const ea = getSideloadPreset('ea-app')!++ expect(getPresetInstallerArgs(ubisoft, true)).toEqual(['/S'])+ expect(getPresetInstallerArgs(ubisoft, false)).toEqual([])+ expect(getPresetInstallerArgs(ea, true)).toEqual([+ 'EAX_LAUNCH_CLIENT=0',+ 'IGNORE_INSTALLED=1'+ ])+ })++ it('applies the Battle.net window fixes when launching on macOS', () => {+ const battlenet = getSideloadPreset('battlenet')!+ const launchArgs = getSideloadPresetLaunchArgs(battlenet, 'darwin')++ expect(launchArgs).toContain('--use-gl=swiftshader')+ expect(launchArgs).toContain('--in-process-gpu')+ expect(launchArgs).toContain('--disable-gpu-compositing')+ expect(getSideloadPresetLaunchArgs(battlenet, 'linux')).toEqual([])+ expect(getSideloadPresetLaunchEnv(battlenet)).toEqual({+ WINE_SIMULATE_WRITECOPY: '1'+ })+ expect(battlenet.launcher?.exeCandidates[0]).toBe(+ 'Program Files (x86)/Battle.net/Battle.net.exe'+ )+ expect(battlenet.launcher?.preferredWineType?.darwin).toBe('wine')+ expect(battlenet.launcher?.preferredWineType?.linux).toBeUndefined()+ expect(battlenet.installerOpensApp).toEqual(['darwin'])+ })++ it('points macOS users to CrossOver for Ubisoft Connect', () => {+ const ubisoft = getSideloadPreset('ubisoft-connect')!++ expect(ubisoft.requiresCrossover).toEqual(['darwin'])+ })++ it('uses stable app names and the right install platform', () => {+ const battlenet = getSideloadPreset('battlenet')+ const xbox = getSideloadPreset('xbox-cloud')++ expect(battlenet).toBeDefined()+ expect(xbox).toBeDefined()+ expect(getSideloadPresetAppName(battlenet!)).toBe('preset-battlenet')+ expect(getSideloadPresetPlatform(battlenet!)).toBe('Windows')+ expect(getSideloadPresetPlatform(xbox!)).toBe('Browser')+ })+})++describe('getPresetCandidatePaths', () => {+ it('checks both plain Wine and Proton prefix layouts', () => {+ const preset = getSideloadPreset('battlenet')!+ const candidates = getPresetCandidatePaths(preset, {+ isWindows: false,+ winePrefix: '/prefixes/battlenet'+ })++ expect(candidates.map(normalize)).toContain(+ '/prefixes/battlenet/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe'+ )+ expect(candidates.map(normalize)).toContain(+ '/prefixes/battlenet/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe'+ )+ })++ it('resolves Windows Program Files folders', () => {+ const preset = getSideloadPreset('ea-app')!+ const candidates = getPresetCandidatePaths(preset, {+ isWindows: true,+ programFiles: 'C:\\Program Files',+ programFilesX86: 'C:\\Program Files (x86)'+ })++ expect(candidates.map(normalize)).toContain(+ 'C:/Program Files/Electronic Arts/EA Desktop/EA Desktop/EALauncher.exe'+ )+ })++ it('returns no executable candidates for web presets', () => {+ const preset = getSideloadPreset('xbox-cloud')!+ expect(+ getPresetCandidatePaths(preset, {+ isWindows: false,+ winePrefix: '/prefixes/xbox'+ })+ ).toEqual([])+ })++ it('resolves versioned install roots for the EA app', () => {+ const preset = getSideloadPreset('ea-app')!+ const roots = getPresetSearchRoots(preset, {+ isWindows: false,+ winePrefix: '/prefixes/ea'+ })++ expect(roots.map(normalize)).toEqual([+ '/prefixes/ea/pfx/drive_c/Program Files/Electronic Arts/EA Desktop',+ '/prefixes/ea/drive_c/Program Files/Electronic Arts/EA Desktop'+ ])+ })++ it('returns no candidates without a prefix', () => {+ const preset = getSideloadPreset('ubisoft-connect')!+ expect(+ getPresetCandidatePaths(preset, { isWindows: false, winePrefix: '' })+ ).toEqual([])+ })++ it('normalizes Windows separators before joining', () => {+ const preset = getSideloadPreset('battlenet')!+ const windowsStyle = {+ ...preset,+ launcher: {+ ...preset.launcher!,+ exeCandidates: ['Program Files\\Battle.net\\Battle.net.exe']+ }+ }++ expect(+ getPresetCandidatePaths(windowsStyle, {+ isWindows: false,+ winePrefix: '/prefixes/battlenet'+ }).map(normalize)+ ).toContain(+ '/prefixes/battlenet/drive_c/Program Files/Battle.net/Battle.net.exe'+ )+ })+})++describe('getPresetWinePrefix', () => {+ it('does not fall back to the shared default prefix', () => {+ expect(getPresetWinePrefix({ version: 'v0.1' }, 'preset-ea-app')).toBe(+ undefined+ )+ expect(+ getPresetWinePrefix(+ { version: 'v0.1', 'preset-ea-app': {} },+ 'preset-ea-app'+ )+ ).toBe(undefined)+ })++ it('reads the prefix stored in the preset config', () => {+ expect(+ getPresetWinePrefix(+ { 'preset-ea-app': { winePrefix: '/prefixes/ea' } },+ 'preset-ea-app'+ )+ ).toBe('/prefixes/ea')+ })+})diff --git a/src/backend/__tests__/sideload_presets_installer.test.ts b/src/backend/__tests__/sideload_presets_installer.test.tsnew file mode 100644index 000000000..9b87627a5--- /dev/null+++ b/src/backend/__tests__/sideload_presets_installer.test.ts@@ -0,0 +1,79 @@+import { existsSync } from 'graceful-fs'++import { GameConfig } from 'backend/game_config'+import { runWineCommand } from 'backend/launcher'+import { runPresetInstaller } from 'backend/storeManagers/sideload/presets'++import type { GameSettings } from 'common/types'++jest.mock('graceful-fs', (): typeof import('graceful-fs') => ({+ ...jest.requireActual<typeof import('graceful-fs')>('graceful-fs'),+ existsSync: jest.fn()+}))+jest.mock('backend/launcher', () => ({ runWineCommand: jest.fn() }))+jest.mock('backend/game_config', () => ({ GameConfig: { get: jest.fn() } }))+jest.mock('backend/logger', () => ({+ createGameLogWriter: jest.fn(() =>+ Promise.resolve({ writeString: jest.fn() })+ ),+ logInfo: jest.fn(),+ logWarning: jest.fn(),+ LogPrefix: { Sideload: 'Sideload' }+}))+jest.mock('backend/ipc', () => ({ sendFrontendMessage: jest.fn() }))+jest.mock('backend/utils', () => ({+ downloadFile: jest.fn(),+ spawnAsync: jest.fn()+}))+jest.mock('backend/constants/environment', () => ({ isWindows: false }))+jest.mock('backend/constants/paths', () => ({+ gamesConfigPath: '/tmp/heroic/gamesConfig',+ publicDir: '/tmp/heroic/public',+ toolsPath: '/tmp/heroic/tools',+ userDataPath: '/tmp/heroic/userData'+}))++const runWineCommandMock = jest.mocked(runWineCommand)+// eslint-disable-next-line @typescript-eslint/unbound-method+const gameConfigMock = jest.mocked(GameConfig.get)+const existsSyncMock = jest.mocked(existsSync)++const gameSettings = {+ winePrefix: '/prefixes/preset-battlenet',+ wineVersion: { bin: '/wine/bin/wine' }+} as unknown as GameSettings++describe('runPresetInstaller', () => {+ beforeEach(() => {+ jest.clearAllMocks()+ existsSyncMock.mockReturnValue(true)+ gameConfigMock.mockReturnValue({+ config: gameSettings+ } as unknown as ReturnType<typeof GameConfig.get>)+ })++ it('reports a clean install when the installer exits with 0', async () => {+ runWineCommandMock.mockResolvedValue({+ stdout: '',+ stderr: '',+ code: 0+ })++ await expect(runPresetInstaller('battlenet')).resolves.toEqual({+ status: 'done'+ })+ })++ it('reports the installer exit code when it fails', async () => {+ runWineCommandMock.mockResolvedValue({+ stdout: '',+ stderr: '',+ code: 1+ })++ await expect(runPresetInstaller('battlenet')).resolves.toEqual({+ status: 'error',+ error: 'installer-exit-1'+ })+ })+})diff --git a/src/backend/__tests__/sideload_scan.test.ts b/src/backend/__tests__/sideload_scan.test.tsnew file mode 100644index 000000000..1b0fc96c7--- /dev/null+++ b/src/backend/__tests__/sideload_scan.test.ts@@ -0,0 +1,206 @@+import {+ mkdirSync,+ mkdtempSync,+ rmSync,+ symlinkSync,+ writeFileSync+} from 'graceful-fs'+import { tmpdir } from 'os'+import { join } from 'path'++import { getSideloadPreset } from 'common/sideload_presets'+import {+ decodeRegistryString,+ parseWineRegistry,+ scanGamesForPreset+} from 'backend/storeManagers/sideload/scan'++describe('sideload registry scanning', () => {+ it('decodes Wine registry escapes', () => {+ expect(decodeRegistryString('Assassin\\x2019s Creed')).toBe(+ 'Assassin’s Creed'+ )+ expect(decodeRegistryString('C:\\\\Program Files\\\\Game')).toBe(+ 'C:\\Program Files\\Game'+ )+ })++ it('does not corrupt path segments that start with escape letters', () => {+ expect(decodeRegistryString('C:\\\\new\\\\tools\\\\temp\\\\x86_64')).toBe(+ 'C:\\new\\tools\\temp\\x86_64'+ )+ expect(decodeRegistryString('C:\\\\x86_64\\\\game.exe')).toBe(+ 'C:\\x86_64\\game.exe'+ )+ })++ it('parses sections with timestamps and string values', () => {+ const sections = parseWineRegistry(+ [+ '[Software\\\\Wow6432Node\\\\Ubisoft\\\\Launcher\\\\Installs\\\\1848] 123',+ '#time=1',+ '"InstallDir"="C:/Games/Assassin\\x2019s Creed/"',+ '',+ '[Software\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\StarCraft] 456',+ '"DisplayName"="StarCraft"',+ '"UninstallString"="\\"C:\\\\ProgramData\\\\Battle.net\\\\Agent\\\\Blizzard Uninstaller.exe\\" --uid=s1"'+ ].join('\n')+ )++ expect(sections[0].name).toBe(+ 'Software\\Wow6432Node\\Ubisoft\\Launcher\\Installs\\1848'+ )+ expect(sections[0].values.InstallDir).toBe('C:/Games/Assassin’s Creed/')+ expect(sections[1].values.DisplayName).toBe('StarCraft')+ expect(sections[1].values.UninstallString).toContain('--uid=s1')+ })+})++describe('sideload registry adapters', () => {+ let root: string++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'heroic-scan-'))+ })++ afterEach(() => {+ rmSync(root, { recursive: true, force: true })+ })++ it('scans Ubisoft installs and builds the uplay URL', async () => {+ const gameDir = join(+ root,+ 'drive_c',+ 'Program Files (x86)',+ 'Ubisoft',+ 'Ubisoft Game Launcher',+ 'games',+ 'Assassin’s Creed Chronicles Russia'+ )+ mkdirSync(gameDir, { recursive: true })+ const sections = parseWineRegistry(+ `[Software\\Wow6432Node\\Ubisoft\\Launcher\\Installs\\1848] 1+"InstallDir"="C:/Program Files (x86)/Ubisoft/Ubisoft Game Launcher/games/Assassin\\x2019s Creed Chronicles Russia/"`+ )++ const games = await scanGamesForPreset(+ getSideloadPreset('ubisoft-connect')!,+ root,+ sections+ )++ expect(games).toHaveLength(1)+ expect(games[0].title).toBe('Assassin’s Creed Chronicles Russia')+ expect(games[0].launchUrl).toBe('uplay://launch/1848/0')+ })++ it('scans EA uninstall entries and finds the game executable', async () => {+ const gameDir = join(+ root,+ 'drive_c',+ 'Program Files',+ 'EA Games',+ 'The Sims 3'+ )+ const binDir = join(gameDir, 'Game', 'Bin')+ mkdirSync(binDir, { recursive: true })+ writeFileSync(join(binDir, 'TS3.exe'), '')+ writeFileSync(join(binDir, 'Sims3Launcher.exe'), '')+ const sections = parseWineRegistry(+ `[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{GUID}] 1+"DisplayName"="The Sims\\x2122 3"+"Publisher"="Electronic Arts Inc."+"InstallLocation"="C:\\Program Files\\EA Games\\The Sims 3\\"`+ )++ const games = await scanGamesForPreset(+ getSideloadPreset('ea-app')!,+ root,+ sections+ )++ expect(games).toHaveLength(1)+ expect(games[0].title).toBe('The Sims 3')+ expect(games[0].executable?.endsWith('TS3.exe')).toBe(true)+ })++ it('scans Battle.net products with a Blizzard uninstaller', async () => {+ const gameDir = join(+ root,+ 'drive_c',+ 'Program Files (x86)',+ 'StarCraft',+ 'x86_64'+ )+ mkdirSync(gameDir, { recursive: true })+ writeFileSync(join(gameDir, 'StarCraft.exe'), '')+ const sections = parseWineRegistry(+ `[Software\\Classes\\battlenet] 1+"URL Protocol"=hex(1):+[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\StarCraft] 1+"DisplayName"="StarCraft"+"InstallLocation"="C:\\Program Files (x86)\\StarCraft"+"UninstallString"="\\"C:\\ProgramData\\Battle.net\\Agent\\Blizzard Uninstaller.exe\\" --lang=enUS --uid=s1 --displayname=\\"StarCraft\\""`+ )++ const games = await scanGamesForPreset(+ getSideloadPreset('battlenet')!,+ root,+ sections+ )++ expect(games).toHaveLength(1)+ expect(games[0].title).toBe('StarCraft')+ expect(games[0].executable?.endsWith('StarCraft.exe')).toBe(true)+ expect(games[0].launchUrl).toBe('battlenet://s1')+ })++ it('maps non-C Wine drives through dosdevices', async () => {+ const gameDir = join(root, 'drive_d', 'EA Games', 'The Sims 3', 'Bin')+ mkdirSync(gameDir, { recursive: true })+ writeFileSync(join(gameDir, 'TS3.exe'), '')+ mkdirSync(join(root, 'dosdevices'), { recursive: true })+ symlinkSync('../drive_d', join(root, 'dosdevices', 'd:'))++ const sections = parseWineRegistry(+ `[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{GUID}] 1+"DisplayName"="The Sims 3"+"Publisher"="Electronic Arts Inc."+"InstallLocation"="D:\\EA Games\\The Sims 3\\"`+ )++ const games = await scanGamesForPreset(+ getSideloadPreset('ea-app')!,+ root,+ sections+ )++ expect(games).toHaveLength(1)+ expect(games[0].executable?.endsWith('TS3.exe')).toBe(true)+ })++ it('finds executables inside symlinked directories', async () => {+ const installDir = join(root, 'drive_c', 'EA Games', 'The Sims 3')+ const realDir = join(root, 'drive_c', 'shared', 'Bin')+ mkdirSync(realDir, { recursive: true })+ mkdirSync(installDir, { recursive: true })+ writeFileSync(join(realDir, 'TS3.exe'), '')+ symlinkSync(realDir, join(installDir, 'linked'))++ const sections = parseWineRegistry(+ `[Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{GUID}] 1+"DisplayName"="The Sims 3"+"Publisher"="Electronic Arts Inc."+"InstallLocation"="C:\\EA Games\\The Sims 3\\"`+ )++ const games = await scanGamesForPreset(+ getSideloadPreset('ea-app')!,+ root,+ sections+ )++ expect(games).toHaveLength(1)+ expect(games[0].executable?.endsWith('TS3.exe')).toBe(true)+ })+})diff --git a/src/backend/images_cache.ts b/src/backend/images_cache.tsindex fdaf3791e..2b6ef22cd 100644--- a/src/backend/images_cache.ts+++ b/src/backend/images_cache.ts@@ -7,13 +7,76 @@ import {rmSync} from 'graceful-fs'import { createHash } from 'crypto'-import { join } from 'path'+import { readFile } from 'fs/promises'+import { extname, join } from 'path'+import { fileURLToPath } from 'url'import axios from 'axios'-import { net, protocol } from 'electron'+import { protocol } from 'electron'import { appFolder } from './constants/paths'const imagesCachePath = join(appFolder, 'images-cache')+const localImageMimeTypes: Record<string, string> = {+ '.avif': 'image/avif',+ '.gif': 'image/gif',+ '.jpeg': 'image/jpeg',+ '.jpg': 'image/jpeg',+ '.png': 'image/png',+ '.svg': 'image/svg+xml',+ '.webp': 'image/webp'+}++function detectImageMimeType(data: Buffer): string {+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8) {+ return 'image/jpeg'+ }+ if (+ data.length >= 8 &&+ data[0] === 0x89 &&+ data.subarray(1, 4).toString('ascii') === 'PNG'+ ) {+ return 'image/png'+ }+ if (data.length >= 6 && data.subarray(0, 4).toString('ascii') === 'GIF8') {+ return 'image/gif'+ }+ if (+ data.length >= 12 &&+ data.subarray(0, 4).toString('ascii') === 'RIFF' &&+ data.subarray(8, 12).toString('ascii') === 'WEBP'+ ) {+ return 'image/webp'+ }+ if (+ data.length >= 12 &&+ data.subarray(4, 8).toString('ascii') === 'ftyp' &&+ data.subarray(8, 12).toString('ascii').startsWith('avif')+ ) {+ return 'image/avif'+ }+ const start = data.subarray(0, 64).toString('utf8').trim()+ if (start.startsWith('<svg') || start.startsWith('<?xml')) {+ return 'image/svg+xml'+ }+ return 'application/octet-stream'+}++async function responseFromFile(filePath: string): Promise<Response> {+ try {+ const data = await readFile(filePath)+ return new Response(data, {+ status: 200,+ headers: {+ 'Content-Type':+ localImageMimeTypes[extname(filePath).toLowerCase()] ??+ detectImageMimeType(data)+ }+ })+ } catch {+ return new Response(null, { status: 404 })+ }+}+const FAILED_MARKER_TTL_MS = 24 * 60 * 60 * 1000const MAX_CONCURRENT_DOWNLOADS = 6const DOWNLOAD_SPACING_MS = 150@@ -122,7 +185,7 @@ const getImageFromCache = async (url: string): Promise<Response> => {// from the dev server (http origin), so proxy them through this protocol too.if (realUrl.startsWith('file://')) {try {- return await net.fetch(new URL(realUrl).toString())+ return await responseFromFile(fileURLToPath(realUrl))} catch {return new Response(null, { status: 404 })}@@ -134,17 +197,17 @@ const getImageFromCache = async (url: string): Promise<Response> => {// Serve from cacheif (existsSync(cachePath)) {- return new Response(join(cachePath))+ return responseFromFile(cachePath)}// Not a downloadable URLif (!realUrl.startsWith('http')) {- return new Response(join(cachePath), { status: 404 })+ return new Response(null, { status: 404 })}// Skip recently failed downloadsif (isRecentlyFailed(digest)) {- return new Response(join(cachePath), { status: 404 })+ return new Response(null, { status: 404 })}// Reuse in-flight download@@ -158,10 +221,10 @@ const getImageFromCache = async (url: string): Promise<Response> => {const ok = await pendingPromiseif (ok && existsSync(cachePath)) {- return new Response(join(cachePath))+ return responseFromFile(cachePath)}// 404 triggers frontend fallback- return new Response(join(cachePath), { status: 404 })+ return new Response(null, { status: 404 })}// Wipe all cached imagesdiff --git a/src/backend/launcher.ts b/src/backend/launcher.tsindex 906da3d87..c5055d33c 100644--- a/src/backend/launcher.ts+++ b/src/backend/launcher.ts@@ -1172,8 +1172,10 @@ function setupWineEnvVars(gameSettings: GameSettings, gameId = '0') {// Disable Winemenubuilder to not mess with file associationsconst wmbDisableString = 'winemenubuilder.exe=d'- // If the user already set WINEDLLOVERRIDES, append to the end- const dllOverridesVar = gameSettings.enviromentOptions.find(+ // If the user already set WINEDLLOVERRIDES, append to the end. A partial+ // config (a preset that was just created, for example) may not carry the+ // list at all, and that used to crash before the prefix existed.+ const dllOverridesVar = (gameSettings.enviromentOptions ?? []).find(({ key }) => key.toLowerCase() === 'winedlloverrides')if (dllOverridesVar) {@@ -1327,21 +1329,12 @@ function setupWineEnvVars(gameSettings: GameSettings, gameId = '0') {}// add back default wine/dxvk debug loggingif (gameSettings?.verboseLogs) {- if (- !gameSettings?.enviromentOptions.find((env) => env.key === 'WINEDEBUG')- )+ const envOptions = gameSettings.enviromentOptions ?? []+ if (!envOptions.find((env) => env.key === 'WINEDEBUG'))ret.WINEDEBUG = '+fixme'- if (- !gameSettings?.enviromentOptions.find(- (env) => env.key === 'DXVK_LOG_LEVEL'- )- )+ if (!envOptions.find((env) => env.key === 'DXVK_LOG_LEVEL'))ret.DXVK_LOG_LEVEL = 'info'- if (- !gameSettings?.enviromentOptions.find(- (env) => env.key === 'VKD3D_DEBUG'- )- )+ if (!envOptions.find((env) => env.key === 'VKD3D_DEBUG'))ret.VKD3D_DEBUG = 'fixme'}}@@ -1602,6 +1595,12 @@ async function runWineCommand({PROTON_VERB: protonVerb}+ // UMU uses GAMEID to pick Proton fixes and store metadata. Sideloaded apps+ // (and installers) have no store-provided id, so allow overriding it.+ if (settings.umuGameId?.trim()) {+ env_vars.GAMEID = settings.umuGameId.trim()+ }+if (ignoreLogging) {delete env_vars['PROTON_LOG']}diff --git a/src/backend/main.ts b/src/backend/main.tsindex 86f9c0ff5..c2e5fb022 100644--- a/src/backend/main.ts+++ b/src/backend/main.ts@@ -136,6 +136,14 @@ import {initStoreManagers,libraryManagerMap} from './storeManagers'+import {+ detectPresetExecutable,+ downloadPresetInstaller,+ getPresetArtwork,+ getPresetStatuses,+ runPresetInstaller+} from './storeManagers/sideload/presets'+import { addScannedGames, scanPresetGames } from './storeManagers/sideload/scan'import {setGameOverrides,getGameOverrides,@@ -1625,6 +1633,32 @@ addListener('addNewApp', (e, args) =>libraryManagerMap['sideload'].addNewApp(args))+addHandler('getSideloadPresetArtwork', async (e, presetId) =>+ getPresetArtwork(presetId)+)++addHandler('downloadSideloadPresetInstaller', async (e, presetId) =>+ downloadPresetInstaller(presetId)+)++addHandler('runSideloadPresetInstaller', async (e, presetId, silent) =>+ runPresetInstaller(presetId, silent)+)++addHandler('detectSideloadPresetExecutable', async (e, presetId) =>+ detectPresetExecutable(presetId)+)++addHandler('getSideloadPresetStatuses', async () => getPresetStatuses())++addHandler('scanSideloadPresetGames', async (e, presetId) =>+ scanPresetGames(presetId)+)++addHandler('addScannedSideloadGames', async (e, presetId, gameIds) =>+ addScannedGames(presetId, gameIds)+)+addListener('setGameMetadataOverride', (e, args) => {const { appName, title, art_cover, art_square } = argssetGameOverrides(appName, { title, art_cover, art_square })diff --git a/src/backend/shortcuts/utils.ts b/src/backend/shortcuts/utils.tsindex 0a9b3ec6d..0f41c9526 100644--- a/src/backend/shortcuts/utils.ts+++ b/src/backend/shortcuts/utils.ts@@ -1,6 +1,13 @@-import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'graceful-fs'+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ unlinkSync,+ writeFileSync+} from 'graceful-fs'import { GameInfo } from 'common/types'import { basename, dirname, extname, join } from 'path'+import { fileURLToPath } from 'url'import { libraryManagerMap } from '../storeManagers'import { downloadFile } from 'backend/utils'import { createAbortController } from 'backend/utils/aborthandler/aborthandler'@@ -25,10 +32,17 @@ function downloadImage(outputFilePath: string): string | undefined {try {- downloadFile({+ // Preset artwork and user-picked images live on disk, not on the network.+ if (imageURL.startsWith('file://')) {+ copyFileSync(fileURLToPath(imageURL), outputFilePath)+ return+ }+ void downloadFile({url: imageURL,dest: outputFilePath,abortSignal: createAbortController(imageURL).signal+ }).catch((error) => {+ console.log(`Downloading of ${imageURL} failed:`, error)})} catch (error) {return `Donwloading of ${imageURL} failed with:\n${error}`diff --git a/src/backend/storeManagers/sideload/games.ts b/src/backend/storeManagers/sideload/games.tsindex 6360ba3e2..16121b507 100644--- a/src/backend/storeManagers/sideload/games.ts+++ b/src/backend/storeManagers/sideload/games.ts@@ -9,6 +9,7 @@ import {import { libraryStore } from './electronStores'import { GameConfig } from '../../game_config'import { killPattern, sendGameStatusUpdate, shutdownWine } from '../../utils'+import { sendFrontendMessage } from '../../ipc'import { logInfo, LogPrefix, logWarning } from 'backend/logger'import { dirname } from 'path'import { existsSync, rmSync } from 'graceful-fs'@@ -62,15 +63,24 @@ export default class SideloadGame implements Game {async isGameAvailable(): Promise<boolean> {return new Promise((resolve) => {- const { install } = this.getGameInfo()+ const { install, launchUrl } = this.getGameInfo()++ if (launchUrl) {+ resolve(true)+ return+ }if (install && install.platform === 'Browser') {resolve(true)+ return}if (install && install.executable) {resolve(existsSync(install.executable))+ return}++ resolve(false)})}@@ -84,18 +94,19 @@ export default class SideloadGame implements Game {async stop(): Promise<void> {const {- install: { executable = undefined }+ install: { executable = undefined },+ launchUrl} = this.getGameInfo()if (executable) {const split = executable.split('/')const exe = split[split.length - 1]killPattern(exe)+ }- if (!this.isNative()) {- const gameSettings = await this.getSettings()- shutdownWine(gameSettings)- }+ if ((executable || launchUrl) && !this.isNative()) {+ const gameSettings = await this.getSettings()+ shutdownWine(gameSettings)}}@@ -122,6 +133,7 @@ export default class SideloadGame implements Game {removePrefix(this.id, 'sideload')}libraryStore.set('games', current)+ sendFrontendMessage('refreshLibrary', 'sideload')if (deleteFiles && executable !== undefined) {rmSync(dirname(executable), { recursive: true })diff --git a/src/backend/storeManagers/sideload/library.ts b/src/backend/storeManagers/sideload/library.tsindex c97c375c1..492a495b5 100644--- a/src/backend/storeManagers/sideload/library.ts+++ b/src/backend/storeManagers/sideload/library.ts@@ -2,7 +2,7 @@ import { ExecResult, GameInfo } from 'common/types'import { readFileSync, readdirSync } from 'graceful-fs'import { dirname, join } from 'path'import { libraryStore } from './electronStores'-import { logWarning } from 'backend/logger'+import { logWarning, LogPrefix } from 'backend/logger'import { addShortcuts } from 'backend/shortcuts/shortcuts/shortcuts'import { sendFrontendMessage } from 'backend/ipc'import { isMac } from 'backend/constants/environment'@@ -21,14 +21,20 @@ export default class SideloadLibraryManager implements LibraryManager {addNewApp({app_name,title,- install: { executable, platform },+ install: { executable, platform, install_path },art_cover,art_square,browserUrl,is_installed = true,+ canRunOffline: providedCanRunOffline,description,customUserAgent,- launchFullScreen+ launchFullScreen,+ presetId,+ sourcePresetId,+ storeGameId,+ launchUrl,+ folder_name: providedFolderName}: GameInfo): void {const game: GameInfo = {runner: 'sideload',@@ -37,17 +43,24 @@ export default class SideloadLibraryManager implements LibraryManager {install: {executable,platform,- is_dlc: false+ is_dlc: false,+ install_path},- folder_name: executable !== undefined ? dirname(executable) : undefined,+ folder_name:+ providedFolderName ??+ (executable !== undefined ? dirname(executable) : undefined),art_cover,is_installed: is_installed !== undefined ? is_installed : true,art_square,- canRunOffline: !browserUrl,+ canRunOffline: providedCanRunOffline ?? !browserUrl,browserUrl,description,customUserAgent,- launchFullScreen+ launchFullScreen,+ ...(presetId ? { presetId } : {}),+ ...(sourcePresetId ? { sourcePresetId } : {}),+ ...(storeGameId ? { storeGameId } : {}),+ ...(launchUrl ? { launchUrl } : {})}if (isMac && executable?.endsWith('.app')) {@@ -71,11 +84,18 @@ export default class SideloadLibraryManager implements LibraryManager {current[gameIndex] = { ...current[gameIndex], ...game }} else {current.push(game)- addShortcuts(new SideloadGame(app_name))}+ // Persist before creating shortcuts: addShortcuts reads the game info back+ // from the store, so it has to exist first.libraryStore.set('games', current)+ if (gameIndex === -1) {+ void addShortcuts(new SideloadGame(app_name)).catch((error) => {+ logWarning(['Failed to add shortcuts:', error], LogPrefix.Sideload)+ })+ }+sendFrontendMessage('refreshLibrary', 'sideload')returndiff --git a/src/backend/storeManagers/sideload/preset_paths.ts b/src/backend/storeManagers/sideload/preset_paths.tsnew file mode 100644index 000000000..09a530ffa--- /dev/null+++ b/src/backend/storeManagers/sideload/preset_paths.ts@@ -0,0 +1,114 @@+import { join } from 'path'++import type {+ SideloadPreset,+ SideloadPresetLauncher+} from 'common/sideload_presets'++type LauncherPreset = SideloadPreset & { launcher: SideloadPresetLauncher }++interface CandidatePathsOptions {+ isWindows: boolean+ winePrefix?: string+ programFiles?: string+ programFilesX86?: string+}++function resolveWindowsRelativePath(+ relativePath: string,+ programFiles?: string,+ programFilesX86?: string+): string | undefined {+ const normalized = relativePath.replaceAll('\\', '/')+ const match = /^(Program Files \(x86\)|Program Files)\/(.+)$/.exec(normalized)+ if (!match) {+ return undefined+ }+ const base =+ match[1] === 'Program Files (x86)'+ ? (programFilesX86 ?? 'C:\\Program Files (x86)')+ : (programFiles ?? 'C:\\Program Files')+ return join(base, match[2].replaceAll('/', '\\'))+}++/**+ * Where the executable of a launcher preset may live.+ *+ * On Windows the candidates are resolved against the Program Files folders; in+ * a Wine prefix they are relative to the prefix' `drive_c` (and to `pfx/drive_c`+ * for Proton prefixes). Returns an empty list for web presets.+ */+export function getPresetCandidatePaths(+ preset: SideloadPreset,+ {+ isWindows,+ winePrefix,+ programFiles,+ programFilesX86+ }: CandidatePathsOptions+): string[] {+ if (!preset.launcher) {+ return []+ }++ const candidates = (preset as LauncherPreset).launcher.exeCandidates++ if (isWindows) {+ return candidates.flatMap((candidate) => {+ const resolved = resolveWindowsRelativePath(+ candidate,+ programFiles,+ programFilesX86+ )+ return resolved ? [resolved] : []+ })+ }++ if (!winePrefix) {+ return []+ }++ return [+ join(winePrefix, 'pfx', 'drive_c'),+ join(winePrefix, 'drive_c')+ ].flatMap((root) =>+ candidates.map((candidate) => join(root, candidate.replaceAll('\\', '/')))+ )+}++/**+ * Roots where versioned install folders may live (for example the EA app,+ * which installs into `EA Desktop/<version>/EA Desktop`).+ */+export function getPresetSearchRoots(+ preset: SideloadPreset,+ {+ isWindows,+ winePrefix,+ programFiles,+ programFilesX86+ }: CandidatePathsOptions+): string[] {+ const root = preset.launcher?.exeSearch?.root+ if (!root) {+ return []+ }++ if (isWindows) {+ const resolved = resolveWindowsRelativePath(+ root,+ programFiles,+ programFilesX86+ )+ return resolved ? [resolved] : []+ }++ if (!winePrefix) {+ return []+ }++ return [+ join(winePrefix, 'pfx', 'drive_c', root.replaceAll('\\', '/')),+ join(winePrefix, 'drive_c', root.replaceAll('\\', '/'))+ ]+}diff --git a/src/backend/storeManagers/sideload/presets.ts b/src/backend/storeManagers/sideload/presets.tsnew file mode 100644index 000000000..472c4d2c8--- /dev/null+++ b/src/backend/storeManagers/sideload/presets.ts@@ -0,0 +1,424 @@+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ renameSync,+ rmSync,+ statSync+} from 'graceful-fs'+import { dirname, extname, join } from 'path'+import { pathToFileURL } from 'url'++import {+ SIDELOAD_PRESETS,+ getPresetInstallerArgs,+ getSideloadPreset,+ getSideloadPresetAppName,+ type SideloadPreset,+ type SideloadPresetArtwork,+ type SideloadPresetLauncher+} from 'common/sideload_presets'+import { GameConfig } from 'backend/game_config'+import { runWineCommand } from 'backend/launcher'+import {+ createGameLogWriter,+ logInfo,+ logWarning,+ LogPrefix+} from 'backend/logger'+import { sendFrontendMessage } from 'backend/ipc'+import { downloadFile, spawnAsync } from 'backend/utils'+import { isWindows } from 'backend/constants/environment'+import { getPresetCandidatePaths, getPresetSearchRoots } from './preset_paths'+import {+ gamesConfigPath,+ publicDir,+ toolsPath,+ userDataPath+} from 'backend/constants/paths'++import { libraryStore } from './electronStores'++import type { GameSettings } from 'common/types'++const presetRedistFolder = join(toolsPath, 'redist', 'presets')+const presetArtworkFolder = join(userDataPath, 'sideload_presets', 'art')++// Vendor installers change over time. Re-download after a month so that a very+// old cached installer does not break the preset.+const installerCacheMaxAge = 30 * 24 * 60 * 60 * 1000++function getPreset(presetId: string): SideloadPreset {+ const preset = getSideloadPreset(presetId)+ if (!preset) {+ throw new Error(`Unknown SideLoad preset: ${presetId}`)+ }+ return preset+}++function getLauncherPreset(presetId: string): SideloadPreset & {+ launcher: SideloadPresetLauncher+} {+ const preset = getPreset(presetId)+ if (!preset.launcher) {+ throw new Error(`SideLoad preset "${presetId}" is not a launcher preset`)+ }+ return preset as SideloadPreset & { launcher: SideloadPresetLauncher }+}++interface SideloadPresetStatus {+ installed: boolean+ prefixExists: boolean+ prefix?: string+}++/**+ * Reads the prefix stored in the preset's own config file without creating a+ * config or falling back to the shared default prefix. GameConfig.get() starts+ * an asynchronous load, so reading `config` immediately could report the+ * shared prefix as if it belonged to the preset.+ */+function getConfiguredPresetPrefix(appName: string): string | undefined {+ const configPath = join(gamesConfigPath, `${appName}.json`)+ if (!existsSync(configPath)) {+ return undefined+ }++ try {+ return getPresetWinePrefix(+ JSON.parse(readFileSync(configPath, 'utf-8')),+ appName+ )+ } catch {+ return undefined+ }+}++export function getPresetWinePrefix(+ config: unknown,+ appName: string+): string | undefined {+ if (!config || typeof config !== 'object') {+ return undefined+ }++ const gameConfig = (config as Record<string, unknown>)[appName]+ if (!gameConfig || typeof gameConfig !== 'object') {+ return undefined+ }++ const prefix = (gameConfig as Record<string, unknown>).winePrefix+ return typeof prefix === 'string' ? prefix : undefined+}++/**+ * Whether a preset is already in the library and whether its prefix still+ * exists on disk. Used by the preset picker to show the "Installed" badge and+ * warn before reusing a prefix.+ */+export function getPresetStatuses(): Record<string, SideloadPresetStatus> {+ const games = libraryStore.get('games', [])+ const statuses: Record<string, SideloadPresetStatus> = {}++ for (const preset of SIDELOAD_PRESETS) {+ const appName = getSideloadPresetAppName(preset)+ const installed = games.some(+ (game) => game.presetId === preset.id || game.app_name === appName+ )+ const prefix = getConfiguredPresetPrefix(appName)+ const prefixExists = Boolean(+ prefix && prefix !== '...' && existsSync(prefix)+ )++ statuses[preset.id] = {+ installed,+ prefixExists,+ prefix: prefixExists ? prefix : undefined+ }+ }++ return statuses+}++function getPresetInstallerPath(preset: SideloadPreset): string {+ return join(+ presetRedistFolder,+ preset.id,+ preset.launcher?.installer.fileName ?? 'installer.exe'+ )+}++/**+ * Downloads the official installer for a launcher preset, if it is not cached+ * yet. The download goes straight from the vendor's endpoint to Heroic's tools+ * folder so that nothing third-party is bundled with the app.+ */+export async function downloadPresetInstaller(+ presetId: string+): Promise<{ installerPath: string }> {+ const preset = getLauncherPreset(presetId)+ const installerPath = getPresetInstallerPath(preset)++ if (existsSync(installerPath)) {+ const installerStat = statSync(installerPath)+ const isFresh =+ installerStat.size > 0 &&+ Date.now() - installerStat.mtimeMs < installerCacheMaxAge+ if (isFresh) {+ return { installerPath }+ }+ }++ mkdirSync(dirname(installerPath), { recursive: true })+ logInfo(+ `Downloading ${preset.title} installer from ${preset.launcher.installer.url}`,+ LogPrefix.DownloadManager+ )++ // Download to a temporary file first so that an interrupted download never+ // leaves a partially written installer in the cache.+ const downloadPath = `${installerPath}.partial`+ rmSync(downloadPath, { force: true })++ try {+ await downloadFile({+ url: preset.launcher.installer.url,+ dest: downloadPath,+ progressCallback: (_downloadedBytes, _speed, progress) => {+ sendFrontendMessage('presetDownloadProgress', {+ presetId: preset.id,+ progress: Math.max(0, Math.min(100, progress))+ })+ }+ })++ if (!existsSync(downloadPath) || statSync(downloadPath).size === 0) {+ throw new Error(`Installer download failed for ${preset.title}`)+ }++ rmSync(installerPath, { force: true })+ renameSync(downloadPath, installerPath)+ } catch (error) {+ rmSync(downloadPath, { force: true })+ throw error+ }++ return { installerPath }+}++async function getPresetGameSettings(+ preset: SideloadPreset+): Promise<GameSettings> {+ const appName = getSideloadPresetAppName(preset)+ const gameConfig = GameConfig.get(appName)+ return gameConfig.config ?? (await gameConfig.getSettings())+}++/**+ * Runs the cached installer: natively on Windows, through Wine/Proton+ * everywhere else. Installers run silently when the vendor documents the+ * flags; otherwise the regular interactive installer is used.+ */+export async function runPresetInstaller(+ presetId: string,+ silent = true+): Promise<{+ status: 'done' | 'error'+ error?: string+}> {+ const preset = getLauncherPreset(presetId)+ const installerPath = getPresetInstallerPath(preset)+ if (!existsSync(installerPath)) {+ return { status: 'error', error: 'installer-missing' }+ }++ const appName = getSideloadPresetAppName(preset)+ const { silentArgs, env = {} } = preset.launcher.installer+ const canInstallSilently = Boolean(silentArgs?.length)+ const args = getPresetInstallerArgs(preset, silent && canInstallSilently)+ const installerEnv = { ...process.env, ...env }+ const logWriter = await createGameLogWriter(appName, 'sideload', 'install')++ try {+ if (isWindows) {+ const result = await spawnAsync(+ installerPath,+ args,+ { env: installerEnv },+ (data) => logWriter.writeString(data)+ )+ // A null code means the installer was killed by a signal, which is a+ // failure too, so both branches treat anything but 0 the same way.+ if (result.code !== 0) {+ return {+ status: 'error',+ error: `installer-exit-${result.code ?? 'unknown'}`+ }+ }+ return { status: 'done' }+ }++ const gameSettings = await getPresetGameSettings(preset)+ if (!gameSettings?.wineVersion?.bin) {+ return { status: 'error', error: 'wine-not-configured' }+ }++ const result = await runWineCommand({+ gameSettings,+ commandParts: [installerPath, ...args],+ wait: true,+ protonVerb: 'run',+ options: { logWriters: [logWriter], env }+ })++ if (result.code !== 0) {+ return {+ status: 'error',+ error: `installer-exit-${result.code ?? 'unknown'}`+ }+ }++ return { status: 'done' }+ } catch (error) {+ logWarning(+ `Failed to run ${preset.title} installer: ${String(error)}`,+ LogPrefix.Sideload+ )+ return { status: 'error', error: `${String(error)}` }+ }+}++function findExecutableInSearchRoots(+ preset: SideloadPreset,+ winePrefix: string | undefined+): string | null {+ const search = preset.launcher?.exeSearch+ if (!search) {+ return null+ }++ const roots = getPresetSearchRoots(preset, {+ isWindows,+ winePrefix,+ programFiles: process.env.ProgramFiles,+ programFilesX86: process.env['ProgramFiles(x86)']+ })++ for (const root of roots) {+ if (!existsSync(root)) {+ continue+ }++ const dirs = [root]+ try {+ for (const entry of readdirSync(root, { withFileTypes: true })) {+ if (entry.isDirectory()) {+ dirs.push(join(root, entry.name))+ }+ }+ } catch {+ // Root may be temporarily unreadable while the installer is writing.+ }++ for (const dir of dirs) {+ for (const name of search.names) {+ for (const candidate of [+ join(dir, name),+ join(dir, 'EA Desktop', name)+ ]) {+ if (existsSync(candidate)) {+ return candidate+ }+ }+ }+ }+ }++ return null+}++/**+ * Looks for the executable that the installer should have created. The+ * installer may still be finishing in the background, so retry a few times+ * before giving up.+ */+export async function detectPresetExecutable(+ presetId: string,+ attempts = 12,+ intervalMs = 500+): Promise<string | null> {+ const preset = getLauncherPreset(presetId)+ const gameSettings = await getPresetGameSettings(preset).catch(() => null)+ const candidates = getPresetCandidatePaths(preset, {+ isWindows,+ winePrefix: gameSettings?.winePrefix,+ programFiles: process.env.ProgramFiles,+ programFilesX86: process.env['ProgramFiles(x86)']+ })++ for (let attempt = 0; attempt < attempts; attempt++) {+ const searched = findExecutableInSearchRoots(+ preset,+ gameSettings?.winePrefix+ )+ if (searched) {+ logInfo(+ `Detected ${preset.title} executable at ${searched}`,+ LogPrefix.Sideload+ )+ return searched+ }++ for (const candidate of candidates) {+ if (existsSync(candidate)) {+ logInfo(+ `Detected ${preset.title} executable at ${candidate}`,+ LogPrefix.Sideload+ )+ return candidate+ }+ }+ if (attempt < attempts - 1) {+ await new Promise((resolve) => setTimeout(resolve, intervalMs))+ }+ }++ return null+}++/**+ * Copies the bundled preset artwork into the user data folder once and+ * returns `file://` URLs, which stay valid across Heroic updates.+ */+export function getPresetArtwork(presetId: string): SideloadPresetArtwork {+ const preset = getPreset(presetId)+ const artwork: SideloadPresetArtwork = { square: '', hero: '' }++ mkdirSync(presetArtworkFolder, { recursive: true })++ for (const kind of ['square', 'hero'] as const) {+ const fileName = preset.artwork[kind]+ const source = join(publicDir, 'presets', fileName)+ const destination = join(+ presetArtworkFolder,+ `${preset.id}-${kind}${extname(fileName)}`+ )++ if (!existsSync(destination)) {+ if (!existsSync(source)) {+ logWarning(+ `Missing bundled artwork for preset ${preset.id}: ${source}`,+ LogPrefix.Backend+ )+ continue+ }+ copyFileSync(source, destination)+ }++ artwork[kind] = pathToFileURL(destination).toString()+ }++ return artwork+}diff --git a/src/backend/storeManagers/sideload/scan.ts b/src/backend/storeManagers/sideload/scan.tsnew file mode 100644index 000000000..9784ff045--- /dev/null+++ b/src/backend/storeManagers/sideload/scan.ts@@ -0,0 +1,680 @@+import { readFile, readdir, realpath, stat } from 'node:fs/promises'+import { existsSync } from 'graceful-fs'+import { basename, join } from 'path'+import axios from 'axios'++import {+ getSideloadPreset,+ getSideloadPresetAppName,+ type MissingSideloadGame,+ type ScannedSideloadGame,+ type SideloadPreset+} from 'common/sideload_presets'+import { GameConfig } from 'backend/game_config'+import { isWindows } from 'backend/constants/environment'+import { writeConfig } from 'backend/utils'+import { logInfo, logWarning, LogPrefix } from 'backend/logger'++import { libraryStore } from './electronStores'+import { getPresetArtwork } from './presets'+import { libraryManagerMap } from '..'++import type { GameInfo } from 'common/types'++interface SideloadScanResult {+ games: ScannedSideloadGame[]+ missing: MissingSideloadGame[]+ prefix?: string+ error?: string+}++interface RegistrySection {+ name: string+ values: Record<string, string>+}++const executableExcludePattern =+ /(unins|uninstall|setup|installer|helper|cleanup|touchup|crash|report|update|patch|launcher|dxsetup|redist|vc_|eula|readme|autorun|touchup)/i++export function decodeRegistryString(value: string): string {+ let decoded = ''++ for (let index = 0; index < value.length; index++) {+ const character = value[index]+ if (character !== '\\') {+ decoded += character+ continue+ }++ const next = value[index + 1]+ if (next === undefined) {+ decoded += '\\'+ continue+ }++ switch (next) {+ case 'n':+ decoded += '\n'+ index+++ break+ case 'r':+ decoded += '\r'+ index+++ break+ case 't':+ decoded += '\t'+ index+++ break+ case '"':+ decoded += '"'+ index+++ break+ case '\\':+ decoded += '\\'+ index+++ break+ case 'x': {+ const hex = /^[0-9a-fA-F]{1,4}/.exec(value.slice(index + 2))?.[0]+ if (hex) {+ decoded += String.fromCharCode(parseInt(hex, 16))+ index += 1 + hex.length+ } else {+ decoded += '\\'+ }+ break+ }+ default:+ // Unknown escapes keep the backslash and the following character.+ decoded += character+ }+ }++ return decoded+}++/**+ * Minimal parser for Wine's .reg files. We only need section names and string+ * values; hex/dword values are intentionally ignored.+ */+export function parseWineRegistry(text: string): RegistrySection[] {+ const sections: RegistrySection[] = []+ let current: RegistrySection | undefined++ for (const line of text.split(/\r?\n/)) {+ const sectionMatch = /^\[(.+)\](?:\s+\d+)?$/.exec(line.trim())+ if (sectionMatch) {+ current = {+ name: sectionMatch[1].replace(/\\\\/g, '\\'),+ values: {}+ }+ sections.push(current)+ continue+ }++ if (!current || !line.startsWith('"')) {+ if (current && line.startsWith('@=')) {+ const raw = line.slice(2).trim()+ if (raw.startsWith('"') && raw.endsWith('"')) {+ current.values['@'] = decodeRegistryString(raw.slice(1, -1))+ }+ }+ continue+ }++ const valueMatch = /^"((?:\\.|[^"\\])+)"=(.+)$/.exec(line)+ if (!valueMatch) {+ continue+ }++ let rawValue = valueMatch[2].trim()+ if (rawValue.startsWith('"') && rawValue.endsWith('"')) {+ rawValue = rawValue.slice(1, -1)+ current.values[decodeRegistryString(valueMatch[1])] =+ decodeRegistryString(rawValue)+ }+ }++ return sections+}++async function readRegistrySections(+ prefixRoot: string+): Promise<RegistrySection[]> {+ const sections = new Map<string, RegistrySection>()++ for (const file of ['system.reg', 'user.reg']) {+ const filePath = join(prefixRoot, file)+ if (!existsSync(filePath)) {+ continue+ }+ try {+ const parsed = parseWineRegistry(await readFile(filePath, 'utf-8'))+ for (const section of parsed) {+ const existing = sections.get(section.name)+ if (existing) {+ Object.assign(existing.values, section.values)+ } else {+ sections.set(section.name, section)+ }+ }+ } catch (error) {+ logWarning(+ `Failed to read ${filePath}: ${String(error)}`,+ LogPrefix.Sideload+ )+ }+ }++ return [...sections.values()]+}++function getRegistryRoot(prefix: string): string | undefined {+ if (existsSync(join(prefix, 'system.reg'))) {+ return prefix+ }+ const protonRoot = join(prefix, 'pfx')+ if (existsSync(join(protonRoot, 'system.reg'))) {+ return protonRoot+ }+ return undefined+}++function registryPathToLocal(+ prefixRoot: string,+ windowsPath: string | undefined+): string | undefined {+ if (!windowsPath) {+ return undefined+ }+ const normalized = windowsPath.replaceAll('\\', '/')+ const match = /^([a-zA-Z]):\/(.*)$/.exec(normalized)+ if (!match) {+ return undefined+ }+ const parts = match[2].split('/').filter(Boolean)+ const drive = match[1].toLowerCase()++ if (drive === 'c') {+ return join(prefixRoot, 'drive_c', ...parts)+ }++ // Other drives are exposed by Wine as dosdevices/<letter>: symlinks.+ const driveRoot = join(prefixRoot, 'dosdevices', `${drive}:`)+ if (!existsSync(driveRoot)) {+ return undefined+ }+ return join(driveRoot, ...parts)+}++function stripTrademarks(value: string): string {+ return value+ .replace(/[™®]/g, '')+ .replace(/\((tm|r)\)/gi, '')+ .replace(/\s+/g, ' ')+ .trim()+}++async function findExecutableInDirectory(+ directory: string,+ depth = 4+): Promise<string | undefined> {+ let best: { path: string; size: number } | undefined+ const visited = new Set<string>()++ const walk = async (current: string, remaining: number) => {+ let realPath: string+ try {+ realPath = await realpath(current)+ } catch {+ return+ }+ if (visited.has(realPath)) {+ return+ }+ visited.add(realPath)++ let entries+ try {+ entries = await readdir(current, { withFileTypes: true })+ } catch {+ return+ }++ for (const entry of entries) {+ const entryPath = join(current, entry.name)+ let isDirectory = entry.isDirectory()+ if (!isDirectory && entry.isSymbolicLink()) {+ try {+ isDirectory = (await stat(entryPath)).isDirectory()+ } catch {+ isDirectory = false+ }+ }++ if (isDirectory) {+ if (remaining > 0 && entry.name !== '__Installer') {+ await walk(entryPath, remaining - 1)+ }+ continue+ }+ if (+ !/\.exe$/i.test(entry.name) ||+ executableExcludePattern.test(entry.name)+ ) {+ continue+ }+ try {+ const size = (await stat(entryPath)).size+ if (!best || size > best.size) {+ best = { path: entryPath, size }+ }+ } catch {+ // ignore unreadable files+ }+ }+ }++ await walk(directory, depth)+ return best?.path+}++function getDisplayIconExecutable(+ prefixRoot: string,+ displayIcon: string | undefined+): string | undefined {+ if (!displayIcon) {+ return undefined+ }+ const cleanPath = displayIcon+ .replace(/^"|"$/g, '')+ .replace(/,\s*\d+$/, '')+ .trim()+ if (!/\.exe$/i.test(cleanPath)) {+ return undefined+ }+ const localPath = registryPathToLocal(prefixRoot, cleanPath)+ return localPath && existsSync(localPath) ? localPath : undefined+}++function scanUbisoft(+ prefixRoot: string,+ sections: RegistrySection[]+): ScannedSideloadGame[] {+ const games: ScannedSideloadGame[] = []+ const seen = new Set<string>()++ for (const section of sections) {+ const match =+ /^Software\\(?:Wow6432Node\\)?Ubisoft\\Launcher\\Installs\\([^\\]+)$/i.exec(+ section.name+ )+ if (!match) {+ continue+ }++ const gameId = match[1]+ if (seen.has(gameId)) {+ continue+ }++ const installDir = registryPathToLocal(+ prefixRoot,+ section.values['InstallDir']+ )+ if (!installDir || !existsSync(installDir)) {+ continue+ }++ seen.add(gameId)+ const title = basename(installDir.replace(/[\\/]+$/, ''))+ games.push({+ id: gameId,+ source: 'ubisoft',+ title,+ installDir,+ launchUrl: `uplay://launch/${gameId}/0`,+ added: false+ })+ }++ return games+}++async function scanEA(+ prefixRoot: string,+ sections: RegistrySection[]+): Promise<ScannedSideloadGame[]> {+ const games: ScannedSideloadGame[] = []+ const seen = new Set<string>()++ for (const section of sections) {+ const isUninstallSection =+ /^Software\\(?:Wow6432Node\\)?Microsoft\\Windows\\CurrentVersion\\Uninstall\\[^\\]+$/i.test(+ section.name+ )+ if (!isUninstallSection) {+ continue+ }++ const displayName = stripTrademarks(section.values['DisplayName'] ?? '')+ const publisher = section.values['Publisher'] ?? ''+ const installDir = registryPathToLocal(+ prefixRoot,+ section.values['InstallLocation']+ )++ if (+ !displayName ||+ !installDir ||+ !existsSync(installDir) ||+ !/electronic arts/i.test(publisher) ||+ /ea app|origin|visual c|directx|redistributable|touchup|cleanup|error reporter/i.test(+ displayName+ ) ||+ /EA Desktop[\\/]?/i.test(installDir)+ ) {+ continue+ }++ const executable =+ (await findExecutableInDirectory(installDir)) ??+ getDisplayIconExecutable(prefixRoot, section.values['DisplayIcon'])+ if (!executable) {+ continue+ }++ const key = (installDir + '|' + executable).toLowerCase()+ if (seen.has(key)) {+ continue+ }+ seen.add(key)++ games.push({+ id: section.name.split('\\').at(-1) ?? displayName,+ source: 'ea',+ title: displayName,+ installDir,+ executable,+ added: false+ })+ }++ return games+}++async function scanBattleNet(+ prefixRoot: string,+ sections: RegistrySection[]+): Promise<ScannedSideloadGame[]> {+ const games: ScannedSideloadGame[] = []+ const seen = new Set<string>()+ const hasBattlenetProtocol = sections.some((section) =>+ /^Software\\Classes\\battlenet$/i.test(section.name)+ )++ for (const section of sections) {+ const isUninstallSection =+ /^Software\\(?:Wow6432Node\\)?Microsoft\\Windows\\CurrentVersion\\Uninstall\\[^\\]+$/i.test(+ section.name+ )+ if (!isUninstallSection) {+ continue+ }++ const uninstallString = section.values['UninstallString'] ?? ''+ if (!/Blizzard Uninstaller\.exe/i.test(uninstallString)) {+ continue+ }+ const uid = /--uid=([^\s"]+)/i.exec(uninstallString)?.[1]+ if (!uid || uid.toLowerCase() === 'battle.net') {+ continue+ }+ if (seen.has(uid)) {+ continue+ }++ const installDir = registryPathToLocal(+ prefixRoot,+ section.values['InstallLocation']+ )+ if (!installDir || !existsSync(installDir)) {+ continue+ }++ const executable =+ getDisplayIconExecutable(prefixRoot, section.values['DisplayIcon']) ??+ (await findExecutableInDirectory(installDir))+ if (!executable) {+ continue+ }++ seen.add(uid)+ games.push({+ id: uid,+ source: 'battlenet',+ title: stripTrademarks(section.values['DisplayName'] ?? uid),+ installDir,+ executable,+ launchUrl: hasBattlenetProtocol ? `battlenet://${uid}` : undefined,+ added: false+ })+ }++ return games+}++export async function scanGamesForPreset(+ preset: SideloadPreset,+ prefixRoot: string,+ sections: RegistrySection[]+): Promise<ScannedSideloadGame[]> {+ switch (preset.id) {+ case 'ubisoft-connect':+ return scanUbisoft(prefixRoot, sections)+ case 'ea-app':+ return scanEA(prefixRoot, sections)+ case 'battlenet':+ return scanBattleNet(prefixRoot, sections)+ default:+ return []+ }+}++function markAlreadyAdded(+ preset: SideloadPreset,+ games: ScannedSideloadGame[]+): ScannedSideloadGame[] {+ const library = libraryStore.get('games', [])++ return games.map((game) => {+ const added = library.some((entry) => {+ if (entry.sourcePresetId === preset.id && entry.storeGameId === game.id) {+ return true+ }+ if (game.launchUrl && entry.launchUrl === game.launchUrl) {+ return true+ }+ if (+ game.executable &&+ entry.install?.executable &&+ entry.install.executable === game.executable+ ) {+ return true+ }+ return false+ })++ return { ...game, added }+ })+}++function getMissingGames(+ preset: SideloadPreset,+ games: ScannedSideloadGame[]+): MissingSideloadGame[] {+ const detected = new Set(games.map((game) => game.id))++ return libraryStore+ .get('games', [])+ .filter((entry) => {+ if (entry.sourcePresetId !== preset.id || !entry.storeGameId) {+ return false+ }+ if (detected.has(entry.storeGameId)) {+ return false+ }+ // Some stores leave an empty install folder behind after uninstalling.+ // Treat the entry as missing when either its executable or its folder+ // is gone.+ const executableMissing = Boolean(+ entry.install?.executable && !existsSync(entry.install.executable)+ )+ const folderMissing = !entry.folder_name || !existsSync(entry.folder_name)+ return executableMissing || folderMissing+ })+ .map((entry) => ({+ appName: entry.app_name,+ title: entry.title,+ storeGameId: entry.storeGameId+ }))+ .sort((a, b) => a.title.localeCompare(b.title))+}++export async function scanPresetGames(+ presetId: string+): Promise<SideloadScanResult> {+ const preset = getSideloadPreset(presetId)+ if (!preset?.launcher) {+ return { games: [], missing: [], error: 'not-a-launcher-preset' }+ }+ if (isWindows) {+ return { games: [], missing: [], error: 'unsupported-platform' }+ }++ const appName = getSideloadPresetAppName(preset)+ const gameConfig = GameConfig.get(appName)+ const settings = gameConfig.config ?? (await gameConfig.getSettings())+ const prefix = settings?.winePrefix+ if (!prefix || prefix === '...' || !existsSync(prefix)) {+ return { games: [], missing: [], error: 'prefix-not-found' }+ }++ const registryRoot = getRegistryRoot(prefix)+ if (!registryRoot) {+ return { games: [], missing: [], error: 'registry-not-found', prefix }+ }++ const games = markAlreadyAdded(+ preset,+ await scanGamesForPreset(+ preset,+ registryRoot,+ await readRegistrySections(registryRoot)+ )+ ).sort((a, b) => a.title.localeCompare(b.title))++ const missing = getMissingGames(preset, games)++ logInfo(+ `Scanned ${games.length} game(s) in ${preset.title} prefix` ++ (missing.length ? `, ${missing.length} missing` : ''),+ LogPrefix.Sideload+ )+ return { games, missing, prefix }+}++async function getBottlesArtwork(title: string): Promise<string | undefined> {+ try {+ const response = await axios.get(+ `https://steamgrid.usebottles.com/api/search/${encodeURIComponent(title)}`,+ { timeout: 5000 }+ )+ const artwork =+ typeof response.data === 'string' ? response.data.trim() : ''+ return artwork.startsWith('http') ? artwork : undefined+ } catch (error) {+ logWarning(+ `Could not fetch Bottles artwork for "${title}": ${String(error)}`,+ LogPrefix.Sideload+ )+ return undefined+ }+}++function scannedAppName(preset: SideloadPreset, game: ScannedSideloadGame) {+ const suffix = game.id+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 40)+ return `preset-${preset.id}-${suffix}`+}++export async function addScannedGames(+ presetId: string,+ gameIds: string[]+): Promise<{ added: string[]; error?: string }> {+ const preset = getSideloadPreset(presetId)+ if (!preset?.launcher) {+ return { added: [], error: 'not-a-launcher-preset' }+ }++ const scan = await scanPresetGames(presetId)+ if (scan.error) {+ return { added: [], error: scan.error }+ }++ const selected = scan.games.filter(+ (game) => !game.added && gameIds.includes(game.id)+ )+ if (!selected.length) {+ return { added: [] }+ }++ const launcherAppName = getSideloadPresetAppName(preset)+ const launcherSettings = await GameConfig.get(launcherAppName).getSettings()+ const artwork = getPresetArtwork(presetId)+ const scannedArtwork = await Promise.all(+ selected.map((game) => getBottlesArtwork(game.title))+ )+ const added: string[] = []++ for (const [index, game] of selected.entries()) {+ const gameArtwork = scannedArtwork[index] ?? artwork.square+ const appName = scannedAppName(preset, game)+ const gameInfo: GameInfo = {+ runner: 'sideload',+ app_name: appName,+ title: game.title,+ install: {+ executable: game.executable,+ platform: 'Windows',+ is_dlc: false+ },+ folder_name: game.installDir,+ art_cover: scannedArtwork[index] ?? artwork.hero,+ art_square: gameArtwork,+ is_installed: true,+ canRunOffline: false,+ launchUrl: game.launchUrl,+ sourcePresetId: preset.id,+ storeGameId: game.id+ }++ libraryManagerMap['sideload'].addNewApp(gameInfo)++ await writeConfig(appName, {+ winePrefix: launcherSettings.winePrefix,+ wineVersion: launcherSettings.wineVersion,+ wineCrossoverBottle: launcherSettings.wineCrossoverBottle+ })++ added.push(appName)+ }++ logInfo(+ `Added ${added.length} scanned ${preset.title} game(s)`,+ LogPrefix.Sideload+ )+ return { added }+}diff --git a/src/backend/storeManagers/storeManagerCommon/games.ts b/src/backend/storeManagers/storeManagerCommon/games.tsindex 380f6d63c..49b7de893 100644--- a/src/backend/storeManagers/storeManagerCommon/games.ts+++ b/src/backend/storeManagers/storeManagerCommon/games.ts@@ -1,4 +1,9 @@import { GameSettings } from 'common/types'+import {+ getSideloadPreset,+ getSideloadPresetLaunchArgs,+ getSideloadPresetLaunchEnv+} from 'common/sideload_presets'import { GameConfig } from '../../game_config'import { logInfo, LogPrefix, logWarning } from 'backend/logger'import { basename, dirname } from 'path'@@ -22,9 +27,9 @@ import {createAbortController,deleteAbortController} from '../../utils/aborthandler/aborthandler'-import { BrowserWindow, dialog, Menu } from 'electron'+import { BrowserWindow, dialog, Menu, shell } from 'electron'import { sendGameStatusUpdate } from 'backend/utils'-import { isLinux, isMac } from 'backend/constants/environment'+import { isLinux, isMac, isWindows } from 'backend/constants/environment'import { windowIcon } from 'backend/constants/paths'import type LogWriter from 'backend/logger/log_writer'@@ -58,10 +63,49 @@ const openNewBrowserGameWindow = async ({fullscreen: launchFullScreen ?? false,autoHideMenuBar: true,webPreferences: {- partition: `persist:${hostname}`+ partition: `persist:${hostname}`,+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ spellcheck: false+ }+ })++ // Remote web apps should never be able to open arbitrary native windows or+ // request sensitive permissions. Login popups are kept inside Electron so+ // that the session (and therefore the login) is shared with the app.+ browserGame.webContents.setWindowOpenHandler(({ url }) => {+ if (!/^https?:\/\//i.test(url)) {+ return { action: 'deny' }+ }+ return {+ action: 'allow',+ overrideBrowserWindowOptions: {+ autoHideMenuBar: true,+ webPreferences: {+ partition: `persist:${hostname}`,+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true+ }+ }}})+ const allowedPermissions = new Set([+ 'fullscreen',+ 'pointerLock',+ 'clipboard-sanitized-write'+ ])+ browserGame.webContents.session.setPermissionRequestHandler(+ (_contents, permission, callback) => {+ callback(allowedPermissions.has(permission))+ }+ )+ browserGame.webContents.session.setPermissionCheckHandler(+ (_contents, permission) => allowedPermissions.has(permission)+ )+browserGame.setMenu(Menu.buildFromTemplate([{ role: 'close' },@@ -126,7 +170,7 @@ export async function launchGame(install: { executable }} = gameInfo- const { browserUrl, customUserAgent, launchFullScreen } = gameInfo+ const { browserUrl, customUserAgent, launchFullScreen, launchUrl } = gameInfoconst gameSettingsOverrides = await GameConfig.get(appName).getSettings()if (@@ -137,17 +181,67 @@ export async function launchGame(}if (browserUrl) {- return openNewBrowserGameWindow({- browserUrl,- abortId: appName,- customUserAgent,- launchFullScreen+ sendGameStatusUpdate({+ appName,+ runner: gameInfo.runner,+ status: 'playing'})++ try {+ return await openNewBrowserGameWindow({+ browserUrl,+ abortId: appName,+ customUserAgent,+ launchFullScreen+ })+ } finally {+ sendGameStatusUpdate({+ appName,+ runner: gameInfo.runner,+ status: 'done'+ })+ }}+ // Scanned store games can be launched through the store client via its URL+ // protocol, but an executable (including one chosen while editing the game)+ // takes precedence so edits are respected.+ if (launchUrl && !executable) {+ logInfo(+ `launching ${appName} through protocol: ${launchUrl}`,+ LogPrefix.Backend+ )+ if (isWindows) {+ await shell.openExternal(launchUrl)+ return true+ }++ const gameSettings = await getAppSettings(appName)+ await runWineCommand({+ gameSettings,+ commandParts: ['start', launchUrl],+ wait: false,+ protonVerb: 'run'+ })+ return true+ }++ const preset =+ runner === 'sideload' && gameInfo.presetId+ ? getSideloadPreset(gameInfo.presetId)+ : undefined+ const presetLaunchArgs = preset+ ? getSideloadPresetLaunchArgs(preset, process.platform)+ : []+ const presetLaunchEnv = preset ? getSideloadPresetLaunchEnv(preset) : {}+const gameSettings = await getAppSettings(appName)const { launcherArgs } = gameSettings- const extraArgs = [...shlex.split(launcherArgs ?? ''), ...args]+ const extraArgs = [+ ...shlex.split(launcherArgs ?? ''),+ ...presetLaunchArgs,+ ...args+ ]const extraArgsJoined = extraArgs.join(' ')if (executable) {@@ -260,9 +354,9 @@ export async function launchGame(protonVerb: 'waitforexitandrun',startFolder: dirname(executable),options: {- env,wrappers,logWriters: [logWriter],+ env: { ...env, ...presetLaunchEnv },logMessagePrefix: LogPrefix.Backend}})diff --git a/src/backend/tools/index.ts b/src/backend/tools/index.tsindex f98cd8dd1..590576863 100644--- a/src/backend/tools/index.ts+++ b/src/backend/tools/index.ts@@ -621,7 +621,8 @@ export const Winetricks = {...setupWineEnvVars(settingsWithWineVersion, appName),WINEPREFIX: winePrefix,PATH: `${winepath}:${process.env.PATH}`,- GAMEID: gui ? 'winetricks-gui' : 'umu-0',+ GAMEID:+ gameSettings.umuGameId?.trim() || (gui ? 'winetricks-gui' : 'umu-0'),UMU_RUNTIME_UPDATE: '0'}diff --git a/src/common/sideload_presets.ts b/src/common/sideload_presets.tsnew file mode 100644index 000000000..eb56ad46d--- /dev/null+++ b/src/common/sideload_presets.ts@@ -0,0 +1,342 @@+import type { TFunction } from 'i18next'++import type { InstallPlatform, WineInstallation } from './types'++/**+ * Presets for the "Add Game" dialog.+ *+ * A preset is only metadata: the artwork that ships with Heroic, the official+ * vendor installer URL and a list of places where the installed executable is+ * usually found. Presets never bundle third-party installers, everything is+ * downloaded from the vendor's own HTTPS endpoint at the user's request.+ */+type SideloadPresetKind = 'web' | 'launcher'++export type SideloadPresetPlatform = 'linux' | 'win32' | 'darwin'++interface SideloadPresetInstaller {+ url: string+ fileName: string+ /** Arguments for the regular, interactive installer. */+ args?: string[]+ /**+ * Arguments for a silent/unattended install, when the vendor supports it.+ * The UI offers a toggle and falls back to the interactive install.+ */+ silentArgs?: string[]+ /** Environment variables applied only while the installer runs. */+ env?: Record<string, string>+}++interface SideloadPresetWebApp {+ url: string+ userAgent?: string+ launchFullScreen?: boolean+}++export interface SideloadPresetLauncher {+ installer: SideloadPresetInstaller+ /**+ * Environment variables applied on every launch, for example Wine quirks+ * the launcher needs to render its own window.+ */+ launchEnv?: Record<string, string>+ /**+ * Extra arguments passed to the launcher when starting it, per host+ * platform. Used for the Chromium switches some launchers need under Wine.+ */+ launchArgs?: Partial<Record<SideloadPresetPlatform, string[]>>+ /**+ * Wine flavour the launcher is known to install and run with, per host+ * platform. Only used as the default pick; the user can choose another one.+ */+ preferredWineType?: Partial<+ Record<SideloadPresetPlatform, WineInstallation['type']>+ >+ /**+ * Executable paths relative to the Windows drive root (`drive_c` in a Wine+ * prefix), ordered by likelihood. The first existing file wins.+ */+ exeCandidates: string[]+ /**+ * Some installers use versioned folders (the EA app does). The launcher can+ * look for these names directly below the root and one folder deeper.+ */+ exeSearch?: {+ root: string+ names: string[]+ }+}++type SideloadScanSource = 'ubisoft' | 'ea' | 'battlenet'++export interface MissingSideloadGame {+ appName: string+ title: string+ storeGameId?: string+}++export interface ScannedSideloadGame {+ /** Stable id used to deduplicate and re-add scanned games. */+ id: string+ source: SideloadScanSource+ title: string+ installDir?: string+ executable?: string+ /** Protocol URL used to launch through the store client. */+ launchUrl?: string+ /** Already present in the Heroic library (scanned from this preset). */+ added: boolean+}++export interface SideloadPresetArtwork {+ square: string+ hero: string+}++export interface SideloadPreset {+ id: string+ kind: SideloadPresetKind+ title: string+ /**+ * Platforms where the vendor installer opens the app itself at the end. On+ * macOS that window can render blank because the installer does not apply+ * Heroic's graphics settings, so the install step warns about it.+ */+ installerOpensApp?: SideloadPresetPlatform[]+ /**+ * Platforms where this launcher only works with the commercial CrossOver+ * build. Free Wine builds may install it but cannot display its window.+ */+ requiresCrossover?: SideloadPresetPlatform[]+ platforms: SideloadPresetPlatform[]+ artwork: SideloadPresetArtwork+ web?: SideloadPresetWebApp+ launcher?: SideloadPresetLauncher+}++const ALL_DESKTOP_PLATFORMS: SideloadPresetPlatform[] = [+ 'linux',+ 'win32',+ 'darwin'+]++const CHROME_USER_AGENT =+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36'++/**+ * Order matters: it is the order the preset picker renders.+ */+export const SIDELOAD_PRESETS: SideloadPreset[] = [+ {+ id: 'battlenet',+ kind: 'launcher',+ title: 'Battle.net',+ installerOpensApp: ['darwin'],+ platforms: ALL_DESKTOP_PLATFORMS,+ artwork: {+ square: 'battlenet-square.jpg',+ hero: 'battlenet-hero.jpg'+ },+ launcher: {+ installer: {+ // Use the direct downloader endpoint: the account/download page URL+ // redirects and returns 403 to the downloader used by Heroic.+ url: 'https://downloader.battle.net/download/getInstaller?os=win&installer=Battle.net-Setup.exe',+ fileName: 'Battle.net-Setup.exe',+ // Keep Battle.net's install location predictable and avoid the+ // installer creating a second prefix entry.+ args: [+ '--installpath=C:\\Program Files (x86)\\Battle.net',+ '--lang=enUS'+ ],+ env: {+ PROTON_ENABLE_WAYLAND: '0',+ WINE_SIMULATE_WRITECOPY: '1'+ }+ },+ // Apple's Game Porting Toolkit ships an old Wine that fails while+ // downloading the Battle.net Agent, so default to Wine Staging there.+ preferredWineType: {+ darwin: 'wine'+ },+ launchEnv: {+ WINE_SIMULATE_WRITECOPY: '1'+ },+ // On macOS the CEF login window stays blank when it renders through the+ // D3D GPU process; these switches keep it on the CPU renderer.+ launchArgs: {+ darwin: [+ '--from-launcher',+ '--disable-gpu-compositing',+ '--in-process-gpu',+ '--use-gl=swiftshader'+ ]+ },+ exeCandidates: [+ 'Program Files (x86)/Battle.net/Battle.net.exe',+ 'Program Files (x86)/Battle.net/Battle.net Launcher.exe',+ 'Program Files/Battle.net/Battle.net.exe',+ 'Program Files/Battle.net/Battle.net Launcher.exe'+ ]+ }+ },+ {+ id: 'ea-app',+ kind: 'launcher',+ title: 'EA app',+ platforms: ALL_DESKTOP_PLATFORMS,+ artwork: {+ square: 'ea-square.jpg',+ hero: 'ea-hero.jpg'+ },+ launcher: {+ installer: {+ url: 'https://origin-a.akamaihd.net/EA-Desktop-Client-Download/installer-releases/EAappInstaller.exe',+ fileName: 'EAappInstaller.exe',+ // Same flags used for the EA app that ships with Epic-managed games.+ args: ['EAX_LAUNCH_CLIENT=0', 'IGNORE_INSTALLED=1'],+ env: {+ PROTON_ENABLE_WAYLAND: '0'+ }+ },+ exeCandidates: [+ 'Program Files/Electronic Arts/EA Desktop/EA Desktop/EALauncher.exe',+ 'Program Files/Electronic Arts/EA Desktop/EA Desktop/EADesktop.exe',+ 'Program Files (x86)/Electronic Arts/EA Desktop/EA Desktop/EALauncher.exe'+ ],+ exeSearch: {+ root: 'Program Files/Electronic Arts/EA Desktop',+ names: ['EALauncher.exe', 'EADesktop.exe']+ }+ }+ },+ {+ id: 'ubisoft-connect',+ kind: 'launcher',+ title: 'Ubisoft Connect',+ requiresCrossover: ['darwin'],+ platforms: ALL_DESKTOP_PLATFORMS,+ artwork: {+ square: 'ubisoft-square.jpg',+ hero: 'ubisoft-hero.jpg'+ },+ launcher: {+ installer: {+ url: 'https://static3.cdn.ubi.com/orbit/launcher_installer/UbisoftConnectInstaller.exe',+ fileName: 'UbisoftConnectInstaller.exe',+ silentArgs: ['/S'],+ env: {+ PROTON_ENABLE_WAYLAND: '0'+ }+ },+ exeCandidates: [+ 'Program Files (x86)/Ubisoft/Ubisoft Game Launcher/UbisoftConnect.exe',+ 'Program Files/Ubisoft/Ubisoft Game Launcher/UbisoftConnect.exe'+ ]+ }+ },+ {+ id: 'xbox-cloud',+ kind: 'web',+ title: 'Xbox Cloud Gaming',+ platforms: ALL_DESKTOP_PLATFORMS,+ artwork: {+ square: 'xbox-square.jpg',+ hero: 'xbox-hero.jpg'+ },+ web: {+ url: 'https://www.xbox.com/play',+ userAgent: CHROME_USER_AGENT,+ launchFullScreen: true+ }+ }+]++export function getSideloadPreset(+ presetId: string | undefined+): SideloadPreset | undefined {+ if (!presetId) {+ return undefined+ }+ return SIDELOAD_PRESETS.find((preset) => preset.id === presetId)+}++/**+ * Stable app name so that re-applying a preset updates the existing entry+ * (and reuses its Wine prefix) instead of adding a duplicate.+ */+export function getSideloadPresetAppName(preset: SideloadPreset): string {+ return `preset-${preset.id}`+}++export function getSideloadPresetPlatform(+ preset: SideloadPreset+): InstallPlatform {+ return preset.kind === 'web' ? 'Browser' : 'Windows'+}++export function getSideloadPresetLaunchArgs(+ preset: SideloadPreset,+ platform: NodeJS.Platform+): string[] {+ return preset.launcher?.launchArgs?.[platform as SideloadPresetPlatform] ?? []+}++export function getSideloadPresetLaunchEnv(+ preset: SideloadPreset+): Record<string, string> {+ return preset.launcher?.launchEnv ?? {}+}++export function getPresetInstallerArgs(+ preset: SideloadPreset,+ silent = true+): string[] {+ if (!preset.launcher) {+ return []+ }++ const { args = [], silentArgs } = preset.launcher.installer+ return silent && silentArgs?.length ? silentArgs : args+}++export function isSideloadPresetAvailableOn(+ preset: SideloadPreset,+ platform: SideloadPresetPlatform+): boolean {+ return preset.platforms.includes(platform)+}++/**+ * Static t() calls keep the preset catalog discoverable by i18next-parser.+ * Do not turn these keys into dynamically built strings.+ */+export function getSideloadPresetText(+ t: TFunction<'gamepage'>,+ preset: SideloadPreset+): { description: string; note?: string } {+ switch (preset.id) {+ case 'battlenet':+ return {+ description: t('sideload.presets.battlenet.description')+ }+ case 'ea-app':+ return {+ description: t('sideload.presets.ea-app.description'),+ note: t('sideload.presets.ea-app.note')+ }+ case 'ubisoft-connect':+ return {+ description: t('sideload.presets.ubisoft-connect.description'),+ note: t('sideload.presets.ubisoft-connect.note')+ }+ case 'xbox-cloud':+ return {+ description: t('sideload.presets.xbox-cloud.description'),+ note: t('sideload.presets.xbox-cloud.note')+ }+ default:+ return { description: preset.title }+ }+}diff --git a/src/common/types.ts b/src/common/types.tsindex cec46af54..ff15b9c0b 100644--- a/src/common/types.ts+++ b/src/common/types.ts@@ -286,6 +286,14 @@ export interface GameInfo {dlcList?: GameMetadataInner[]customUserAgent?: stringlaunchFullScreen?: boolean+ /** Id of the Add Game preset this entry was created from, if any. */+ presetId?: string+ /** Launcher preset this game was discovered from. */+ sourcePresetId?: string+ /** Store-specific id (e.g. Ubisoft game id) for scanned games. */+ storeGameId?: string+ /** Protocol URL used to launch a game through its store client. */+ launchUrl?: stringoverrides?: {title?: stringart_cover?: stringdiff --git a/src/common/types/ipc.ts b/src/common/types/ipc.tsindex 589a223e3..3b44e7aa1 100644--- a/src/common/types/ipc.ts+++ b/src/common/types/ipc.ts@@ -50,6 +50,10 @@ import type {WineManagerStatus,WineVersionInfo} from '../types'+import type {+ MissingSideloadGame,+ ScannedSideloadGame+} from '../sideload_presets'import type {CatalogLocaleSettings,CatalogProduct,@@ -544,6 +548,34 @@ interface AsyncIPCFunctions {getRollbackSnapshot: () => Promise<HeroicRollbackSnapshot | null>rollbackHeroicBackup: () => Promise<HeroicApplyResult>restartHeroic: () => Promise<void>+ getSideloadPresetArtwork: (presetId: string) => Promise<{+ square: string+ hero: string+ }>+ downloadSideloadPresetInstaller: (+ presetId: string+ ) => Promise<{ installerPath: string }>+ runSideloadPresetInstaller: (+ presetId: string,+ silent?: boolean+ ) => Promise<{ status: 'done' | 'error'; error?: string }>+ detectSideloadPresetExecutable: (presetId: string) => Promise<string | null>+ getSideloadPresetStatuses: () => Promise<+ Record<+ string,+ { installed: boolean; prefixExists: boolean; prefix?: string }+ >+ >+ scanSideloadPresetGames: (presetId: string) => Promise<{+ games: ScannedSideloadGame[]+ missing: MissingSideloadGame[]+ prefix?: string+ error?: string+ }>+ addScannedSideloadGames: (+ presetId: string,+ gameIds: string[]+ ) => Promise<{ added: string[]; error?: string }>}interface FrontendMessages {@@ -599,6 +631,10 @@ interface FrontendMessages {>) => voiditchioOAuthCallback: (url: string) => void+ presetDownloadProgress: (progress: {+ presetId: string+ progress: number+ }) => void// Used inside tests, so we can be a bit lenient with the type checking heremessage: (...params: unknown[]) => voiddiff --git a/src/frontend/components/UI/UninstallModal/index.tsx b/src/frontend/components/UI/UninstallModal/index.tsxindex 2ccdb6120..c72328485 100644--- a/src/frontend/components/UI/UninstallModal/index.tsx+++ b/src/frontend/components/UI/UninstallModal/index.tsx@@ -37,6 +37,7 @@ const UninstallModal: React.FC<UninstallModalProps> = function ({const location = useLocation()const { installingEpicGame, libraryStatus } = useContext(ContextProvider)const [gameTitle, setGameTitle] = useState('')+ const [isScannedGame, setIsScannedGame] = useState(false)const isGameRunning = libraryStatus.find((st) =>@@ -66,6 +67,7 @@ const UninstallModal: React.FC<UninstallModalProps> = function ({}setGameTitle(gameInfo.overrides?.title || gameInfo.title)+ setIsScannedGame(Boolean(gameInfo.sourcePresetId))const { install } = gameInfoif (install.platform?.toLowerCase() !== 'windows') {@@ -80,7 +82,10 @@ const UninstallModal: React.FC<UninstallModalProps> = function ({const defaultSettings = await window.api.requestGameSettings('default')setWinePrefix(gameSettings.winePrefix)- setDisableDeleteWine(gameSettings.winePrefix === defaultSettings.winePrefix)+ setDisableDeleteWine(+ gameSettings.winePrefix === defaultSettings.winePrefix ||+ Boolean(gameInfo.sourcePresetId)+ )}useEffect(() => {@@ -201,10 +206,15 @@ const UninstallModal: React.FC<UninstallModalProps> = function ({)}{disableDeleteWine && (<p className="default-wine-warning">- {t(- 'gamepage:box.uninstall.prefix_warning',- 'The Wine prefix for this game is the default prefix. If you really want to delete it, you have to do it manually.'- )}+ {isScannedGame+ ? t(+ 'gamepage:box.uninstall.shared_prefix_warning',+ 'This game uses the launcher prefix, which may be shared by other scanned games. Remove the launcher itself to delete that prefix.'+ )+ : t(+ 'gamepage:box.uninstall.prefix_warning',+ 'The Wine prefix for this game is the default prefix. If you really want to delete it, you have to do it manually.'+ )}</p>)}{!isDlc && (diff --git a/src/frontend/components/UI/Winetricks/index.tsx b/src/frontend/components/UI/Winetricks/index.tsxindex 81f97e66c..37e116fd4 100644--- a/src/frontend/components/UI/Winetricks/index.tsx+++ b/src/frontend/components/UI/Winetricks/index.tsx@@ -10,10 +10,17 @@ import { Runner } from 'common/types'interface Props {onClose: () => voidrunner: Runner+ /** Defaults to the app open in the Settings screen. */+ appName?: string}-export default function Winetricks({ onClose, runner }: Props) {- const { appName } = useContext(SettingsContext)+export default function Winetricks({+ onClose,+ runner,+ appName: appNameOverride+}: Props) {+ const { appName: settingsAppName } = useContext(SettingsContext)+ const appName = appNameOverride ?? settingsAppNameconst { t } = useTranslation()const [loadingInstalled, setLoadingInstalled] = useState(true)diff --git a/src/frontend/screens/Game/GamePage/components/GameActions.tsx b/src/frontend/screens/Game/GamePage/components/GameActions.tsxindex 20bd83c95..5894ba5a9 100644--- a/src/frontend/screens/Game/GamePage/components/GameActions.tsx+++ b/src/frontend/screens/Game/GamePage/components/GameActions.tsx@@ -2,6 +2,11 @@ import { useContext, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { Heart, RefreshCw } from 'lucide-react'import { GameInfo } from 'common/types'+import {+ SIDELOAD_PRESETS,+ getSideloadPreset,+ getSideloadPresetAppName+} from 'common/sideload_presets'import { Button, Icon, Tooltip } from 'frontend/components/UI'import ContextProvider from 'frontend/state/ContextProvider'import GameContext from '../../GameContext'@@ -9,6 +14,7 @@ import DotsMenu from './DotsMenu'import MainButton from './MainButton'import SettingsButton from './SettingsButton'import CloudSyncStatus from 'frontend/components/UI/CloudSyncStatus'+import ScanGamesButton from './ScanGames'interface Props {gameInfo: GameInfo@@ -30,7 +36,7 @@ const GameActions = ({hideMainButton = false}: Props) => {const { t } = useTranslation('gamepage')- const { favouriteGames } = useContext(ContextProvider)+ const { favouriteGames, platform } = useContext(ContextProvider)const { appName } = useContext(GameContext)const title = gameInfo.overrides?.title || gameInfo.title@@ -41,6 +47,17 @@ const GameActions = ({)const isBrowserGame = gameInfo.install.platform === 'Browser'+ const preset =+ (gameInfo.presetId ? getSideloadPreset(gameInfo.presetId) : undefined) ??+ SIDELOAD_PRESETS.find(+ (candidate) =>+ candidate.kind === 'launcher' &&+ getSideloadPresetAppName(candidate) === gameInfo.app_name+ )+ const showScanGames =+ gameInfo.runner === 'sideload' &&+ preset?.kind === 'launcher' &&+ platform !== 'win32'return (<div className="gameActions">@@ -54,6 +71,10 @@ const GameActions = ({<DotsMenu gameInfo={gameInfo} handleUpdate={handleUpdate} />+ {showScanGames && preset && (+ <ScanGamesButton presetId={preset.id} launcherTitle={preset.title} />+ )}+{!isBrowserGame && <SettingsButton gameInfo={gameInfo} />}<Tooltipdiff --git a/src/frontend/screens/Game/GamePage/components/ScanGames/index.css b/src/frontend/screens/Game/GamePage/components/ScanGames/index.cssnew file mode 100644index 000000000..c6fc6f218--- /dev/null+++ b/src/frontend/screens/Game/GamePage/components/ScanGames/index.css@@ -0,0 +1,145 @@+.scanGamesDialog .Modal__content {+ min-height: 240px;+}++.scanGamesDialog__subtitle {+ margin: 0 0 var(--space-md);+ color: var(--text-secondary);+ font-size: var(--body-md);+}++.scanGamesDialog__missing {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-md);+ margin-bottom: var(--space-md);+ padding: var(--space-md);+ background: var(--background-darker);+ border: 1px solid var(--status-warning, var(--accent));+ border-radius: var(--radius-sm);+}++.scanGamesDialog__missing strong {+ display: block;+ color: var(--text-default);+}++.scanGamesDialog__missing p {+ margin: var(--space-xs) 0;+ color: var(--text-secondary);+ font-size: var(--body-sm);+}++.scanGamesDialog__missing ul {+ margin: 0;+ padding-inline-start: var(--space-lg);+ max-height: 120px;+ overflow-y: auto;+}++.scanGamesDialog__confirm {+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+ margin-bottom: var(--space-md);+ padding: var(--space-md);+ background: var(--background-darker);+ border: 1px solid var(--status-warning, var(--accent));+ border-radius: var(--radius-sm);+}++.scanGamesDialog__confirm p {+ margin: 0;+ color: var(--text-secondary);+ font-size: var(--body-sm);+}++.scanGamesDialog__confirm ul {+ margin: 0;+ padding-inline-start: var(--space-lg);+}++.scanGamesDialog__confirmActions {+ display: flex;+ gap: var(--space-sm);+}++.scanGamesDialog__status {+ display: flex;+ align-items: center;+ gap: var(--space-sm);+ color: var(--text-secondary);+}++.scanGamesDialog__status .spinner {+ animation: scanGamesSpin 1s linear infinite;+}++@keyframes scanGamesSpin {+ from {+ transform: rotate(0deg);+ }+ to {+ transform: rotate(360deg);+ }+}++.scanGamesDialog__list {+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+ max-height: 360px;+ overflow-y: auto;+}++.scanGamesDialog__row {+ display: flex;+ align-items: flex-start;+ gap: var(--space-sm);+ padding: var(--space-sm);+ background: var(--background-darker);+ border-radius: var(--radius-sm);+ cursor: pointer;+}++.scanGamesDialog__row:has(input:disabled) {+ opacity: 0.6;+ cursor: default;+}++.scanGamesDialog__game {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ flex: 1;+}++.scanGamesDialog__gameTitle {+ font-weight: var(--semibold);+ color: var(--text-default);+}++.scanGamesDialog__path {+ color: var(--text-secondary);+ font-size: var(--text-xs);+ word-break: break-all;+}++.scanGamesDialog__badges {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-xs);+ margin-top: var(--space-xs);+}++.Modal__footer.scanGamesDialog__footer {+ justify-content: space-between;+ gap: var(--space-md);+}++.scanGamesDialog__footerRight {+ display: flex;+ gap: var(--space-sm);+}diff --git a/src/frontend/screens/Game/GamePage/components/ScanGames/index.tsx b/src/frontend/screens/Game/GamePage/components/ScanGames/index.tsxnew file mode 100644index 000000000..9cfc4f97d--- /dev/null+++ b/src/frontend/screens/Game/GamePage/components/ScanGames/index.tsx@@ -0,0 +1,472 @@+import './index.css'+import { useCallback, useContext, useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { LoaderCircle, ScanSearch } from 'lucide-react'++import type {+ MissingSideloadGame,+ ScannedSideloadGame+} from 'common/sideload_presets'+import { Alert, Badge, Button, Icon, Tooltip } from 'frontend/components/UI'+import Checkbox from 'frontend/components/UI/Checkbox'+import {+ Modal,+ ModalContent,+ ModalFooter,+ ModalHeader+} from 'frontend/components/UI/Modal'+import ContextProvider from 'frontend/state/ContextProvider'+import { useLocation, useNavigate } from 'react-router-dom'++type Props = {+ presetId: string+ launcherTitle: string+}++function ScanGamesButton({ presetId, launcherTitle }: Props) {+ const { t } = useTranslation('gamepage')+ const location = useLocation()+ const navigate = useNavigate()+ const autoScan = Boolean(+ (location.state as { autoScanGames?: boolean } | null)?.autoScanGames+ )+ const [open, setOpen] = useState(false)+ const [autoOpened, setAutoOpened] = useState(false)++ useEffect(() => {+ if (!autoScan) {+ return+ }+ setAutoOpened(true)+ setOpen(true)+ navigate(location.pathname, {+ replace: true,+ state: { ...location.state, autoScanGames: false }+ })+ }, [autoScan])++ return (+ <>+ <Tooltip content={t('scan-games.button', 'Scan installed games')} asChild>+ <Button+ variant="secondary"+ className="gameActions__scan"+ aria-label={t('scan-games.button', 'Scan installed games')}+ onClick={() => setOpen(true)}+ icon={<Icon glyph={ScanSearch} size="md" />}+ >+ {t('scan-games.button-short', 'Scan games')}+ </Button>+ </Tooltip>+ {open && (+ <ScanGamesDialog+ presetId={presetId}+ launcherTitle={launcherTitle}+ autoOpened={autoOpened}+ onClose={() => {+ setOpen(false)+ setAutoOpened(false)+ }}+ />+ )}+ </>+ )+}++function ScanGamesDialog({+ presetId,+ launcherTitle,+ autoOpened = false,+ onClose+}: Props & { autoOpened?: boolean; onClose: () => void }) {+ const { t } = useTranslation('gamepage')+ const { showDialogModal } = useContext(ContextProvider)+ const [games, setGames] = useState<ScannedSideloadGame[]>([])+ const [missing, setMissing] = useState<MissingSideloadGame[]>([])+ const [selected, setSelected] = useState<Set<string>>(new Set())+ const [loading, setLoading] = useState(true)+ const [adding, setAdding] = useState(false)+ const [removing, setRemoving] = useState(false)+ const [confirmingRemoval, setConfirmingRemoval] = useState(false)+ const [removeError, setRemoveError] = useState('')+ const [error, setError] = useState('')++ const scan = useCallback(async () => {+ setLoading(true)+ setError('')+ try {+ const result = await window.api.scanSideloadPresetGames(presetId)+ if (result.error) {+ setError(result.error)+ setGames([])+ setMissing([])+ } else {+ setGames(result.games)+ setMissing(result.missing ?? [])+ setSelected((current) => {+ const next = new Set<string>()+ for (const game of result.games) {+ if (!game.added && current.has(game.id)) {+ next.add(game.id)+ }+ }+ return next+ })+ }+ } catch (scanError) {+ setError(String(scanError))+ setGames([])+ setMissing([])+ } finally {+ setLoading(false)+ }+ }, [presetId])++ useEffect(() => {+ void scan()+ }, [scan])++ useEffect(() => {+ if (+ autoOpened &&+ !loading &&+ !error &&+ games.length === 0 &&+ missing.length === 0+ ) {+ onClose()+ }+ }, [autoOpened, loading, error, games.length, missing.length, onClose])++ const toggle = (game: ScannedSideloadGame) => {+ if (game.added) {+ return+ }+ setSelected((current) => {+ const next = new Set(current)+ if (next.has(game.id)) {+ next.delete(game.id)+ } else {+ next.add(game.id)+ }+ return next+ })+ }++ const addSelected = async () => {+ if (!selected.size) {+ return+ }+ const selectedGames = games.filter((game) => selected.has(game.id))+ setAdding(true)+ try {+ const result = await window.api.addScannedSideloadGames(presetId, [+ ...selected+ ])+ if (result.error) {+ showDialogModal({+ title: t('scan-games.error.title', 'Could not add games'),+ message: t(+ 'scan-games.error.add',+ 'Could not add the selected games: {{error}}',+ { error: result.error }+ ),+ type: 'ERROR',+ buttons: [{ text: t('box.ok', 'OK') }]+ })+ return+ }++ onClose()++ if (!result.added.length) {+ showDialogModal({+ title: t('scan-games.success.title', 'Added to your library'),+ message: t(+ 'scan-games.success.none',+ 'No new games were added; they are already in your library.'+ ),+ type: 'MESSAGE',+ buttons: [{ text: t('box.ok', 'OK') }]+ })+ return+ }++ showDialogModal({+ title: t('scan-games.success.title', 'Added to your library'),+ message: (+ <div>+ <p>+ {t('scan-games.success.message', {+ count: result.added.length+ })}+ </p>+ <ul className="scanGamesDialog__addedList">+ {selectedGames.map((game) => (+ <li key={game.id}>{game.title}</li>+ ))}+ </ul>+ </div>+ ),+ type: 'MESSAGE',+ buttons: [{ text: t('box.ok', 'OK') }]+ })+ } catch (addError) {+ showDialogModal({+ title: t('scan-games.error.title', 'Could not add games'),+ message: String(addError),+ type: 'ERROR',+ buttons: [{ text: t('box.ok', 'OK') }]+ })+ } finally {+ setAdding(false)+ }+ }++ const removeMissing = async () => {+ setRemoving(true)+ setRemoveError('')+ try {+ for (const game of missing) {+ await window.api.uninstall(game.appName, 'sideload', false, false)+ }+ setConfirmingRemoval(false)+ await scan()+ } catch (error) {+ setRemoveError(+ t(+ 'scan-games.missing.failed',+ 'Could not remove the games from Heroic: {{error}}',+ { error: String(error) }+ )+ )+ } finally {+ setRemoving(false)+ }+ }++ const askRemoveMissing = () => {+ if (!missing.length) {+ return+ }+ setRemoveError('')+ setConfirmingRemoval(true)+ }++ const errorMessage = () => {+ switch (error) {+ case 'prefix-not-found':+ return t(+ 'scan-games.error.prefix-not-found',+ 'The Wine prefix used by {{launcher}} was not found.',+ { launcher: launcherTitle }+ )+ case 'registry-not-found':+ return t(+ 'scan-games.error.registry-not-found',+ 'Could not read the Wine registry for this prefix.'+ )+ case 'unsupported-platform':+ return t(+ 'scan-games.error.unsupported-platform',+ 'Scanning installed games is only available for Wine/Proton prefixes.'+ )+ default:+ return t(+ 'scan-games.error.generic',+ 'Could not scan the launcher prefix: {{error}}',+ { error }+ )+ }+ }++ return (+ <Modal showCloseButton onClose={onClose} className="scanGamesDialog">+ <ModalHeader>{t('scan-games.title', 'Scan installed games')}</ModalHeader>+ <ModalContent>+ <p className="scanGamesDialog__subtitle">+ {t(+ 'scan-games.subtitle',+ 'Games installed by {{launcher}} in this prefix:',+ { launcher: launcherTitle }+ )}+ </p>++ {loading && (+ <div className="scanGamesDialog__status">+ <Icon glyph={LoaderCircle} size="lg" className="spinner" />+ {t('scan-games.loading', 'Scanning the prefix…')}+ </div>+ )}++ {!loading && error && <Alert variant="error">{errorMessage()}</Alert>}++ {!loading && !error && missing.length > 0 && !confirmingRemoval && (+ <div className="scanGamesDialog__missing">+ <div>+ <strong>+ {t('scan-games.missing.title', 'Games no longer installed')}+ </strong>+ <p>+ {t(+ 'scan-games.missing.banner',+ 'Still in your Heroic library, but no longer installed by {{launcher}}:',+ { launcher: launcherTitle }+ )}+ </p>+ <ul>+ {missing.map((game) => (+ <li key={game.appName}>{game.title}</li>+ ))}+ </ul>+ </div>+ <Button+ variant="dangerSubtle"+ onClick={askRemoveMissing}+ disabled={loading}+ >+ {t('scan-games.missing.remove', 'Remove from Heroic')}+ </Button>+ </div>+ )}++ {!loading && !error && confirmingRemoval && (+ <div className="scanGamesDialog__confirm">+ <strong>+ {t('scan-games.missing.confirm-title', 'Remove from Heroic?')}+ </strong>+ <p>+ {t(+ 'scan-games.missing.confirm-message',+ 'These games were removed from {{launcher}} but are still in your Heroic library:',+ { launcher: launcherTitle }+ )}+ </p>+ <ul>+ {missing.map((game) => (+ <li key={game.appName}>{game.title}</li>+ ))}+ </ul>+ {removeError && <Alert variant="error">{removeError}</Alert>}+ <div className="scanGamesDialog__confirmActions">+ <Button+ variant="danger"+ onClick={() => void removeMissing()}+ disabled={removing}+ >+ {removing+ ? t('scan-games.missing.removing', 'Removing…')+ : t('scan-games.missing.remove', 'Remove from Heroic')}+ </Button>+ <Button+ variant="secondary"+ onClick={() => setConfirmingRemoval(false)}+ disabled={removing}+ >+ {t('box.cancel', 'Cancel')}+ </Button>+ </div>+ </div>+ )}++ {!loading &&+ !error &&+ games.length === 0 &&+ missing.length === 0 &&+ !confirmingRemoval && (+ <Alert variant="neutral">+ {t(+ 'scan-games.empty',+ 'No installed games were found. Install a game through {{launcher}}, then use Rescan.',+ { launcher: launcherTitle }+ )}+ </Alert>+ )}++ {!loading && !error && games.length > 0 && (+ <div className="scanGamesDialog__list">+ {games.map((game) => (+ <label+ key={game.id}+ className="scanGamesDialog__row"+ data-testid={`scan-game-${game.id}`}+ >+ <Checkbox+ checked={selected.has(game.id)}+ disabled={game.added}+ onChange={() => toggle(game)}+ inputProps={{+ 'aria-label': t('scan-games.select', 'Select {{title}}', {+ title: game.title+ })+ }}+ />+ <span className="scanGamesDialog__game">+ <span className="scanGamesDialog__gameTitle">+ {game.title}+ </span>+ {game.installDir && (+ <span className="scanGamesDialog__path">+ {game.installDir}+ </span>+ )}+ <span className="scanGamesDialog__badges">+ <Badge variant="neutral">+ {game.source === 'ubisoft'+ ? 'Ubisoft Connect'+ : game.source === 'ea'+ ? 'EA app'+ : 'Battle.net'}+ </Badge>+ <Badge variant={game.launchUrl ? 'info' : 'neutral'}>+ {game.launchUrl+ ? t(+ 'scan-games.launch-via',+ 'Launches via {{launcher}}',+ {+ launcher: launcherTitle+ }+ )+ : t('scan-games.launch-direct', 'Direct executable')}+ </Badge>+ {game.added && (+ <Badge variant="success">+ {t('scan-games.added', 'Added')}+ </Badge>+ )}+ </span>+ </span>+ </label>+ ))}+ </div>+ )}+ </ModalContent>+ <ModalFooter className="scanGamesDialog__footer">+ <Button+ variant="secondary"+ onClick={() => void scan()}+ disabled={loading || adding}+ icon={<Icon glyph={ScanSearch} size="md" />}+ >+ {t('scan-games.rescan', 'Rescan')}+ </Button>+ <div className="scanGamesDialog__footerRight">+ <Button variant="ghost" onClick={onClose} disabled={adding}>+ {t('scan-games.cancel', 'Cancel')}+ </Button>+ <Button+ variant="primary"+ onClick={() => void addSelected()}+ disabled={!selected.size || adding}+ >+ {adding+ ? t('scan-games.adding', 'Adding…')+ : t('scan-games.add-selected', 'Add selected')}+ </Button>+ </div>+ </ModalFooter>+ </Modal>+ )+}++export default ScanGamesButtondiff --git a/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.scss b/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.scssnew file mode 100644index 000000000..395795844--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.scss@@ -0,0 +1,170 @@+.presetPicker {+ flex: 1 1 auto;+ min-height: 0;+ overflow-y: auto;+ padding: var(--space-md) var(--modal-padding-inline) var(--space-md);+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+}++.presetCustomEntry {+ display: flex;+ align-items: center;+ gap: var(--space-md);+ width: 100%;+ padding: var(--space-sm-fixed) var(--space-md);+ text-align: start;+ color: var(--text-default);+ background: var(--panel-surface, var(--background-darker));+ border: 1px solid var(--panel-border);+ border-radius: var(--radius-sm);+ cursor: pointer;+ transition:+ box-shadow 0.2s cubic-bezier(0.22, 0.61, 0.36, 1),+ border-color 0.2s ease;+}++.presetCustomEntry:hover,+.presetCustomEntry:focus-visible {+ border-color: var(--navbar-accent, var(--accent));+ box-shadow:+ inset 0 0 0 1px var(--navbar-accent, var(--accent)),+ 0 8px 24px -12px var(--navbar-accent, var(--accent));+}++.presetCustomEntry__icon {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ width: 44px;+ height: 44px;+ color: var(--primary);+ background: var(--background-darker);+ border-radius: var(--radius-pill);+}++.presetCustomEntry__text {+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+}++.presetCustomEntry__title {+ font-family: var(--primary-font-family);+ font-size: var(--title-sm);+ font-weight: var(--bold);+}++.presetCustomEntry__description {+ font-size: var(--body-sm);+ color: var(--text-secondary);+}++.presetCustomEntry__hint {+ margin-top: var(--space-xs);+ font-size: var(--body-sm);+ color: var(--text-secondary);+}++.presetPicker__sectionHeader {+ display: flex;+ align-items: center;+ gap: var(--space-md);+ font-size: var(--body-sm);+ color: var(--text-secondary);+}++.presetPicker__sectionHeader::before,+.presetPicker__sectionHeader::after {+ flex: 1;+ height: 1px;+ content: '';+ background: var(--panel-divider);+}++.presetPicker__grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));+ gap: var(--space-sm-fixed);+}++.presetCard {+ display: flex;+ height: 100%;+ overflow: hidden;+ cursor: pointer;+ background: var(--panel-surface, var(--background-darker));+ border: none;+ border-radius: var(--radius-sm);+ outline: none;+ transition: box-shadow 0.2s cubic-bezier(0.22, 0.61, 0.36, 1);+}++.presetCard:hover,+.presetCard:focus-within,+.presetCard:focus-visible {+ box-shadow:+ inset 0 0 0 1px var(--navbar-accent, var(--accent)),+ 0 8px 24px -12px var(--navbar-accent, var(--accent));+}++.presetCard .presetCard__card.Panel {+ flex: 1;+ gap: var(--space-xs-fixed);+ padding: var(--space-sm-fixed);+ background: transparent;+ border-radius: 0;+}++.presetCard .FeatureCard__footer {+ margin-top: auto;+}++.presetCard .FeatureCard__description {+ display: -webkit-box;+ overflow: hidden;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+ line-clamp: 2;+}++.presetCard__art {+ flex-shrink: 0;+ width: 44px;+ height: 44px;+ object-fit: cover;+ border-radius: var(--radius-sm);+}++.presetCard__art--custom {+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--primary);+ background: var(--background-darker);+}++.presetCard__actions {+ display: flex;+ align-items: stretch;+ width: 100%;+}++@media (max-width: 700px) {+ .presetPicker__grid {+ grid-template-columns: minmax(0, 1fr);+ }++ .presetCustomEntry {+ flex-direction: column;+ align-items: flex-start;+ }++ .presetCustomEntry .Button {+ width: 100%;+ }+}diff --git a/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.stories.tsx b/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.stories.tsxnew file mode 100644index 000000000..6f7e1ca32--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.stories.tsx@@ -0,0 +1,48 @@+import { expect, fn, userEvent } from 'storybook/test'+import type { Meta, StoryObj } from '@storybook/react-vite'++import PresetPicker from '.'++const meta = {+ title: 'Overlays/PresetPicker',+ component: PresetPicker,+ args: {+ platform: 'linux',+ onSelectPreset: fn(),+ onCustom: fn()+ },+ render: (args) => (+ <div style={{ width: 860, maxWidth: '95vw' }}>+ <PresetPicker {...args} />+ </div>+ ),+ parameters: {+ docs: {+ story: { inline: false, height: '760px' },+ description: {+ component:+ 'First screen of the Add Game dialog. Presets download official vendor installers (launchers) or open a curated web app, and the Custom card falls back to the manual sideload flow.'+ }+ }+ }+} satisfies Meta<typeof PresetPicker>++export default meta++type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const PicksBattleNet: Story = {+ play: async ({ canvas, args }) => {+ await userEvent.click(canvas.getByTestId('preset-battlenet'))+ await expect(args.onSelectPreset).toHaveBeenCalled()+ }+}++export const PicksCustom: Story = {+ play: async ({ canvas, args }) => {+ await userEvent.click(canvas.getByTestId('preset-custom'))+ await expect(args.onCustom).toHaveBeenCalled()+ }+}diff --git a/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.tsx b/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.tsxnew file mode 100644index 000000000..f97e812d6--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/PresetPicker/index.tsx@@ -0,0 +1,306 @@+import './index.scss'+import { useContext, useEffect, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import classNames from 'classnames'+import { CircleCheck, Globe, Layers, Plus } from 'lucide-react'++import {+ SIDELOAD_PRESETS,+ getSideloadPresetText,+ type SideloadPreset,+ type SideloadPresetPlatform,+ isSideloadPresetAvailableOn+} from 'common/sideload_presets'+import {+ Badge,+ CachedImage,+ Icon,+ InfoTooltip,+ SectionHeader+} from 'frontend/components/UI'+import FeatureCard from 'frontend/components/UI/FeatureCard'+import Button from 'frontend/components/UI/Button'+import { ModalContent } from 'frontend/components/UI/Modal'+import ContextProvider from 'frontend/state/ContextProvider'+import fallbackImage from 'frontend/assets/heroic_card.jpg'++type Props = {+ platform: SideloadPresetPlatform+ onSelectPreset: (preset: SideloadPreset) => void+ onCustom: () => void+}++type PresetStatus = {+ installed: boolean+ prefixExists: boolean+ prefix?: string+}++function PresetCard({+ preset,+ artwork,+ installed,+ onSelect+}: {+ preset: SideloadPreset+ artwork?: string+ installed: boolean+ onSelect: () => void+}) {+ const { t } = useTranslation('gamepage')+ const isLauncher = preset.kind === 'launcher'+ const { description } = getSideloadPresetText(t, preset)++ return (+ <div+ className={classNames('presetCard', {+ 'presetCard--installed': installed+ })}+ onClick={onSelect}+ data-testid={`preset-${preset.id}`}+ >+ <FeatureCard+ className="presetCard__card"+ layout="inline"+ icon={+ <CachedImage+ className="presetCard__art"+ src={artwork || fallbackImage}+ fallback={fallbackImage}+ alt={preset.title}+ />+ }+ title={preset.title}+ description={description}+ meta={+ <>+ <Badge+ variant="neutral"+ glyph={isLauncher ? Layers : Globe}+ className="presetCard__typeBadge"+ >+ {isLauncher+ ? t('sideload.presets.badge-launcher', 'Launcher')+ : t('sideload.presets.badge-web', 'Web app')}+ </Badge>+ {installed && (+ <Badge variant="success" glyph={CircleCheck}>+ {t('sideload.presets.installed', 'Installed')}+ </Badge>+ )}+ </>+ }+ action={+ <div className="presetCard__actions">+ <Button+ variant={installed ? 'ghost' : 'secondary'}+ size="md"+ fullWidth+ onClick={(event) => {+ event.stopPropagation()+ onSelect()+ }}+ >+ {installed+ ? t('sideload.presets.add-again', 'Add again')+ : t('sideload.presets.add', 'Add')}+ </Button>+ </div>+ }+ />+ </div>+ )+}++function CustomEntry({ onSelect }: { onSelect: () => void }) {+ const { t } = useTranslation('gamepage')++ return (+ <div+ className="presetCustomEntry"+ onClick={onSelect}+ data-testid="preset-custom"+ >+ <span className="presetCustomEntry__icon">+ <Icon glyph={Plus} size="lg" />+ </span>+ <span className="presetCustomEntry__text">+ <span className="presetCustomEntry__title">+ {t(+ 'sideload.presets.custom.title',+ 'Add a custom app, game or script'+ )}+ </span>+ <span className="presetCustomEntry__description">+ {t(+ 'sideload.presets.custom.description',+ 'Use any executable, script or web URL.'+ )}+ </span>+ <span className="presetCustomEntry__hint">+ {t(+ 'sideload.presets.custom.store-hint',+ 'Epic, GOG and Amazon games should be imported from your library after logging in, not added here.'+ )}+ </span>+ </span>+ <Button+ variant="secondary"+ onClick={(event) => {+ event.stopPropagation()+ onSelect()+ }}+ >+ {t('sideload.presets.custom.action', 'Custom')}+ </Button>+ </div>+ )+}++export default function PresetPicker({+ platform,+ onSelectPreset,+ onCustom+}: Props) {+ const { t } = useTranslation('gamepage')+ const { showDialogModal } = useContext(ContextProvider)+ const [artwork, setArtwork] = useState<Record<string, string>>({})+ const [statuses, setStatuses] = useState<Record<string, PresetStatus>>({})++ const availablePresets = useMemo(+ () =>+ SIDELOAD_PRESETS.filter((preset) =>+ isSideloadPresetAvailableOn(preset, platform)+ ),+ [platform]+ )++ useEffect(() => {+ let cancelled = false++ const loadArtwork = async () => {+ const entries = await Promise.all(+ availablePresets.map(async (preset) => {+ try {+ const art = await window.api.getSideloadPresetArtwork(preset.id)+ return [preset.id, art.square] as const+ } catch {+ return [preset.id, ''] as const+ }+ })+ )+ if (!cancelled) {+ setArtwork(Object.fromEntries(entries))+ }+ }++ void loadArtwork()+ return () => {+ cancelled = true+ }+ }, [availablePresets])++ useEffect(() => {+ let cancelled = false++ window.api+ .getSideloadPresetStatuses()+ .then((result) => {+ if (!cancelled) {+ setStatuses(result)+ }+ })+ .catch(() => {})++ return () => {+ cancelled = true+ }+ }, [])++ const selectPreset = (preset: SideloadPreset) => {+ const status = statuses[preset.id]++ if (status?.installed || status?.prefixExists) {+ const prefix = status.prefix ?? ''+ showDialogModal({+ title: status.installed+ ? t(+ 'sideload.presets.installed-warning.title',+ '{{title}} is already installed',+ { title: preset.title }+ )+ : t(+ 'sideload.presets.prefix-warning.title',+ 'A Wine prefix already exists'+ ),+ message: status.installed+ ? prefix+ ? t(+ 'sideload.presets.installed-warning.message',+ 'Continuing will run the preset again and may reinstall or overwrite files in {{prefix}}. You can change the prefix in the next step.',+ { prefix }+ )+ : t(+ 'sideload.presets.installed-warning.no-prefix-message',+ 'Continuing will run the preset again. You can adjust the setup in the next step.'+ )+ : t(+ 'sideload.presets.prefix-warning.message',+ 'Heroic found an existing prefix at {{prefix}}. Continuing will reuse it. You can change it in the next step.',+ { prefix }+ ),+ buttons: [+ {+ text: t('sideload.presets.warning.continue', 'Continue anyway'),+ variant: 'primary',+ onClick: () => onSelectPreset(preset)+ },+ { text: t('sideload.presets.warning.cancel', 'Cancel') }+ ],+ type: 'MESSAGE'+ })+ return+ }++ onSelectPreset(preset)+ }++ return (+ <ModalContent className="presetPicker">+ <SectionHeader+ title={t('sideload.presets.title', 'Add a game or app')}+ subtitle={t(+ 'sideload.presets.subtitle',+ 'Start from a preset, or add your own executable or web URL.'+ )}+ />++ <CustomEntry onSelect={onCustom} />++ <div className="presetPicker__sectionHeader">+ <span>+ {t('sideload.presets.or-use-presets', 'Or use one of our presets')}+ </span>+ <InfoTooltip+ content={t(+ 'sideload.presets.disclaimer-short',+ 'Presets download the official installer directly from the vendor. No third-party software is bundled.'+ )}+ label={t('sideload.presets.title', 'Add a game or app')}+ />+ </div>++ <div className="presetPicker__grid">+ {availablePresets.map((preset) => (+ <PresetCard+ key={preset.id}+ preset={preset}+ artwork={artwork[preset.id]}+ installed={Boolean(statuses[preset.id]?.installed)}+ onSelect={() => selectPreset(preset)}+ />+ ))}+ </div>+ </ModalContent>+ )+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.scss b/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.scssnew file mode 100644index 000000000..90c088084--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.scss@@ -0,0 +1,46 @@+.sideloadAdvanced {+ padding: var(--space-sm) var(--space-md);+ background: var(--background-darker);+ border: 1px solid var(--panel-border);+ border-radius: var(--radius-sm);+}++.sideloadAdvanced[open] {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+}++.sideloadAdvanced__summary {+ color: var(--text-default);+ font-weight: var(--semibold);+ cursor: pointer;+}++.sideloadAdvanced__hint {+ margin: 0;+ color: var(--text-secondary);+ font-size: var(--text-sm);+ line-height: 1.5;+}++.sideloadAdvanced__winetricks {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-md);+}++.sideloadAdvanced__winetricksText {+ max-width: 65ch;+ color: var(--text-secondary);+ font-size: var(--text-sm);+ line-height: 1.5;+}++@media (max-width: 640px) {+ .sideloadAdvanced__winetricks {+ flex-direction: column;+ align-items: flex-start;+ }+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.stories.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.stories.tsxnew file mode 100644index 000000000..cef1f4cd6--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.stories.tsx@@ -0,0 +1,74 @@+import { useState } from 'react'+import { expect, fn, userEvent } from 'storybook/test'+import type { Meta, StoryObj } from '@storybook/react-vite'++import type { EnviromentVariable } from 'common/types'++import SideloadAdvanced from '.'++function Controlled(args: React.ComponentProps<typeof SideloadAdvanced>) {+ const [environmentOptions, setEnvironmentOptions] = useState<+ EnviromentVariable[]+ >([{ key: 'DXVK_HUD', value: 'fps' }])+ const [umuGameId, setUmuGameId] = useState('')++ return (+ <div style={{ width: 720, maxWidth: '95vw' }}>+ <SideloadAdvanced+ {...args}+ environmentOptions={environmentOptions}+ onEnvironmentOptionsChange={setEnvironmentOptions}+ umuGameId={umuGameId}+ onUmuGameIdChange={setUmuGameId}+ />+ </div>+ )+}++const meta = {+ title: 'Overlays/SideloadAdvanced',+ component: SideloadAdvanced,+ args: {+ canRunWinetricks: true,+ onOpenWinetricks: fn(),+ environmentOptions: [],+ onEnvironmentOptionsChange: fn(),+ umuGameId: '',+ onUmuGameIdChange: fn(),+ showUmuOptions: true+ },+ render: (args) => <Controlled {...args} />,+ parameters: {+ docs: {+ description: {+ component:+ 'Optional advanced settings shown while adding a sideloaded game: Winetricks, the UMU GAMEID and environment variables are applied to the installer and to the app.'+ }+ }+ }+} satisfies Meta<typeof SideloadAdvanced>++export default meta++type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const OpensWinetricks: Story = {+ play: async ({ canvas, args }) => {+ await userEvent.click(canvas.getByText('Advanced'))+ const winetricksButton = await canvas.findByRole('button', {+ name: /Run winetricks/i+ })+ await expect(winetricksButton).toBeEnabled()+ await expect(+ canvas.getByRole('textbox', { name: /UMU GAMEID/i })+ ).toBeVisible()+ await userEvent.click(winetricksButton)+ await expect(args.onOpenWinetricks).toHaveBeenCalled()+ }+}++export const WithoutUmuOptions: Story = {+ args: { showUmuOptions: false }+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.tsxnew file mode 100644index 000000000..73fd5c10d--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadAdvanced/index.tsx@@ -0,0 +1,83 @@+import './index.scss'+import { Wrench } from 'lucide-react'+import { useTranslation } from 'react-i18next'++import type { EnviromentVariable } from 'common/types'+import { Icon, TextInputField } from 'frontend/components/UI'+import Button from 'frontend/components/UI/Button'+import EnvVariablesTable from 'frontend/screens/Settings/components/EnvVariablesTable'++type Props = {+ canRunWinetricks: boolean+ onOpenWinetricks: () => void+ environmentOptions: EnviromentVariable[]+ onEnvironmentOptionsChange: (environmentOptions: EnviromentVariable[]) => void+ umuGameId: string+ onUmuGameIdChange: (umuGameId: string) => void+ showUmuOptions: boolean+}++export default function SideloadAdvanced({+ canRunWinetricks,+ onOpenWinetricks,+ environmentOptions,+ onEnvironmentOptionsChange,+ umuGameId,+ onUmuGameIdChange,+ showUmuOptions+}: Props) {+ const { t } = useTranslation('gamepage')++ return (+ <details className="sideloadAdvanced">+ <summary className="sideloadAdvanced__summary">+ {t('sideload.advanced.title', 'Advanced')}+ </summary>+ <p className="sideloadAdvanced__hint">+ {t(+ 'sideload.advanced.hint',+ 'Optional. Configure Wine dependencies, the UMU GAMEID and environment variables before installing.'+ )}+ </p>++ <div className="sideloadAdvanced__winetricks">+ <span className="sideloadAdvanced__winetricksText">+ {t(+ 'sideload.advanced.winetricks-description',+ 'Install Wine dependencies in the selected prefix. They are used by the installer and by the app after it is added.'+ )}+ </span>+ <Button+ variant="secondary"+ icon={<Icon glyph={Wrench} size="sm" />}+ onClick={onOpenWinetricks}+ disabled={!canRunWinetricks}+ >+ {t('sideload.advanced.winetricks', 'Run winetricks')}+ </Button>+ </div>++ {showUmuOptions && (+ <TextInputField+ htmlId="sideload-umu-game-id"+ label={t('sideload.advanced.umu-id', 'UMU GAMEID')}+ placeholder={t(+ 'sideload.advanced.umu-placeholder',+ 'Leave blank to use the default'+ )}+ value={umuGameId}+ onChange={onUmuGameIdChange}+ info={t(+ 'sideload.advanced.umu-info',+ 'UMU uses GAMEID to apply Proton fixes and store metadata. Set it when the game or launcher is missing from the UMU database.'+ )}+ />+ )}++ <EnvVariablesTable+ environmentOptions={environmentOptions}+ onEnvironmentOptionsChange={onEnvironmentOptionsChange}+ />+ </details>+ )+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/hooks/useInstallerLog.ts b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/hooks/useInstallerLog.tsnew file mode 100644index 000000000..9c54ee655--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/hooks/useInstallerLog.ts@@ -0,0 +1,37 @@+import { useEffect, useRef, useState } from 'react'++/**+ * Polls the install log of a sideloaded app. The backend writes installer+ * output to the app's install log, so this works even before the app itself+ * has been added to the library.+ */+export default function useInstallerLog(appName: string, active: boolean) {+ const [logContent, setLogContent] = useState('')+ const fetching = useRef(false)++ useEffect(() => {+ if (!active) {+ return+ }++ const fetchLog = () => {+ if (fetching.current) {+ return+ }+ fetching.current = true+ window.api+ .getLogContent({ appName, runner: 'sideload', type: 'install' })+ .then((content) => setLogContent(content || ''))+ .catch(() => {})+ .finally(() => {+ fetching.current = false+ })+ }++ fetchLog()+ const interval = setInterval(fetchLog, 1000)+ return () => clearInterval(interval)+ }, [active, appName])++ return logContent+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.scss b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.scssindex 0040fd137..0d04eecec 100644--- a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.scss+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.scss@@ -235,6 +235,25 @@gap: var(--space-md);padding: var(--space-md);+ .protonShortcutsHint {+ margin: 0 0 var(--space-sm);+ color: var(--text-secondary);+ font-size: var(--body-sm);+ }++ .shortcutTag {+ padding: 2px var(--space-xs);+ color: var(--text-secondary);+ font-size: var(--text-xs);+ background: var(--background-darker);+ border-radius: var(--radius-pill);+ }++ .shortcutTile--disabled {+ opacity: 0.45;+ cursor: not-allowed;+ }+.protonShortcutsTitle {margin: 0;font-size: var(--text-md);@@ -332,3 +351,72 @@flex-shrink: 0;}}++.sideloadPresetNote {+ margin: 0 0 var(--space-md);+}++.sideloadPresetInstall {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ padding: var(--space-md);++ &--running {+ height: 100%;+ }++ &__status {+ display: flex;+ align-items: center;+ gap: var(--space-sm);+ font-size: var(--text-lg);+ font-weight: var(--semibold);+ color: var(--text-default);++ .spinner {+ animation: sideloadSpin 1s linear infinite;+ }+ }++ &__hint {+ margin: 0;+ font-size: var(--text-sm);+ line-height: 1.5;+ color: var(--text-secondary);+ }++ &__errorDetail {+ display: block;+ margin-top: var(--space-2xs);+ font-family: var(--monospace-font-family, monospace);+ font-size: var(--text-xs);+ color: var(--text-secondary);+ word-break: break-word;+ }++ &__log {+ width: 100%;+ height: 180px;+ display: flex;+ }++ &__logPlaceholder {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 100%;+ height: 100%;+ border-radius: var(--radius-sm);+ background: #1e1e1e;+ color: var(--text-secondary);+ font-style: italic;+ }++ &__actions {+ display: flex;+ align-items: center;+ gap: var(--space-sm);+ flex-wrap: wrap;+ }+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.tsxindex 357df3359..37877c877 100644--- a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.tsx+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/index.tsx@@ -1,26 +1,50 @@import './index.scss'import short from 'short-uuid'import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'-import { InstallPlatform, WineInstallation, GameInfo } from 'common/types'+import {+ InstallPlatform,+ WineInstallation,+ GameInfo,+ GameSettings,+ EnviromentVariable+} from 'common/types'+import {+ getSideloadPresetAppName,+ getSideloadPresetText,+ type SideloadPreset,+ type SideloadPresetPlatform+} from 'common/sideload_presets'import { ModalContent, ModalFooter } from 'frontend/components/UI/Modal'import Button from 'frontend/components/UI/Button'+import {+ Alert,+ Stepper,+ StepperStep,+ ToggleSwitch+} from 'frontend/components/UI'import { getGameInfo, getGameSettings, writeConfig } from 'frontend/helpers'import React, {useCallback,useContext,useEffect,useMemo,+ useRef,useState} from 'react'import { useTranslation } from 'react-i18next'+import { useNavigate } from 'react-router-dom'import { AvailablePlatforms } from '..'import fallbackImage from 'frontend/assets/heroic_card.jpg'import ContextProvider from 'frontend/state/ContextProvider'-import { Stepper, StepperStep } from 'frontend/components/UI'import MetadataStep from './steps/MetadataStep'import InstallationStep from './steps/InstallationStep'import FinishStep from './steps/FinishStep'import ImagesStep from './steps/ImagesStep'+import PresetInstallStep, {+ type PresetInstallPhase+} from './steps/PresetInstallStep'+import SideloadAdvanced from '../SideloadAdvanced'+import Winetricks from 'frontend/components/UI/Winetricks'type Props = {availablePlatforms: AvailablePlatforms@@ -35,6 +59,9 @@ type Props = {appName?: stringtitle: stringsetTitle: (title: string) => void+ preset?: SideloadPreset+ onBackToPresets?: () => void+ onPresetBusyChange?: (busy: boolean) => void}type SupportedSteps = 'meta' | 'images' | 'compat' | 'install' | 'finish'@@ -51,9 +78,13 @@ export default function SideloadDialog({wineSelector,appName,title,- setTitle+ setTitle,+ preset,+ onBackToPresets,+ onPresetBusyChange}: Props) {const { t } = useTranslation('gamepage')+ const navigate = useNavigate()const [activeStep, setActiveStep] = useState(0)const [selectedExe, setSelectedExe] = useState('')const [gameUrl, setGameUrl] = useState('')@@ -61,19 +92,83 @@ export default function SideloadDialog({const [launchFullScreen, setLaunchFullScreen] = useState(false)const [imageUrl, setImageUrl] = useState('')const [heroUrl, setHeroUrl] = useState('')- const [app_name, setApp_name] = useState(appName ?? '')+ const [app_name, setApp_name] = useState(+ preset ? getSideloadPresetAppName(preset) : (appName ?? '')+ )const [runningSetup, setRunningSetup] = useState(false)const [gameInfo, setGameInfo] = useState<Partial<GameInfo>>({})const [addingApp, setAddingApp] = useState(false)const [hasSgdbKey, setHasSgdbKey] = useState(false)+ const [environmentOptions, setEnvironmentOptions] = useState<+ EnviromentVariable[]+ >([])+ const [umuGameId, setUmuGameId] = useState('')+ const [winetricksOpen, setWinetricksOpen] = useState(false)+ const [presetPhase, setPresetPhase] = useState<PresetInstallPhase>('idle')+ const [installSilently, setInstallSilently] = useState(true)+ const [presetDownloadProgress, setPresetDownloadProgress] = useState(0)+ const [presetError, setPresetError] = useState('')const editMode = Boolean(appName)+ const presetStarted = useRef(false)+ const presetRunId = useRef(0)- const { refreshLibrary, platform } = useContext(ContextProvider)+ const { refreshLibrary, platform, showDialogModal } =+ useContext(ContextProvider)const appPlatform = gameInfo.install?.platform || platformToInstall+ const activePresetId = preset?.id+ const presetText = preset ? getSideloadPresetText(t, preset) : undefined++ const withAdvancedSettings = useCallback(+ (settings: GameSettings): GameSettings => ({+ ...settings,+ winePrefix,+ wineVersion: wineVersion || settings.wineVersion,+ wineCrossoverBottle: crossoverBottle,+ ...(environmentOptions.length+ ? { enviromentOptions: environmentOptions }+ : {}),+ ...(umuGameId.trim() ? { umuGameId } : {})+ }),+ [winePrefix, wineVersion, crossoverBottle, environmentOptions, umuGameId]+ )++ const getConfigOverride = useCallback(+ (settings: GameSettings): Partial<GameSettings> => {+ // Only write per-game values the user explicitly set. Empty values must+ // inherit the global configuration instead of freezing it.+ const advanced = Object.fromEntries(+ Object.entries(settings).filter(+ ([key]) => key !== 'enviromentOptions' && key !== 'umuGameId'+ )+ ) as Partial<GameSettings>++ return {+ ...advanced,+ ...(environmentOptions.length+ ? { enviromentOptions: environmentOptions }+ : {}),+ ...(umuGameId.trim() ? { umuGameId } : {})+ }+ },+ [environmentOptions, umuGameId]+ )++ const perGameSettings = useMemo(+ () => ({+ winePrefix,+ wineVersion,+ wineCrossoverBottle: crossoverBottle,+ ...(environmentOptions.length+ ? { enviromentOptions: environmentOptions }+ : {}),+ ...(umuGameId.trim() ? { umuGameId } : {})+ }),+ [winePrefix, wineVersion, crossoverBottle, environmentOptions, umuGameId]+ )useEffect(() => {- window.api.steamgriddb.hasApiKey().then(setHasSgdbKey)+ void window.api.steamgriddb.hasApiKey().then(setHasSgdbKey)if (appName) {void getGameInfo(appName, 'sideload').then((info) => {@@ -111,11 +206,67 @@ export default function SideloadDialog({setImageUrl(art_square || '')setHeroUrl(art_cover && art_cover !== art_square ? art_cover : '')})- } else {- setApp_name(short.generate().toString())+ return}++ if (preset) {+ setApp_name(getSideloadPresetAppName(preset))+ if (preset.web) {+ setGameUrl(preset.web.url)+ setCustomUserAgent(preset.web.userAgent ?? '')+ setLaunchFullScreen(preset.web.launchFullScreen ?? false)+ }+ return+ }++ setApp_name(short.generate().toString())+ // Only run on mount: the dialog is remounted for every new app/preset.+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [])+ useEffect(() => {+ if (!activePresetId || appName) {+ return+ }++ let active = true+ window.api+ .getSideloadPresetArtwork(activePresetId)+ .then(({ square, hero }) => {+ if (!active) {+ return+ }+ setImageUrl(square)+ setHeroUrl(hero)+ })+ .catch(() => {})++ return () => {+ active = false+ }+ }, [activePresetId, appName])++ useEffect(() => {+ if (!activePresetId) {+ return+ }++ return window.api.onPresetDownloadProgress((_, { presetId, progress }) => {+ if (presetId === activePresetId) {+ setPresetDownloadProgress(progress)+ }+ })+ }, [activePresetId])++ useEffect(+ () => () => {+ // Invalidate any download/install chain that is still in flight when+ // the dialog closes.+ presetRunId.current+++ },+ []+ )+async function handleInstall(): Promise<void> {if (!wineSelectionValid) return@@ -134,17 +285,14 @@ export default function SideloadDialog({canRunOffline: true,browserUrl: gameUrl,customUserAgent,- launchFullScreen+ launchFullScreen,+ presetId: preset?.id})if (!editMode) {await window.api.writeConfig({appName: app_name,- config: {- winePrefix,- wineVersion,- wineCrossoverBottle: crossoverBottle- }+ config: perGameSettings})}@@ -154,6 +302,28 @@ export default function SideloadDialog({checkForUpdates: true})setAddingApp(false)++ // When a launcher preset is added, check right away whether the prefix+ // already contains games. If it does, take the user to the launcher page+ // with the scan dialog open; if not, just close without an empty dialog.+ if (preset?.kind === 'launcher' && !editMode) {+ try {+ const scan = await window.api.scanSideloadPresetGames(preset.id)+ if (scan.games.length > 0) {+ const info = await window.api.getGameInfo(app_name, 'sideload')+ if (info) {+ backdropClick()+ navigate(`/gamepage/sideload/${app_name}`, {+ state: { gameInfo: info, autoScanGames: true }+ })+ return+ }+ }+ } catch (scanError) {+ window.api.logError(String(scanError))+ }+ }+return backdropClick()}@@ -204,19 +374,16 @@ export default function SideloadDialog({if (!gameSettings) {return}+ const settingsWithAdvanced = withAdvancedSettings(gameSettings)await writeConfig({appName: app_name,- config: { ...gameSettings, winePrefix, wineVersion }+ config: getConfigOverride(settingsWithAdvanced)})await window.api.runWineCommand({commandParts: [exeToRun],wait: true,protonVerb: 'run',- gameSettings: {- ...gameSettings,- winePrefix,- wineVersion: wineVersion || gameSettings.wineVersion- },+ gameSettings: settingsWithAdvanced,logToApp: { appName: app_name, runner: 'sideload' }})setRunningSetup(false)@@ -229,6 +396,119 @@ export default function SideloadDialog({return}+ async function detectAndContinue() {+ if (!preset) {+ return+ }++ setPresetPhase('detecting')+ const executable = await window.api.detectSideloadPresetExecutable(+ preset.id+ )++ if (executable) {+ setSelectedExe(executable)+ setPresetPhase('done')+ goToStep('finish')+ return+ }++ setPresetError('not-found')+ setPresetPhase('error')+ }++ async function startPresetInstall(silentOverride?: boolean) {+ if (!preset?.launcher) {+ return+ }++ const runId = ++presetRunId.current+ const isStale = () => presetRunId.current !== runId++ setPresetError('')+ setPresetDownloadProgress(0)+ setPresetPhase('downloading')++ try {+ await window.api.downloadSideloadPresetInstaller(preset.id)+ if (isStale()) {+ return+ }++ const gameSettings = await getGameSettings(app_name, 'sideload')+ if (!gameSettings) {+ throw new Error('Missing game settings')+ }+ // Windows installers run natively, so no Wine settings are needed there.+ if (platform !== 'win32') {+ await writeConfig({+ appName: app_name,+ config: getConfigOverride(withAdvancedSettings(gameSettings))+ })+ }+ if (isStale()) {+ return+ }++ setPresetPhase('running')+ const result = await window.api.runSideloadPresetInstaller(+ preset.id,+ silentOverride ?? installSilently+ )+ if (isStale()) {+ return+ }+ if (result.status === 'error') {+ throw new Error(result.error ?? 'installer-failed')+ }++ await detectAndContinue()+ } catch (error) {+ if (isStale()) {+ return+ }+ setPresetError(String(error))+ setPresetPhase('error')+ }+ }++ function handlePresetContinue() {+ presetRunId.current+++ void detectAndContinue()+ }++ function handlePresetRetry() {+ presetStarted.current = true+ void startPresetInstall()+ }++ function handlePresetRetryInteractive() {+ presetStarted.current = true+ setInstallSilently(false)+ void startPresetInstall(false)+ }++ function handleSelectExecutableManually() {+ goToStep('finish')+ }++ async function handleOpenWinetricks() {+ if (!app_name) {+ return+ }++ const gameSettings = await getGameSettings(app_name, 'sideload')+ if (!gameSettings) {+ return+ }++ await writeConfig({+ appName: app_name,+ config: getConfigOverride(withAdvancedSettings(gameSettings))+ })+ setWinetricksOpen(true)+ }+function platformIcon() {const platformIcon = availablePlatforms.filter((p) => p.name === appPlatform.replace('Mac', 'macOS')@@ -267,25 +547,95 @@ export default function SideloadDialog({}}+ const presetStepInfo: Record<SupportedSteps, StepperStep> = {+ ...stepInfo,+ compat: {+ title:+ platform === 'win32'+ ? t('sideload.presets.step.install-options', 'Installation options')+ : t('sideload.presets.step.setup', 'Setup'),+ description:+ platform === 'win32'+ ? t(+ 'sideload.presets.step.install-options-desc',+ 'Silent installation'+ )+ : t('sideload.presets.step.setup-desc', 'Wine prefix and version')+ },+ install: {+ title: t('sideload.presets.step.install', 'Installation'),+ description: t(+ 'sideload.presets.step.install-desc',+ 'Download and run the installer'+ )+ },+ finish: {+ title: t('sideload.presets.step.options', 'Options'),+ description: t(+ 'sideload.presets.step.options-desc',+ 'Executable and launch options'+ )+ }+ }+const flowSteps: SupportedSteps[] = useMemo(() => {+ if (preset) {+ const steps: SupportedSteps[] = []+ if (+ preset.kind === 'launcher' &&+ (platform !== 'win32' || preset.launcher?.installer.silentArgs)+ ) {+ steps.push('compat')+ }+ if (preset.kind === 'launcher') {+ steps.push('install')+ }+ steps.push('finish')+ return steps+ }+const steps: SupportedSteps[] = ['meta', 'images']if (!editMode && shouldShowRunExe) {steps.push('compat', 'install')}steps.push('finish')return steps- }, [shouldShowRunExe])+ }, [preset, platform, editMode, shouldShowRunExe])++ useEffect(() => {+ if (!preset?.launcher) {+ return+ }+ if (flowSteps[activeStep] !== 'install') {+ return+ }+ if (presetStarted.current) {+ return+ }+ presetStarted.current = true+ void startPresetInstall()+ // startPresetInstall reads the current prefix/Wine state. It is guarded by+ // presetStarted, so re-running this effect does not restart the installer.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [activeStep, flowSteps, preset])const numberOfSteps = flowSteps.lengthconst lastStepIndex = numberOfSteps - 1+ function goToStep(step: SupportedSteps) {+ const index = flowSteps.indexOf(step)+ if (index !== -1) {+ setActiveStep(index)+ }+ }+function handlePreviousStepClick() {setActiveStep(Math.max(activeStep - 1, 0))}function handleNextStepClick() {if (activeStep === lastStepIndex) {- handleInstall()+ void handleInstall()return}setActiveStep(Math.min(activeStep + 1, lastStepIndex))@@ -314,8 +664,79 @@ export default function SideloadDialog({/>)case 'compat':- return <div className="sideloadCompatForm">{wineSelector}</div>+ return (+ <div className="sideloadCompatForm">+ {preset?.requiresCrossover?.includes(+ platform as SideloadPresetPlatform+ ) && (+ <Alert variant="warning" className="sideloadPresetNote">+ {t(+ 'sideload.presets.macos-requires-crossover',+ 'macOS: this launcher needs the commercial CrossOver version. Free Wine builds can install it, but its window does not open.'+ )}+ </Alert>+ )}+ {preset?.launcher?.installer.silentArgs && (+ <ToggleSwitch+ htmlId="sideload-silent-install"+ title={t(+ 'sideload.presets.silent-install.title',+ 'Silent installation'+ )}+ description={t(+ 'sideload.presets.silent-install.description',+ 'Run the installer without showing its window. Turn this off if the silent install fails.'+ )}+ value={installSilently}+ handleChange={() => setInstallSilently(!installSilently)}+ />+ )}+ {platform !== 'win32' && (+ <>+ {wineSelector}+ <SideloadAdvanced+ canRunWinetricks={Boolean(+ wineVersion && winePrefix && winePrefix !== '...'+ )}+ onOpenWinetricks={() => void handleOpenWinetricks()}+ environmentOptions={environmentOptions}+ onEnvironmentOptionsChange={setEnvironmentOptions}+ umuGameId={umuGameId}+ onUmuGameIdChange={setUmuGameId}+ showUmuOptions={+ platform === 'linux' && wineVersion?.type === 'proton'+ }+ />+ </>+ )}+ </div>+ )case 'install':+ if (preset?.launcher) {+ return (+ <PresetInstallStep+ appName={app_name}+ presetTitle={preset.title}+ phase={presetPhase}+ downloadProgress={presetDownloadProgress}+ error={presetError}+ onContinue={handlePresetContinue}+ onRetry={handlePresetRetry}+ onCheckAgain={() => void detectAndContinue()}+ onSelectManually={handleSelectExecutableManually}+ onCancel={handleCancelPreset}+ showInstallerNotice={Boolean(+ preset?.installerOpensApp?.includes(+ platform as SideloadPresetPlatform+ )+ )}+ canRetryInteractive={Boolean(+ preset?.launcher?.installer.silentArgs+ )}+ onRetryInteractive={handlePresetRetryInteractive}+ />+ )+ }return (<InstallationStepappName={app_name}@@ -328,29 +749,58 @@ export default function SideloadDialog({)case 'finish':return (- <FinishStep- appPlatform={appPlatform}- gameUrl={gameUrl}- setGameUrl={setGameUrl}- customUserAgent={customUserAgent}- setCustomUserAgent={setCustomUserAgent}- launchFullScreen={launchFullScreen}- setLaunchFullScreen={setLaunchFullScreen}- winePrefix={winePrefix}- wineVersion={wineVersion}- selectedExe={selectedExe}- setSelectedExe={setSelectedExe}- fileFilters={fileFilters}- />+ <>+ {presetText?.note && (+ <Alert variant="info" className="sideloadPresetNote">+ {presetText.note}+ </Alert>+ )}+ {preset?.kind === 'launcher' && (+ <Alert variant="info" className="sideloadPresetNote">+ {t(+ 'sideload.presets.next-steps',+ 'Open {{title}}, sign in, install a game there, then return to this page and use "Scan games" to add it to Heroic.',+ { title: preset.title }+ )}+ </Alert>+ )}+ {preset?.kind === 'launcher' && platform === 'win32' && (+ <Alert variant="warning" className="sideloadPresetNote">+ {t(+ 'sideload.presets.scan-platform-note',+ 'Scanning installed games is currently available on Linux and macOS only. On Windows, add games with the custom flow for now.'+ )}+ </Alert>+ )}+ <FinishStep+ appPlatform={appPlatform}+ gameUrl={gameUrl}+ setGameUrl={setGameUrl}+ customUserAgent={customUserAgent}+ setCustomUserAgent={setCustomUserAgent}+ launchFullScreen={launchFullScreen}+ setLaunchFullScreen={setLaunchFullScreen}+ winePrefix={winePrefix}+ wineVersion={wineVersion}+ selectedExe={selectedExe}+ setSelectedExe={setSelectedExe}+ fileFilters={fileFilters}+ launcherMode={preset?.kind === 'launcher'}+ presetTitle={preset?.title}+ />+ </>)}}const showNextButton = useMemo(() => {const step = flowSteps[activeStep]- if (step === 'install') return false+ if (step === 'install') {+ // When the executable was already detected, allow going back to Options.+ return preset?.kind === 'launcher' && presetPhase === 'done'+ }return true- }, [flowSteps, activeStep])+ }, [flowSteps, activeStep, preset, presetPhase])const noAppEntryPoint =(appPlatform !== 'Browser' && !selectedExe) ||@@ -358,14 +808,80 @@ export default function SideloadDialog({const lastStep = lastStepIndex === activeStep+ const presetBusy =+ preset?.kind === 'launcher' &&+ (presetPhase === 'downloading' ||+ presetPhase === 'running' ||+ presetPhase === 'detecting')++ useEffect(() => {+ onPresetBusyChange?.(presetBusy)+ }, [presetBusy, onPresetBusyChange])++ const cancelPresetRun = () => {+ presetRunId.current+++ presetStarted.current = false+ setPresetPhase('idle')+ setPresetError('')+ setPresetDownloadProgress(0)++ if (activeStep > 0) {+ setActiveStep(activeStep - 1)+ } else if (onBackToPresets) {+ onBackToPresets()+ } else {+ backdropClick()+ }+ }++ const handleCancelPreset = () => {+ if (!presetBusy) {+ cancelPresetRun()+ return+ }++ showDialogModal({+ title: t(+ 'sideload.presets.closing.title',+ 'Installation is still running'+ ),+ message: t(+ 'sideload.presets.closing.message',+ 'The installer is still running. Close the window anyway? The installer may keep running in the background.'+ ),+ type: 'MESSAGE',+ buttons: [+ {+ text: t('sideload.presets.closing.continue', 'Close anyway'),+ variant: 'primary',+ onClick: cancelPresetRun+ },+ {+ text: t('sideload.presets.closing.cancel', 'Keep installing')+ }+ ]+ })+ }++ const presetInstallStep =+ preset?.kind === 'launcher' && flowSteps[activeStep] === 'install'++ const canReturnToPresets = Boolean(+ preset && onBackToPresets && activeStep === 0+ )+return (<><ModalContent className="sideloadDialog">- <Stepper- className="sideloadStepper"- activeStep={activeStep}- steps={flowSteps.map((step) => stepInfo[step])}- />+ {flowSteps.length > 1 && (+ <Stepper+ className="sideloadStepper"+ activeStep={activeStep}+ steps={flowSteps.map((step) =>+ preset ? presetStepInfo[step] : stepInfo[step]+ )}+ />+ )}<div className="stepContentRenderer">{renderDialogContent(flowSteps[activeStep])}</div>@@ -378,8 +894,22 @@ export default function SideloadDialog({<div className="sideloadFooterButtons"><Buttonvariant="ghost"- onClick={handlePreviousStepClick}- disabled={addingApp || runningSetup || activeStep === 0}+ onClick={() => {+ if (presetInstallStep) {+ handleCancelPreset()+ return+ }+ if (canReturnToPresets && onBackToPresets) {+ onBackToPresets()+ return+ }+ handlePreviousStepClick()+ }}+ disabled={+ addingApp ||+ runningSetup ||+ (activeStep === 0 && !canReturnToPresets)+ }>{t('button.back', 'Back')}</Button>@@ -390,7 +920,8 @@ export default function SideloadDialog({disabled={(lastStep && (noAppEntryPoint || !wineSelectionValid)) ||addingApp ||- runningSetup+ runningSetup ||+ presetBusy}>{lastStep@@ -400,6 +931,13 @@ export default function SideloadDialog({)}</div></ModalFooter>+ {winetricksOpen && (+ <Winetricks+ appName={app_name}+ runner="sideload"+ onClose={() => setWinetricksOpen(false)}+ />+ )}</>)}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.stories.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.stories.tsxnew file mode 100644index 000000000..c7920c5df--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.stories.tsx@@ -0,0 +1,88 @@+import { expect, fn } from 'storybook/test'+import type { Meta, StoryObj } from '@storybook/react-vite'++import type { WineInstallation } from 'common/types'+import type { ParsedProtonShorctut } from 'common/types/proton_shorctuts'++import FinishStep from './FinishStep'++const shortcuts: ParsedProtonShorctut[] = [+ {+ name: 'Battle.net',+ executable:+ '/home/user/Games/Heroic/Prefixes/default/Battle.net/drive_c/Program Files (x86)/Battle.net/Battle.net.exe'+ },+ {+ name: 'Hearthstone',+ executable:+ '/home/user/Games/Heroic/Prefixes/default/Battle.net/drive_c/Program Files (x86)/Hearthstone/Hearthstone.exe'+ }+]++const proton = {+ bin: '/usr/bin/proton',+ name: 'GE-Proton',+ type: 'proton'+} satisfies WineInstallation++const meta = {+ title: 'Overlays/FinishStep',+ component: FinishStep,+ args: {+ appPlatform: 'Windows',+ gameUrl: '',+ setGameUrl: fn(),+ customUserAgent: '',+ setCustomUserAgent: fn(),+ launchFullScreen: false,+ setLaunchFullScreen: fn(),+ winePrefix: '/home/user/Games/Heroic/Prefixes/default/Battle.net',+ wineVersion: proton,+ selectedExe: shortcuts[0].executable,+ setSelectedExe: fn(),+ fileFilters: () => [{ name: 'Executables', extensions: ['exe'] }],+ launcherMode: true,+ presetTitle: 'Battle.net'+ },+ decorators: [+ (Story) => {+ window.platform = 'linux'+ window.api.getProtonShortcuts = async () => shortcuts+ return (+ <div style={{ width: 720, maxWidth: '95vw' }}>+ <Story />+ </div>+ )+ }+ ]+} satisfies Meta<typeof FinishStep>++export default meta++type Story = StoryObj<typeof meta>++export const LauncherExecutable: Story = {+ play: async ({ canvas }) => {+ await expect(canvas.getByText(/choose the launcher/i)).toBeInTheDocument()+ await expect(+ canvas.getByRole('button', { name: /Battle.net/ })+ ).toBeEnabled()+ await expect(+ canvas.getByRole('button', { name: /Hearthstone/ })+ ).toBeDisabled()+ await expect(canvas.getByText('Game executable')).toBeInTheDocument()+ }+}++export const ManualSelectionKeepsAllOptions: Story = {+ args: {+ launcherMode: false,+ presetTitle: undefined,+ selectedExe: shortcuts[0].executable+ },+ play: async ({ canvas }) => {+ await expect(+ canvas.getByRole('button', { name: /Hearthstone/ })+ ).toBeEnabled()+ }+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.tsxindex 1cf0f5431..acd80501f 100644--- a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.tsx+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/FinishStep.tsx@@ -2,6 +2,7 @@ import { CircleCheck, MonitorX } from 'lucide-react'import { InstallPlatform, WineInstallation } from 'common/types'import { ParsedProtonShorctut } from 'common/types/proton_shorctuts'import {+ Alert,CachedImage,EmptyState,Icon,@@ -26,6 +27,8 @@ type Props = {setSelectedExe: (val: string) => voidselectedExe: stringfileFilters: (installPlatform: InstallPlatform) => Electron.FileFilter[]+ launcherMode?: boolean+ presetTitle?: string}export default function FinishStep({@@ -40,7 +43,9 @@ export default function FinishStep({setGameUrl,setCustomUserAgent,setLaunchFullScreen,- fileFilters+ fileFilters,+ launcherMode = false,+ presetTitle}: Props) {const { t } = useTranslation('gamepage')@@ -71,11 +76,23 @@ export default function FinishStep({<div className="sideloadFinish">{showSideloadExe && (<>+ {launcherMode && (+ <Alert variant="warning" className="sideloadLauncherExeNotice">+ {t(+ 'sideload.info.launcher-exe',+ 'Heroic identified the executables in this prefix, but this entry must launch the launcher itself ({{title}}). Do not select a game executable here; installed games can be added later with Scan games on the launcher page.',+ { title: presetTitle ?? '' }+ )}+ </Alert>+ )}+{window.platform === 'linux' && appPlatform === 'Windows' && (<ProtonShorcutsSectionprotonShortcuts={protonShortcuts}selectedExe={selectedExe}setSelectedExe={setSelectedExe}+ launcherMode={launcherMode}+ launcherTitle={presetTitle}/>)}@@ -83,12 +100,30 @@ export default function FinishStep({type="file"onPathChange={setSelectedExe}path={selectedExe}- placeholder={t('sideload.info.exe', 'Select Executable')}- pathDialogTitle={t('box.sideload.exe', 'Select Executable')}+ placeholder={+ launcherMode+ ? t(+ 'sideload.info.launcher-exe-placeholder',+ 'Launcher executable'+ )+ : t('sideload.info.exe', 'Select Executable')+ }+ pathDialogTitle={+ launcherMode+ ? t(+ 'box.sideload.launcher-exe',+ 'Select the launcher executable'+ )+ : t('box.sideload.exe', 'Select Executable')+ }pathDialogDefaultPath={winePrefix}pathDialogFilters={fileFilters(appPlatform)}htmlId="sideload-exe"- label={t('sideload.info.exe', 'Select Executable')}+ label={+ launcherMode+ ? t('sideload.info.launcher-exe-label', 'Launcher executable')+ : t('sideload.info.exe', 'Select Executable')+ }noDeleteButton/></>@@ -134,12 +169,16 @@ interface ProtonShorcutsSectionProps {protonShortcuts: ParsedProtonShorctut[]selectedExe: stringsetSelectedExe: (val: string) => void+ launcherMode?: boolean+ launcherTitle?: string}function ProtonShorcutsSection({protonShortcuts,selectedExe,- setSelectedExe+ setSelectedExe,+ launcherMode = false,+ launcherTitle}: ProtonShorcutsSectionProps) {const { t } = useTranslation('gamepage')@@ -147,11 +186,25 @@ function ProtonShorcutsSection({<>{!!protonShortcuts.length && (<h5 className="protonShortcutsTitle">- {t('sideload.info.proton-shortcuts', 'Detected software')}+ {launcherMode+ ? t(+ 'sideload.info.launcher-shortcuts-title',+ 'Detected software — choose the launcher'+ )+ : t('sideload.info.proton-shortcuts', 'Detected software')}</h5>)}+ {launcherMode && (+ <p className="protonShortcutsHint">+ {t(+ 'sideload.info.launcher-shortcuts-hint',+ 'Heroic found the executables below. Keep the launcher ({{title}}) selected; game executables are added later with Scan games.',+ { title: launcherTitle ?? '' }+ )}+ </p>+ )}<div className="proton-shortcuts">- {!protonShortcuts.length && (+ {!protonShortcuts.length && !selectedExe && (<EmptyStateglyph={MonitorX}title={t(@@ -164,33 +217,64 @@ function ProtonShorcutsSection({)}/>)}- {protonShortcuts.map((shortcut) => (- <Button- key={shortcut.name}- variant="ghost"- className={- selectedExe === shortcut.executable- ? 'shortcutTile shortcutTile--selected'- : 'shortcutTile'- }- onClick={() => setSelectedExe(shortcut.executable)}- >- {shortcut.icon && (- <CachedImage- className="shortcutImage"- src={`file://${shortcut.icon}`}- />- )}- <span className="shortcutName">{shortcut.name}</span>- {selectedExe === shortcut.executable && (- <Icon- glyph={CircleCheck}- size="md"- className="shortcutSelectedIcon"- />- )}- </Button>- ))}+ {protonShortcuts.map((shortcut) => {+ const isSelected = selectedExe === shortcut.executable+ const isLauncherShortcut =+ !launcherMode ||+ shortcut.name.localeCompare(launcherTitle ?? '', undefined, {+ sensitivity: 'base'+ }) === 0+ const hasLauncherTile =+ !launcherMode ||+ protonShortcuts.some(+ (candidate) =>+ candidate.name.localeCompare(launcherTitle ?? '', undefined, {+ sensitivity: 'base'+ }) === 0+ )+ const isGameExecutable =+ launcherMode && hasLauncherTile && !isLauncherShortcut++ return (+ <Button+ key={shortcut.name}+ variant="ghost"+ className={[+ 'shortcutTile',+ isSelected ? 'shortcutTile--selected' : '',+ isGameExecutable ? 'shortcutTile--disabled' : ''+ ]+ .filter(Boolean)+ .join(' ')}+ disabled={isGameExecutable}+ onClick={() => {+ if (!isGameExecutable) {+ setSelectedExe(shortcut.executable)+ }+ }}+ >+ {shortcut.icon && (+ <CachedImage+ className="shortcutImage"+ src={`file://${shortcut.icon}`}+ />+ )}+ <span className="shortcutName">{shortcut.name}</span>+ {isGameExecutable && (+ <span className="shortcutTag">+ {t('sideload.info.game-executable', 'Game executable')}+ </span>+ )}+ {isSelected && (+ <Icon+ glyph={CircleCheck}+ size="md"+ className="shortcutSelectedIcon"+ />+ )}+ </Button>+ )+ })}</div></>)diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/InstallationStep.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/InstallationStep.tsxindex c6e915554..a948d8889 100644--- a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/InstallationStep.tsx+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/InstallationStep.tsx@@ -1,9 +1,9 @@-import { useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoaderCircle, MonitorDown, SkipForward } from 'lucide-react'import Button from 'frontend/components/UI/Button'import { Icon, LogPanel } from 'frontend/components/UI'import HorizontalSelector from 'frontend/components/UI/HorizontalSelector'+import useInstallerLog from '../hooks/useInstallerLog'type Props = {appName: string@@ -23,28 +23,7 @@ export default function InstallationStep({runningSetup}: Props) {const { t } = useTranslation('gamepage')- const [logContent, setLogContent] = useState('')- const fetching = useRef(false)-- useEffect(() => {- if (!runningSetup) return-- const fetchLog = () => {- if (fetching.current) return- fetching.current = true- window.api- .getLogContent({ appName, runner: 'sideload', type: 'install' })- .then((content) => setLogContent(content || ''))- .catch(() => {})- .finally(() => {- fetching.current = false- })- }-- fetchLog()- const interval = setInterval(fetchLog, 1000)- return () => clearInterval(interval)- }, [runningSetup, appName])+ const logContent = useInstallerLog(appName, runningSetup)if (runningSetup) {return (diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/PresetInstallStep.stories.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/PresetInstallStep.stories.tsxnew file mode 100644index 000000000..8882b3398--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/PresetInstallStep.stories.tsx@@ -0,0 +1,73 @@+import { expect, fn, userEvent } from 'storybook/test'+import type { Meta, StoryObj } from '@storybook/react-vite'++import PresetInstallStep from './PresetInstallStep'++const meta = {+ title: 'Overlays/PresetInstallStep',+ component: PresetInstallStep,+ args: {+ appName: 'preset-battlenet',+ presetTitle: 'Battle.net',+ phase: 'downloading',+ downloadProgress: 42,+ onContinue: fn(),+ onRetry: fn(),+ onCheckAgain: fn(),+ onSelectManually: fn(),+ onCancel: fn(),+ canRetryInteractive: true,+ onRetryInteractive: fn()+ },+ render: (args) => (+ <div style={{ width: 720, maxWidth: '95vw' }}>+ <PresetInstallStep {...args} />+ </div>+ ),+ parameters: {+ docs: {+ description: {+ component:+ 'Installer step used by launcher presets. It shows download progress, the live installer log, and recovery actions when the executable cannot be found.'+ }+ }+ }+} satisfies Meta<typeof PresetInstallStep>++export default meta++type Story = StoryObj<typeof meta>++export const Downloading: Story = {+ play: async ({ canvas }) => {+ await expect(+ canvas.getByText(/Downloading the installer/i)+ ).toBeInTheDocument()+ await expect(canvas.getByText('42%')).toBeInTheDocument()+ }+}++export const Running: Story = {+ args: { phase: 'running' }+}++export const NotFound: Story = {+ args: { phase: 'error', error: 'not-found' },+ play: async ({ canvas }) => {+ await expect(canvas.getByText(/Check again/i)).toBeInTheDocument()+ }+}++export const InstallerError: Story = {+ args: { phase: 'error', error: 'installer-exit-1' }+}++export const RetriesInteractively: Story = {+ args: { phase: 'error', error: 'not-found' },+ play: async ({ canvas, args }) => {+ await userEvent.click(+ canvas.getByRole('button', { name: /Run installer interactively/i })+ )+ await expect(args.onRetryInteractive).toHaveBeenCalled()+ }+}diff --git a/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/PresetInstallStep.tsx b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/PresetInstallStep.tsxnew file mode 100644index 000000000..18e6fd4b2--- /dev/null+++ b/src/frontend/screens/Library/components/InstallModal/SideloadDialog/steps/PresetInstallStep.tsx@@ -0,0 +1,257 @@+import {+ CircleCheck,+ LoaderCircle,+ MonitorDown,+ Search,+ TriangleAlert+} from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { Alert, Icon, LogPanel, ProgressBar } from 'frontend/components/UI'+import Button from 'frontend/components/UI/Button'++import useInstallerLog from '../hooks/useInstallerLog'++export type PresetInstallPhase =+ | 'idle'+ | 'downloading'+ | 'running'+ | 'detecting'+ | 'done'+ | 'error'++type Props = {+ appName: string+ presetTitle: string+ phase: PresetInstallPhase+ downloadProgress: number+ error?: string+ onContinue: () => void+ onRetry: () => void+ onCheckAgain: () => void+ onSelectManually: () => void+ onCancel: () => void+ canRetryInteractive: boolean+ onRetryInteractive: () => void+ showInstallerNotice?: boolean+}++export default function PresetInstallStep({+ appName,+ presetTitle,+ phase,+ downloadProgress,+ error,+ onContinue,+ onRetry,+ onCheckAgain,+ onSelectManually,+ onCancel,+ canRetryInteractive,+ onRetryInteractive,+ showInstallerNotice = false+}: Props) {+ const { t } = useTranslation('gamepage')+ const logContent = useInstallerLog(appName, phase === 'running')+ const cancelButton = (+ <Button variant="ghost" onClick={onCancel}>+ {t('sideload.presets.cancel', 'Cancel')}+ </Button>+ )++ if (phase === 'done') {+ return (+ <div className="sideloadPresetInstall">+ <div className="sideloadPresetInstall__status">+ <Icon glyph={CircleCheck} size="lg" />+ <span>+ {t(+ 'sideload.presets.done',+ 'Executable found, you can finish the setup.'+ )}+ </span>+ </div>+ <p className="sideloadPresetInstall__hint">+ {t(+ 'sideload.presets.next-steps',+ 'Open {{title}}, sign in, install a game there, then return to this page and use "Scan games" to add it to Heroic.',+ { title: presetTitle }+ )}+ </p>+ </div>+ )+ }++ if (phase === 'error') {+ const notFound = error === 'not-found'+ return (+ <div className="sideloadPresetInstall">+ <Alert+ variant="error"+ title={+ notFound+ ? t(+ 'sideload.presets.not-found.title',+ "We couldn't find the installed app"+ )+ : t('sideload.presets.error.title', 'Something went wrong')+ }+ >+ {notFound+ ? t(+ 'sideload.presets.not-found.description',+ "The installer finished, but Heroic couldn't locate {{title}} in the Wine prefix. You can try again, or select the executable manually.",+ { title: presetTitle }+ )+ : t(+ 'sideload.presets.error.description',+ 'Heroic could not finish setting up {{title}}. You can try again or select the executable manually.',+ { title: presetTitle }+ )}+ {!notFound && error ? (+ <span className="sideloadPresetInstall__errorDetail">{error}</span>+ ) : null}+ </Alert>+ <div className="sideloadPresetInstall__actions">+ {notFound ? (+ <Button variant="primary" onClick={onCheckAgain}>+ {t('sideload.presets.check-again', 'Check again')}+ </Button>+ ) : (+ <Button variant="secondary" onClick={onRetry}>+ {t('sideload.presets.retry', 'Try again')}+ </Button>+ )}+ <Button+ variant={notFound ? 'secondary' : 'primary'}+ onClick={onSelectManually}+ >+ {t(+ 'sideload.presets.select-manually',+ 'Select executable manually'+ )}+ </Button>+ {canRetryInteractive && (+ <Button variant="ghost" onClick={onRetryInteractive}>+ {t(+ 'sideload.presets.retry-interactive',+ 'Run installer interactively'+ )}+ </Button>+ )}+ {cancelButton}+ </div>+ </div>+ )+ }++ if (phase === 'downloading') {+ return (+ <div className="sideloadPresetInstall">+ <div className="sideloadPresetInstall__status">+ <Icon glyph={MonitorDown} size="lg" />+ <span>+ {t('sideload.presets.downloading', 'Downloading the installer…')}+ </span>+ </div>+ <ProgressBar+ value={downloadProgress}+ showValue+ size="md"+ label={t(+ 'sideload.presets.downloading',+ 'Downloading the installer…'+ )}+ />+ <p className="sideloadPresetInstall__hint">+ {t(+ 'sideload.presets.downloading-hint',+ 'Heroic downloads {{title}} directly from the official vendor endpoint. Nothing is bundled with the app.',+ { title: presetTitle }+ )}+ </p>+ <div className="sideloadPresetInstall__actions">{cancelButton}</div>+ </div>+ )+ }++ if (phase === 'detecting') {+ return (+ <div className="sideloadPresetInstall">+ <div className="sideloadPresetInstall__status">+ <Icon glyph={Search} size="lg" />+ <span>+ {t(+ 'sideload.presets.detecting',+ 'Looking for the installed application…'+ )}+ </span>+ </div>+ <div className="sideloadPresetInstall__actions">{cancelButton}</div>+ </div>+ )+ }++ if (phase === 'running') {+ return (+ <div className="sideloadPresetInstall sideloadPresetInstall--running">+ <div className="sideloadPresetInstall__status">+ <Icon glyph={LoaderCircle} size="lg" className="spinner" />+ <span>+ {t(+ 'sideload.presets.running.title',+ 'Complete the {{title}} installation',+ { title: presetTitle }+ )}+ </span>+ </div>+ <p className="sideloadPresetInstall__hint">+ {t(+ 'sideload.presets.running.description',+ 'Finish the installer in the window that just opened. If the installer launches {{title}} at the end, close it so Heroic can continue. You can also continue now and pick the executable manually.',+ { title: presetTitle }+ )}+ </p>+ {showInstallerNotice && (+ <Alert variant="warning" className="sideloadPresetNote">+ {t(+ 'sideload.presets.macos-installer-notice',+ "macOS: the installer starts {{title}} at the end. That window can stay blank because the installer doesn't use Heroic's graphics settings. Close it, finish the setup, and start {{title}} from Heroic.",+ { title: presetTitle }+ )}+ </Alert>+ )}+ <div className="sideloadPresetInstall__actions">+ <Button variant="secondary" onClick={onContinue}>+ {t('sideload.presets.continue', 'Continue anyway')}+ </Button>+ {cancelButton}+ </div>+ <div className="sideloadPresetInstall__log">+ {logContent ? (+ <LogPanel content={logContent} />+ ) : (+ <span className="sideloadPresetInstall__logPlaceholder">+ {t(+ 'sideload.presets.running.waiting-log',+ 'Waiting for installer output…'+ )}+ </span>+ )}+ </div>+ </div>+ )+ }++ return (+ <div className="sideloadPresetInstall">+ <div className="sideloadPresetInstall__status">+ <Icon glyph={TriangleAlert} size="lg" />+ <span>+ {t('sideload.presets.preparing', 'Preparing the installer…')}+ </span>+ </div>+ <div className="sideloadPresetInstall__actions">{cancelButton}</div>+ </div>+ )+}diff --git a/src/frontend/screens/Library/components/InstallModal/WineSelector/index.tsx b/src/frontend/screens/Library/components/InstallModal/WineSelector/index.tsxindex f36c7c46a..99f0e5a78 100644--- a/src/frontend/screens/Library/components/InstallModal/WineSelector/index.tsx+++ b/src/frontend/screens/Library/components/InstallModal/WineSelector/index.tsx@@ -32,6 +32,7 @@ type Props = {onWineVersionPicked: () => voiduseSharedPrefix: booleansetUseSharedPrefix: (value: boolean) => void+ preferredWineType?: WineInstallation['type']}export default function WineSelector({@@ -49,7 +50,8 @@ export default function WineSelector({userPickedWineVersion,onWineVersionPicked,useSharedPrefix,- setUseSharedPrefix+ setUseSharedPrefix,+ preferredWineType}: Props) {const { t, i18n } = useTranslation('gamepage')@@ -84,9 +86,16 @@ export default function WineSelector({useEffect(() => {if (!globalConfig || useSharedPrefix) return+ // Presets can ask for a specific Wine flavour (plain Wine on macOS, for+ // example). When one is requested and installed it takes precedence over+ // the configured Game Defaults version.+ const preferredVersion = preferredWineType+ ? wineVersionList.find((version) => version.type === preferredWineType)+ : undefined+const nextWineVersion = repickWineVersion(wineVersion,- globalConfig.wineVersion,+ preferredVersion ?? globalConfig.wineVersion,wineVersionList,userPickedWineVersion)@@ -100,7 +109,8 @@ export default function WineSelector({globalConfig,setWineVersion,useSharedPrefix,- userPickedWineVersion+ userPickedWineVersion,+ preferredWineType])const showPrefix = wineVersion?.type !== 'crossover'diff --git a/src/frontend/screens/Library/components/InstallModal/index.tsx b/src/frontend/screens/Library/components/InstallModal/index.tsxindex 53cb67265..516dc6cc7 100644--- a/src/frontend/screens/Library/components/InstallModal/index.tsx+++ b/src/frontend/screens/Library/components/InstallModal/index.tsx@@ -10,12 +10,18 @@ import {Runner,WineInstallation} from 'common/types'+import {+ getSideloadPresetPlatform,+ type SideloadPreset,+ type SideloadPresetPlatform+} from 'common/sideload_presets'import { Modal } from 'frontend/components/UI/Modal'import './index.scss'import DownloadDialog from './DownloadDialog'import ImportDialog from './ImportDialog'+import PresetPicker from './PresetPicker'import SideloadDialog from './SideloadDialog'import WineSelector from './WineSelector'import { isWineVersionListed } from './WineSelector/selectDefaultWineVersion'@@ -43,7 +49,7 @@ export type AvailablePlatforms = {}[]function InstallModal({ appName, runner, gameInfo = null }: Props) {- const { platform, isLinuxArm } = useContext(ContextProvider)+ const { platform, isLinuxArm, showDialogModal } = useContext(ContextProvider)const { t, i18n } = useTranslation('gamepage')const { action = 'install' } = useInstallGameModal()@@ -56,6 +62,9 @@ function InstallModal({ appName, runner, gameInfo = null }: Props) {const [sideloadTitle, setSideloadTitle] = useState(t('sideload.field.title', 'Title'))+ const [preset, setPreset] = useState<SideloadPreset>()+ const [customFlow, setCustomFlow] = useState(false)+ const [presetBusy, setPresetBusy] = useState(false)const [steamPlatforms, setSteamPlatforms] = useState<InstallPlatform[] | null@@ -232,7 +241,55 @@ function InstallModal({ appName, runner, gameInfo = null }: Props) {const isThirdPartyManagedApp = gameInfo && !!gameInfo.thirdPartyManagedAppconst isImportMode = action === 'import'- const closeModal = () => closeInstallGameModal()+ const closeModal = () => {+ if (presetBusy) {+ showDialogModal({+ title: t(+ 'sideload.presets.closing.title',+ 'Installation is still running'+ ),+ message: t(+ 'sideload.presets.closing.message',+ 'The installer is still running. Close the window anyway? The installer may keep running in the background.'+ ),+ type: 'MESSAGE',+ buttons: [+ {+ text: t('sideload.presets.closing.continue', 'Close anyway'),+ variant: 'primary',+ onClick: () => closeInstallGameModal()+ },+ {+ text: t('sideload.presets.closing.cancel', 'Keep installing')+ }+ ]+ })+ return+ }++ closeInstallGameModal()+ }++ const showPresetPicker =+ isSideload && !appName && !preset && !customFlow && !isImportMode++ const handlePresetSelect = (selectedPreset: SideloadPreset) => {+ setPresetBusy(false)+ setPreset(selectedPreset)+ setSideloadTitle(selectedPreset.title)+ setPlatformToInstall(getSideloadPresetPlatform(selectedPreset))+ }++ const handleBackToPresets = () => {+ setPresetBusy(false)+ setPreset(undefined)+ setCustomFlow(false)+ setSideloadTitle(t('sideload.field.title', 'Title'))+ setPlatformToInstall(getDefaultplatform())+ setWineVersion(undefined)+ setWinePrefix('...')+ setCrossoverBottle('')+ }const isDownloadDialog =showDownloadDialog && !isThirdPartyManagedApp && !isImportMode@@ -244,7 +301,13 @@ function InstallModal({ appName, runner, gameInfo = null }: Props) {size={isDownloadDialog ? 'md' : 'lg'}className="InstallModal__dialog">- {isThirdPartyManagedApp ? (+ {showPresetPicker ? (+ <PresetPicker+ platform={platform as SideloadPresetPlatform}+ onSelectPreset={handlePresetSelect}+ onCustom={() => setCustomFlow(true)}+ />+ ) : isThirdPartyManagedApp ? (<ThirdPartyDialogappName={appName}runner={runner}@@ -355,6 +418,9 @@ function InstallModal({ appName, runner, gameInfo = null }: Props) {appName={appName}crossoverBottle={crossoverBottle}platformSelection={platformSelection()}+ preset={preset}+ onBackToPresets={preset ? handleBackToPresets : undefined}+ onPresetBusyChange={setPresetBusy}wineSelector={hasWine ? (<WineSelector@@ -373,6 +439,11 @@ function InstallModal({ appName, runner, gameInfo = null }: Props) {title={sideloadTitle}initiallyOpennoDetails+ preferredWineType={+ preset?.launcher?.preferredWineType?.[+ platform as SideloadPresetPlatform+ ]+ }/>) : null}diff --git a/src/frontend/screens/Settings/components/EnvVariablesTable.tsx b/src/frontend/screens/Settings/components/EnvVariablesTable.tsxindex 4c95d74a5..a47525a56 100644--- a/src/frontend/screens/Settings/components/EnvVariablesTable.tsx+++ b/src/frontend/screens/Settings/components/EnvVariablesTable.tsx@@ -9,20 +9,37 @@ import {import useSetting from 'frontend/hooks/useSetting'import ContextProvider from 'frontend/state/ContextProvider'import { Eraser, ListChecks, Plus } from 'lucide-react'+import type { EnviromentVariable } from 'common/types'import { Modal, ModalHeader } from 'frontend/components/UI/Modal'import './EnvVariablesTable.css'import BulkEditModal from './BulkEditModal'import EnvVariableRow, { validateEnvKey } from './EnvVariableRow'-const EnvVariablesTable = () => {+interface Props {+ /** Controlled list. Useful outside the Settings screen, e.g. the Add Game modal. */+ environmentOptions?: EnviromentVariable[]+ onEnvironmentOptionsChange?: (+ environmentOptions: EnviromentVariable[]+ ) => void+}++const EnvVariablesTable = ({+ environmentOptions: controlledEnvironmentOptions,+ onEnvironmentOptionsChange+}: Props = {}) => {const { t } = useTranslation()const { showDialogModal } = useContext(ContextProvider)- const [environmentOptions, setEnvironmentOptions] = useSetting(+ const [settingEnvironmentOptions, setSettingEnvironmentOptions] = useSetting('enviromentOptions',[])+ const environmentOptions =+ controlledEnvironmentOptions ?? settingEnvironmentOptions+ const setEnvironmentOptions =+ onEnvironmentOptionsChange ?? setSettingEnvironmentOptions+const [newKey, setNewKey] = useState('')const [newValue, setNewValue] = useState('')const [formError, setFormError] = useState('')diff --git a/src/preload/api/helpers.ts b/src/preload/api/helpers.tsindex e1785dd47..8a7fff5d4 100644--- a/src/preload/api/helpers.ts+++ b/src/preload/api/helpers.ts@@ -54,3 +54,11 @@ export const getGmgDiscounts = makeHandlerInvoker('getGmgDiscounts')export const getHumbleDiscounts = makeHandlerInvoker('getHumbleDiscounts')export const setTitleBarOverlay = makeListenerCaller('setTitleBarOverlay')export const isGameAvailable = makeHandlerInvoker('isGameAvailable')+export const getSideloadPresetArtwork = makeHandlerInvoker('getSideloadPresetArtwork')+export const downloadSideloadPresetInstaller = makeHandlerInvoker('downloadSideloadPresetInstaller')+export const runSideloadPresetInstaller = makeHandlerInvoker('runSideloadPresetInstaller')+export const detectSideloadPresetExecutable = makeHandlerInvoker('detectSideloadPresetExecutable')+export const getSideloadPresetStatuses = makeHandlerInvoker('getSideloadPresetStatuses')+export const scanSideloadPresetGames = makeHandlerInvoker('scanSideloadPresetGames')+export const addScannedSideloadGames = makeHandlerInvoker('addScannedSideloadGames')+export const onPresetDownloadProgress = frontendListenerSlot('presetDownloadProgress')