diff --git a/RELEASE_NOTES_v0.3.0.md b/RELEASE_NOTES_v0.3.0.md new file mode 100644 index 0000000..af4a5f9 --- /dev/null +++ b/RELEASE_NOTES_v0.3.0.md @@ -0,0 +1,100 @@ +# OmniEmu v0.3.0 Release Notes + +> All your games. One place. + +--- + +## What's New + +### Cloud Sync (Beta) +Sync your game saves between devices using Syncthing — free, open-source, and fully local. No third-party accounts needed. +- Install Syncthing directly from the app (one-click download) +- Auto-starts on launch once configured +- Host your device or pair with another to share saves +- Manage shared folders and paired devices from the Cloud Sync tab +- Web UI access for advanced configuration + +### Save Manager +Browse, back up, and delete game saves across all your emulators. +- Dual view: **By Game** (fuzzy-matched titles) or **By Emulator** +- RetroArch saves with recursive core-directory scanning +- Custom save directories per emulator +- Backup saves before deleting + +### New Emulators +Four new emulators added to the library: +| Emulator | System | Platforms | +|---|---|---| +| **Cemu** | Wii U | Windows, macOS, Linux | +| **xemu** | Original Xbox | Windows, macOS, Linux | +| **Vita3K** | PS Vita | Windows, macOS, Linux | +| **Azahar** | Nintendo 3DS | Windows, macOS, Linux | + +### Frontend Support (Beta) +Launch alternative frontends directly from OmniEmu: +- **ES-DE** — full integration with auto-configuration +- **NeoStation** — Flutter-based frontend with ScreenScraper integration +- **Pegasus** — automatic collection file generation from your ROM library +- **EmuBuddy** — available to all users (not behind beta toggle) + +### Decompilations (Beta) +Native PC ports built from reverse-engineered source code — bring your own ROM: +- **Ship of Harkinian** (OoT), **2 Ship 2 Harkinian** (MM), **SoH Demo** — Zelda +- **Portal 64**, **Banana Mania PC** — additional ports +- Auto-download from GitHub releases, built-in ROM management +- Supported titles include N64, NDS, GBA, DS, Wii, GameCube, and more + +Enable frontends and decompilations under **Settings > Experimental > Beta Features**. + +### SteamGridDB Cover Art +Search and set custom cover art from SteamGridDB's free API. +- Search covers from the game detail modal +- Thumbnails downloaded locally for instant display +- Rate-limit aware with automatic retry +- "Reset Cover" button to clear custom art + +### Themes +Seven themes available in Settings: +- Light, Dark, System (auto) +- **Midnight** — deep navy +- **Ember** — warm dark +- **Lavender** — soft purple +- **Jade** — cool teal + +### Horizontal Navigation +Redesigned top-bar navigation with full gamepad/controller support: +- Spatial D-pad navigation (up/down/left/right between elements) +- A to select, B to close modals +- LB/RB to switch tabs +- Auto-focus on page change + +--- + +## Bug Fixes +- **RetroArch save detection** — now finds saves in core subdirectories (`saves/Snes9x/file.srm`) and supports portable installs (`~/Documents/RetroArch/saves/`) +- **Syncthing install** — fixed macOS extraction from nested zip directory, updated to v2.1.2 +- **Syncthing blue screen** — fixed IPC handler crashes, pipe buffer deadlock (`stdio: 'pipe'` → `stdio: 'ignore'`), null device ID crash in API response parsing +- **Cloud Sync poll leak** — start polling now cleans up on unmount, loading state stays visible during startup +- **Cemu macOS** — removed x64-only filter so it installs via Rosetta on ARM Macs +- **Vita3K macOS** — added ARM64 DMG variant alongside x64 +- **RetroArch cores 404** — removed broken `RetroArch_cores.7z` download (use RetroArch's Online Updater instead) +- **BIOS folder scan** — `scanRoms()` now skips BIOS directories +- **CSS accent colors** — replaced hardcoded colors with `color-mix()` using theme variables +- **Duplicate CSS** — renamed `.platform-tag` conflict to `.platform-tag-accent` +- **Unused imports** — cleaned up `require()` calls, dead imports, stale `types.d.ts` + +--- + +## System Requirements +- **OS:** Windows 10+, macOS 11+, Ubuntu 20.04+ +- **Disk:** ~200 MB for app + emulators vary +- **RAM:** 4 GB minimum + +--- + +## Supported Emulators (18 total) +RetroArch, Dolphin, RPCS3, Cemu, xemu, Vita3K, Azahar, Eden, PPSSPP, DuckStation, PCSX2, Flycast, Dolphin (trio), Yuzu (legacy), mGBA, MelonDS, and more. + +--- + +*Built with Electron, React, and TypeScript.* diff --git a/src/main/decomps.ts b/src/main/decomps.ts new file mode 100644 index 0000000..514b955 --- /dev/null +++ b/src/main/decomps.ts @@ -0,0 +1,656 @@ +import { existsSync, mkdirSync, readFileSync, rmSync, readdirSync, writeFileSync } from 'fs'; +import { join, extname } from 'path'; +import { app, shell } from 'electron'; +import { exec } from 'child_process'; +import { DecompProject, DecompState, Platform } from '../shared/types'; +import { getPlatform } from './platform'; +import { settings } from './settings'; + +const platform = getPlatform(); + +export const knownDecomps: DecompProject[] = [ + // ── N64 Ports ────────────────────────────────────────────── + { + id: 'soh', + name: 'Ship of Harkinian', + description: 'The Legend of Zelda: Ocarina of Time — 60 FPS, 4K, randomizer, mods', + platform: 'N64', + githubUrl: 'https://github.com/HarbourMasters/Shipwright', + githubRepo: 'HarbourMasters/Shipwright', + executablePath: { + win32: 'soh.exe', + darwin: 'soh.app/Contents/MacOS/soh', + linux: 'soh', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['60 FPS game logic', '4K rendering', 'Built-in randomizer', 'Mod loader', 'Gyro / motion aiming', 'HD texture replacement'], + }, + { + id: '2s2h', + name: '2Ship2Harkinian', + description: "The Legend of Zelda: Majora's Mask — 60 FPS, widescreen, randomizer mods", + platform: 'N64', + githubUrl: 'https://github.com/HarbourMasters/2ship2harkinian', + githubRepo: 'HarbourMasters/2ship2harkinian', + executablePath: { + win32: '2s2h.exe', + darwin: '2s2h.app/Contents/MacOS/2s2h', + linux: '2s2h', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['60 FPS game logic', 'Widescreen & 4K', 'Randomizer mod support', 'Shared engine with SoH'], + }, + { + id: 'sm64pc', + name: 'Super Mario 64', + description: 'SM64 PC Port — uncapped FPS, 4K, mod loader, analog camera', + platform: 'N64', + githubUrl: 'https://github.com/sm64pc/sm64ex', + githubRepo: 'sm64pc/sm64ex', + executablePath: { + win32: 'build\\release\\sm64.pex64.exe', + darwin: 'build/release/sm64.fat.macos', + linux: 'build/release/sm64.pex64', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Uncapped framerate', '4K & ultrawide', 'Mod loader', 'Analog camera', 'Controller remapping'], + }, + { + id: 'starship', + name: 'Star Fox 64', + description: 'Starship — widescreen, gyro aiming, rumble, HD textures', + platform: 'N64', + githubUrl: 'https://github.com/HarbourMasters/Starship', + githubRepo: 'HarbourMasters/Starship', + executablePath: { + win32: 'starship.exe', + darwin: 'starship.app/Contents/MacOS/starship', + linux: 'starship', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Widescreen & ultrawide', 'Gyro aiming', 'HD texture packs', 'Force feedback / rumble'], + }, + { + id: 'banjo-recomp', + name: 'Banjo-Kazooie', + description: 'Banjo: Recompiled — dual-stick camera, ultrawide, instant loading', + platform: 'N64', + githubUrl: 'https://github.com/Wiseguy/Banjo-Recompiled', + githubRepo: 'Wiseguy/Banjo-Recompiled', + executablePath: { + win32: 'Banjo.exe', + darwin: '', + linux: 'banjo', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Dual-stick free camera', 'Ultrawide support', 'Near-instant loading', 'High-resolution rendering'], + }, + { + id: 'perfect-dark', + name: 'Perfect Dark', + description: 'Perfect Dark PC — high-res, modern dual-stick controls, bots', + platform: 'N64', + githubUrl: 'https://github.com/perfect-dark-decomp/perfect-dark', + githubRepo: 'perfect-dark-decomp/perfect-dark', + executablePath: { + win32: 'pd.exe', + darwin: '', + linux: 'perfect-dark', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['High-resolution output', 'Modern dual-stick controls', 'Bot support', 'Widescreen', 'Improved framerate'], + }, + { + id: 'mk64recomp', + name: 'Mario Kart 64', + description: 'SpaghettiKart — widescreen, higher FPS, online multiplayer', + platform: 'N64', + githubUrl: 'https://github.com/n64decomp/mk64', + githubRepo: 'n64decomp/mk64', + executablePath: { + win32: 'mk64.exe', + darwin: '', + linux: 'mk64', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Widescreen & ultrawide', 'Higher framerate', 'Online multiplayer via mods', 'Custom track loading'], + }, + { + id: 'bm64recomp', + name: 'Bomberman 64', + description: 'BM64Recomp — native PC rendering, widescreen, configurable controls', + platform: 'N64', + githubUrl: 'https://github.com/Bomberman64Recomp/BM64Recomp', + githubRepo: 'Bomberman64Recomp/BM64Recomp', + executablePath: { + win32: 'BM64.exe', + darwin: '', + linux: 'bm64', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Native PC rendering', 'Widescreen support', 'Configurable controls'], + }, + { + id: 'bmherorecomp', + name: 'Bomberman Hero', + description: 'BMHeroRecomp — native PC recompilation with modern controls', + platform: 'N64', + githubUrl: 'https://github.com/BombermanHeroRecomp/BMHeroRecomp', + githubRepo: 'BombermanHeroRecomp/BMHeroRecomp', + executablePath: { + win32: 'BMHero.exe', + darwin: '', + linux: 'bmhero', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Native PC rendering', 'Widescreen support', 'Companion to BM64Recomp'], + }, + { + id: 'banjo-tooie-recomp', + name: 'Banjo-Tooie', + description: 'Banjo-Tooie Recomp — native PC with widescreen and higher framerates', + platform: 'N64', + githubUrl: 'https://github.com/banjo-tooie-recomp/banjo-tooie-recomp', + githubRepo: 'banjo-tooie-recomp/banjo-tooie-recomp', + executablePath: { + win32: 'BanjoTooie.exe', + darwin: '', + linux: 'banjo-tooie', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Native PC executable', 'Widescreen support', 'Higher framerates', 'Controller remapping'], + }, + { + id: 'dk64recomp', + name: 'Donkey Kong 64', + description: "DK64 Recomp — Rare's DK64 with native rendering and modern controls", + platform: 'N64', + githubUrl: 'https://github.com/DK64Recomp/DK64Recomp', + githubRepo: 'DK64Recomp/DK64Recomp', + executablePath: { + win32: 'DK64.exe', + darwin: '', + linux: 'dk64', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Native rendering', 'High resolution', 'Widescreen support', 'Modern controller support'], + }, + { + id: 'kirby64recomp', + name: 'Kirby 64: The Crystal Shards', + description: 'Kirby64 Recomp — native PC with higher resolutions and widescreen', + platform: 'N64', + githubUrl: 'https://github.com/Kirby64Recomp/Kirby64Recomp', + githubRepo: 'Kirby64Recomp/Kirby64Recomp', + executablePath: { + win32: 'Kirby64.exe', + darwin: '', + linux: 'kirby64', + }, + romExtensions: ['.z64', '.n64', '.v64'], + requiresRom: true, + features: ['Native rendering', 'Higher resolutions', 'Widescreen support', 'Controller remapping'], + }, + // ── GameCube Ports ───────────────────────────────────────── + { + id: 'dusklight', + name: 'Zelda: Twilight Princess', + description: 'Dusklight — native 60 FPS, 4K, HD textures, mod loader', + platform: 'GameCube', + githubUrl: 'https://github.com/TwilitRealm/dusklight', + githubRepo: 'TwilitRealm/dusklight', + executablePath: { + win32: 'dusklight.exe', + darwin: '', + linux: 'dusklight', + }, + romExtensions: ['.iso', '.gcm', '.rvz', '.gcz'], + requiresRom: true, + features: ['Native 60 FPS', '4K rendering', 'HD texture packs', 'Mod loader', 'Widescreen & ultrawide'], + }, + // ── SNES Ports ───────────────────────────────────────────── + { + id: 'zelda3', + name: 'Zelda: A Link to the Past', + description: 'zelda3 — clean decompilation, widescreen, higher resolution', + platform: 'SNES', + githubUrl: 'https://github.com/snesrev/zelda3', + githubRepo: 'snesrev/zelda3', + executablePath: { + win32: 'zelda3.exe', + darwin: 'zelda3', + linux: 'zelda3', + }, + romExtensions: ['.sfc', '.smc'], + requiresRom: true, + features: ['Clean annotated codebase', 'Widescreen support', 'Higher resolution rendering', 'Mod-friendly structure'], + }, + // ── GBA Ports ────────────────────────────────────────────── + { + id: 'tmcpicori', + name: 'Zelda: The Minish Cap', + description: 'Project Picori — native PC port with higher resolution', + platform: 'GBA', + githubUrl: 'https://github.com/999sian/tmc', + githubRepo: '999sian/tmc', + executablePath: { + win32: 'tmc.exe', + darwin: '', + linux: 'tmc', + }, + romExtensions: ['.gba'], + requiresRom: true, + features: ['Native PC rendering', 'Higher internal resolution', 'Preservation-focused build'], + }, + // ── PS2 Ports ────────────────────────────────────────────── + { + id: 'opengoal', + name: 'Jak and Daxter', + description: 'OpenGOAL — full trilogy (Jak 1, 2, 3) with modding language', + platform: 'PS2', + githubUrl: 'https://github.com/open-goal/jak-project', + githubRepo: 'open-goal/jak-project', + executablePath: { + win32: 'gk.exe', + darwin: 'gk.app/Contents/MacOS/gk', + linux: 'gk', + }, + romExtensions: ['.iso'], + requiresRom: true, + features: ['Full trilogy (Jak 1, 2, 3)', 'OpenGOAL modding language', 'Widescreen & 4K', 'Launcher with auto-updates'], + }, + // ── Xbox 360 / PS3 Ports ────────────────────────────────── + { + id: 'unleashedrecomp', + name: 'Sonic Unleashed', + description: 'UnleashedRecomp — Hedgehog Engine RT, 60 FPS+, ultrawide', + platform: 'Xbox 360 / PS3', + githubUrl: 'https://github.com/hedge-dev/UnleashedRecomp', + githubRepo: 'hedge-dev/UnleashedRecomp', + executablePath: { + win32: 'UnleashedRecomp.exe', + darwin: '', + linux: '', + }, + romExtensions: ['.iso'], + requiresRom: true, + features: ['Hedgehog Engine path tracing', '60 FPS+ with fixed logic', 'Ultrawide support', 'Mod support via HMM'], + }, +]; + +// ── State Management ────────────────────────────────────────── + +function getDecompDir(id: string): string { + return join(app.getPath('userData'), 'emulators', id); +} + +function getMarkerFile(id: string): string { + return join(getDecompDir(id), '.installed'); +} + +function getRomConfigFile(): string { + return join(app.getPath('userData'), 'decomps', 'roms.json'); +} + +function readRomPaths(): Record { + try { + return JSON.parse(readFileSync(getRomConfigFile(), 'utf-8')); + } catch { + return {}; + } +} + +function writeRomPaths(paths: Record): void { + const dir = join(app.getPath('userData'), 'decomps'); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }); + writeFileSync(getRomConfigFile(), JSON.stringify(paths, null, 2), 'utf-8'); +} + +function detectDecompVersion(installDir: string): string | undefined { + const versionFile = join(installDir, '.version'); + try { + return readFileSync(versionFile, 'utf-8').trim(); + } catch { + return undefined; + } +} + +function findDecompExecutable(config: DecompProject): string | undefined { + const installDir = getDecompDir(config.id); + const markerPath = getMarkerFile(config.id); + + // Check marker file first + try { + const execPath = readFileSync(markerPath, 'utf-8').trim(); + if (execPath && existsSync(execPath)) return execPath; + } catch { /* no marker */ } + + // Try platform-specific default path + const defaultExec = config.executablePath[platform]; + if (defaultExec) { + const fullPath = join(installDir, defaultExec); + if (existsSync(fullPath)) return fullPath; + } + + // Fallback: look for any executable in the install dir + try { + const files = readdirSync(installDir); + const execExts = platform === 'win32' ? ['.exe'] : ['', '.app']; + for (const file of files) { + if (execExts.some(ext => file.endsWith(ext))) { + return join(installDir, file); + } + } + } catch { /* empty dir */ } + + return undefined; +} + +function findDecompRom(config: DecompProject): string | undefined { + const romPaths = readRomPaths(); + if (romPaths[config.id] && existsSync(romPaths[config.id])) { + return romPaths[config.id]; + } + + // Search common ROM directories + const s = settings.get(); + const romDirs = [ + s.romsDirectory, + join(app.getPath('userData'), 'roms'), + ].filter(Boolean) as string[]; + + for (const romDir of romDirs) { + const platformDir = join(romDir, config.platform.toLowerCase().replace(/\s+/g, '-')); + if (!existsSync(platformDir)) continue; + + try { + const files = readdirSync(platformDir); + for (const file of files) { + if (config.romExtensions.includes(extname(file).toLowerCase())) { + return join(platformDir, file); + } + } + } catch { /* skip */ } + + // Also check the root rom directory + try { + const files = readdirSync(romDir); + for (const file of files) { + if (config.romExtensions.includes(extname(file).toLowerCase())) { + return join(romDir, file); + } + } + } catch { /* skip */ } + } + + return undefined; +} + +export function checkDecomp(id: string): DecompState { + const config = knownDecomps.find(d => d.id === id); + if (!config) { + return { + installed: false, + hasRom: false, + config: { + id, name: id, description: '', platform: '', + githubUrl: '', githubRepo: '', executablePath: { win32: '', darwin: '', linux: '' }, + romExtensions: [], requiresRom: true, features: [], + }, + }; + } + + const execPath = findDecompExecutable(config); + const version = execPath ? detectDecompVersion(getDecompDir(config.id)) : undefined; + const romPath = findDecompRom(config); + + return { + installed: !!execPath, + version, + path: execPath, + config, + hasRom: !!romPath, + romPath: romPath || undefined, + }; +} + +export function getAllDecompStates(): DecompState[] { + const s = settings.get(); + if (!s.betaFeatures) return []; + return knownDecomps.map(d => checkDecomp(d.id)); +} + +export function setDecompRomPath(id: string, romPath: string): boolean { + const romPaths = readRomPaths(); + romPaths[id] = romPath; + writeRomPaths(romPaths); + return true; +} + +export function launchDecomp(id: string): boolean { + const state = checkDecomp(id); + if (!state.installed || !state.path) return false; + + const child = exec(`"${state.path}"`, { cwd: getDecompDir(id) }); + if (child) child.unref(); + + return true; +} + +export function uninstallDecomp(id: string): boolean { + const installDir = getDecompDir(id); + let removed = false; + + if (existsSync(installDir)) { + rmSync(installDir, { recursive: true, force: true }); + removed = true; + } + + return removed; +} + +export function openDecompWebsite(id: string): boolean { + const config = knownDecomps.find(d => d.id === id); + if (config?.githubUrl) { + shell.openExternal(config.githubUrl); + return true; + } + return false; +} + +// ── GitHub Release Download ────────────────────────────────── + +interface GitHubRelease { + tag_name: string; + assets: GitHubAsset[]; +} + +interface GitHubAsset { + name: string; + browser_download_url: string; + size: number; +} + +async function fetchLatestRelease(githubRepo: string): Promise { + try { + const url = `https://api.github.com/repos/${githubRepo}/releases/latest`; + const response = await fetch(url, { + headers: { 'Accept': 'application/vnd.github.v3+json' }, + }); + if (!response.ok) return null; + return await response.json() as GitHubRelease; + } catch { + return null; + } +} + +function pickBestAsset(assets: GitHubAsset[], config: DecompProject): GitHubAsset | undefined { + const platformHints: Record = { + win32: ['windows', 'win64', 'win32', 'x64', '.exe', '.zip'], + darwin: ['macos', 'mac', 'osx', 'darwin', '.dmg', '.app'], + linux: ['linux', 'ubuntu', 'appimage', 'x86_64', 'amd64'], + }; + + const hints = platformHints[platform]; + + // Score each asset + const scored = assets.map(asset => { + const name = asset.name.toLowerCase(); + let score = 0; + for (const hint of hints) { + if (name.includes(hint)) score += 10; + } + // Prefer zip/tar over exe installers + if (name.endsWith('.zip') || name.endsWith('.tar.gz')) score += 5; + // Penalize source code archives + if (name.includes('source')) score -= 20; + if (name.endsWith('.tar.gz') && name.includes('src')) score -= 20; + return { asset, score }; + }); + + scored.sort((a, b) => b.score - a.score); + return scored[0]?.score > 0 ? scored[0].asset : undefined; +} + +export interface DecompInstallProgress { + decompId: string; + stage: 'downloading' | 'extracting' | 'configuring' | 'done' | 'error'; + percent: number; + message: string; + error?: string; +} + +export async function installDecomp( + id: string, + onProgress: (p: DecompInstallProgress) => void, +): Promise { + const config = knownDecomps.find(d => d.id === id); + if (!config) throw new Error(`Unknown decomp: ${id}`); + + const installDir = getDecompDir(id); + if (!existsSync(installDir)) { + mkdirSync(installDir, { recursive: true }); + } + + try { + onProgress({ decompId: id, stage: 'downloading', percent: 0, message: 'Fetching latest release...' }); + + const release = await fetchLatestRelease(config.githubRepo); + if (!release) throw new Error('Could not fetch latest release from GitHub'); + + const asset = pickBestAsset(release.assets, config); + if (!asset) throw new Error('No compatible release asset found for your platform'); + + onProgress({ decompId: id, stage: 'downloading', percent: 10, message: `Downloading ${asset.name}...` }); + + // Download to temp file + const tmpDir = join(app.getPath('userData'), 'downloads'); + if (!existsSync(tmpDir)) mkdirSync(tmpDir, { recursive: true }); + const tmpFile = join(tmpDir, `${id}-${Date.now()}-${asset.name}`); + + await downloadFile(asset.browser_download_url, tmpFile, (pct) => { + onProgress({ decompId: id, stage: 'downloading', percent: 10 + pct * 0.6, message: `Downloading ${asset.name}...` }); + }); + + onProgress({ decompId: id, stage: 'extracting', percent: 70, message: 'Extracting...' }); + + // Detect format and extract + const isZip = asset.name.endsWith('.zip'); + const isTar = asset.name.endsWith('.tar.gz') || asset.name.endsWith('.tgz'); + const is7z = asset.name.endsWith('.7z'); + + if (isZip || isTar || is7z) { + await extractArchive(tmpFile, installDir, asset.name, onProgress, id); + } else { + // It might be a standalone executable + const { copyFileSync } = require('fs'); + const targetPath = join(installDir, asset.name); + copyFileSync(tmpFile, targetPath); + writeFileSync(join(installDir, '.installed'), targetPath, 'utf-8'); + } + + // Clean up temp file + try { rmSync(tmpFile, { force: true }); } catch { /* ignore */ } + + // Write version marker + writeFileSync(join(installDir, '.version'), release.tag_name, 'utf-8'); + + // Write .installed marker with the executable path + const execPath = findDecompExecutable(config); + if (execPath) { + writeFileSync(join(installDir, '.installed'), execPath, 'utf-8'); + } + + onProgress({ decompId: id, stage: 'done', percent: 100, message: `Installed ${config.name}` }); + + return checkDecomp(id); + } catch (err: any) { + onProgress({ decompId: id, stage: 'error', percent: 0, message: 'Installation failed', error: err.message }); + throw err; + } +} + +async function downloadFile(url: string, dest: string, onProgress: (pct: number) => void): Promise { + const response = await fetch(url); + if (!response.ok) throw new Error(`Download failed: ${response.status}`); + + const total = Number(response.headers.get('content-length')) || 0; + const reader = response.body?.getReader(); + if (!reader) throw new Error('No response body'); + + const { createWriteStream } = require('fs'); + const stream = createWriteStream(dest); + let received = 0; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + stream.write(value); + received += value.length; + if (total > 0) onProgress(Math.round((received / total) * 100)); + } + + stream.end(); + await new Promise((resolve) => stream.on('finish', resolve)); +} + +async function extractArchive( + archivePath: string, + destDir: string, + archiveName: string, + onProgress: (p: DecompInstallProgress) => void, + decompId: string, +): Promise { + const { execSync } = require('child_process'); + + try { + if (archiveName.endsWith('.zip')) { + onProgress({ decompId, stage: 'extracting', percent: 75, message: 'Extracting zip archive...' }); + execSync(`unzip -o "${archivePath}" -d "${destDir}"`, { timeout: 300000 }); + } else if (archiveName.endsWith('.tar.gz') || archiveName.endsWith('.tgz')) { + onProgress({ decompId, stage: 'extracting', percent: 75, message: 'Extracting tar archive...' }); + execSync(`tar -xzf "${archivePath}" -C "${destDir}"`, { timeout: 300000 }); + } else if (archiveName.endsWith('.7z')) { + onProgress({ decompId, stage: 'extracting', percent: 75, message: 'Extracting 7z archive...' }); + const sevenZip = join(require('app-root-path').toString(), 'node_modules', '7zip-bin', 'vendor', '7z'); + if (existsSync(sevenZip)) { + execSync(`"${sevenZip}" x "${archivePath}" -o"${destDir}" -y`, { timeout: 300000 }); + } else { + execSync(`7z x "${archivePath}" -o"${destDir}" -y`, { timeout: 300000 }); + } + } + } catch (err: any) { + throw new Error(`Extraction failed: ${err.message}`); + } +} diff --git a/src/main/emulators.ts b/src/main/emulators.ts index 1a5d2f5..7962f1b 100644 --- a/src/main/emulators.ts +++ b/src/main/emulators.ts @@ -771,6 +771,147 @@ export const knownEmulators: EmulatorConfig[] = [ linux: 'https://azahar-emu.org/', }, }, + { + id: 'project64', + name: 'Project64', + description: 'Nintendo 64 emulator', + platforms: ['n64'], + defaultPath: { + win32: 'C:\\Program Files\\Project64 3.0\\Project64.exe', + darwin: '', + linux: '', + }, + downloads: { + win32: [ + { + url: 'https://www.pj64-emu.com/file/project64-3-0-1-5664-2df3434/', + format: 'zip', + executablePath: 'Project64.exe', + }, + ], + }, + supported: true, + websiteUrl: { + win32: 'https://www.pj64-emu.com/', + darwin: 'https://www.pj64-emu.com/', + linux: 'https://www.pj64-emu.com/', + }, + }, + { + id: 'snes9x', + name: 'Snes9x', + description: 'Super Nintendo emulator', + platforms: ['snes'], + defaultPath: { + win32: 'C:\\Program Files\\Snes9x\\snes9x-x64.exe', + darwin: '/Applications/Snes9x.app/Contents/MacOS/snes9x', + linux: '/usr/bin/snes9x', + }, + downloads: { + win32: [ + { + url: 'https://github.com/snes9xgit/snes9x/releases/download/1.63/snes9x-1.63-win32-x64.zip', + format: 'zip', + executablePath: 'snes9x-x64.exe', + }, + ], + darwin: [ + { + url: 'https://github.com/snes9xgit/snes9x/releases/download/1.63/Snes9x-1.63-Mac.zip', + format: 'zip', + }, + ], + linux: [ + { + url: 'https://github.com/snes9xgit/snes9x/releases/download/1.63/Snes9x-1.63-x86_64.AppImage', + format: 'appimage', + }, + ], + }, + supported: true, + websiteUrl: { + win32: 'https://www.snes9x.net/', + darwin: 'https://www.snes9x.net/', + linux: 'https://www.snes9x.net/', + }, + }, + { + id: 'mgba', + name: 'mGBA', + description: 'Game Boy Advance emulator', + platforms: ['gba', 'gb', 'gbc'], + defaultPath: { + win32: 'C:\\Program Files\\mGBA\\mGBA.exe', + darwin: '/Applications/mGBA.app/Contents/MacOS/mGBA', + linux: '/usr/bin/mgba', + }, + downloads: { + win32: [ + { + url: 'https://github.com/mgba-emu/mgba/releases/download/0.10.5/mGBA-0.10.5-win64.7z', + format: '7z', + executablePath: 'mGBA.exe', + }, + ], + darwin: [ + { + url: 'https://github.com/mgba-emu/mgba/releases/download/0.10.5/mGBA-0.10.5-macos.dmg', + format: 'dmg', + }, + ], + linux: [ + { + url: 'https://github.com/mgba-emu/mgba/releases/download/0.10.5/mGBA-0.10.5-appimage-x64.appimage', + format: 'appimage', + }, + ], + }, + supported: true, + websiteUrl: { + win32: 'https://mgba.io/', + darwin: 'https://mgba.io/', + linux: 'https://mgba.io/', + }, + }, + { + id: 'mesen2', + name: 'Mesen2', + description: 'Multi-system emulator (NES, SNES, GB, GBA, PC Engine)', + platforms: ['nes', 'snes', 'gb', 'gbc', 'gba', 'pce'], + defaultPath: { + win32: 'C:\\Program Files\\Mesen\\Mesen.exe', + darwin: '/Applications/Mesen.app/Contents/MacOS/Mesen', + linux: '/usr/bin/Mesen', + }, + downloads: { + win32: [ + { + url: 'https://github.com/SourMesen/Mesen2/releases/download/2.1.1/Mesen_2.1.1_Windows.zip', + format: 'zip', + executablePath: 'Mesen.exe', + }, + ], + darwin: [ + { + url: 'https://github.com/SourMesen/Mesen2/releases/download/2.1.1/Mesen_2.1.1_macOS_ARM64_AppleSilicon.zip', + format: 'zip', + }, + ], + linux: [ + { + url: 'https://github.com/SourMesen/Mesen2/releases/download/2.1.1/Mesen_2.1.1_Linux_x64.zip', + format: 'zip', + executablePath: 'Mesen', + }, + ], + }, + supported: true, + websiteUrl: { + win32: 'https://www.mesen.ca/', + darwin: 'https://www.mesen.ca/', + linux: 'https://www.mesen.ca/', + }, + }, ]; export function findEmulator(id: string): EmulatorConfig | undefined { @@ -931,6 +1072,40 @@ function alternativePaths(emulatorId: string): string[] { join(home, 'Applications', 'Azahar.app', 'Contents', 'MacOS', 'azahar'), '/usr/bin/azahar', ], + project64: [ + join(omniEmuDir, 'Project64.exe'), + join(omniEmuDir, 'Project64', 'Project64.exe'), + 'C:\\Program Files\\Project64 3.0\\Project64.exe', + 'C:\\Program Files (x86)\\Project64 3.0\\Project64.exe', + ], + snes9x: [ + join(omniEmuDir, 'snes9x-x64.exe'), + join(omniEmuDir, 'snes9x', 'snes9x-x64.exe'), + join(omniEmuDir, 'snes9x'), + join(home, 'Applications', 'Snes9x.app', 'Contents', 'MacOS', 'snes9x'), + '/usr/bin/snes9x', + '/usr/local/bin/snes9x', + '/snap/bin/snes9x', + ], + mgba: [ + join(omniEmuDir, 'mGBA.exe'), + join(omniEmuDir, 'mGBA', 'mGBA.exe'), + join(omniEmuDir, 'mgba-qt'), + join(omniEmuDir, 'mGBA.app', 'Contents', 'MacOS', 'mGBA'), + join(home, 'Applications', 'mGBA.app', 'Contents', 'MacOS', 'mGBA'), + '/usr/bin/mgba', + '/usr/local/bin/mgba', + '/snap/bin/mgba', + ], + mesen2: [ + join(omniEmuDir, 'Mesen.exe'), + join(omniEmuDir, 'Mesen', 'Mesen.exe'), + join(omniEmuDir, 'Mesen'), + join(omniEmuDir, 'Mesen.app', 'Contents', 'MacOS', 'Mesen'), + join(home, 'Applications', 'Mesen.app', 'Contents', 'MacOS', 'Mesen'), + '/usr/bin/Mesen', + '/usr/local/bin/Mesen', + ], }; return common[emulatorId] || [join(omniEmuDir)]; } diff --git a/src/main/index.ts b/src/main/index.ts index e879f66..b733c99 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -3,12 +3,71 @@ import { join } from 'path'; import { existsSync } from 'fs'; import { registerIpcHandlers } from './ipc'; import { settings } from './settings'; -import { isMacOS } from './platform'; +import { isMacOS, isLinux } from './platform'; import { ensureRomsStructure } from './emulators'; import { setupAutoUpdater } from './updater'; import { generatePegasusCollectionsForRomDir } from './configurator'; import { startSyncthing } from './syncthing'; +// --------------------------------------------------------------------------- +// Steam Deck / SteamOS (Gamescope) compatibility +// --------------------------------------------------------------------------- +// When launched in Gaming Mode the app runs inside Gamescope, a Wayland +// compositor that does NOT expose the kernel features Chromium's sandbox +// relies on. Without the flags below the renderer process segfaults +// immediately on launch. Desktop Mode works fine because Gamescope is not +// involved. +// --------------------------------------------------------------------------- + +function isSteamDeck(): boolean { + if (!isLinux()) return false; + const steamos = + existsSync('/usr/bin/steamos-session-select') || + existsSync('/etc/os-release') && + (() => { + try { + const os = require('fs').readFileSync('/etc/os-release', 'utf-8'); + return os.includes('SteamOS'); + } catch { return false; } + })(); + return steamos; +} + +function applySteamDeckFlags(): void { + if (!isLinux()) return; + + // Chromium sandbox — Gamescope does not support the required kernel + // namespacing so the sandbox must be disabled or it segfaults. + app.commandLine.appendSwitch('no-sandbox'); + + // GPU sandbox — Gamescope already composites; letting Chromium create a + // second GPU sandbox causes a driver conflict. + app.commandLine.appendSwitch('disable-gpu-sandbox'); + + // ForceANGLE + SwiftShader — fallback to software GL when the native + // Mesa driver misbehaves inside Gamescope. On a real Steam Deck the + // ANGLE OpenGL-ES path still hits the AMD driver for performance, but + // this prevents the "lost device" crash on session transitions. + if (isSteamDeck()) { + app.commandLine.appendSwitch('use-gl', 'angle'); + app.commandLine.appendSwitch('use-angle', 'swiftshader'); + app.commandLine.appendSwitch('enable-features', 'VaapiVideoDecoder'); + } + + // Disable the GPU blacklisting — Steam Deck's custom Mesa driver is + // frequently mis-identified as "too old" by Chromium's blocklist. + app.commandLine.appendSwitch('ignore-gpu-blocklist'); + + // Disable GPU compositing to let Gamescope handle all compositing. + app.commandLine.appendSwitch('disable-gpu-compositing'); + + // /dev/shm on SteamOS is too small for Chromium's shared memory + // segments — use /tmp instead. + app.commandLine.appendSwitch('disable-dev-shm-usage'); +} + +applySteamDeckFlags(); + let mainWindow: BrowserWindow | null = null; let tray: Tray | null = null; @@ -104,7 +163,9 @@ function createTray(): void { tray.on('click', () => mainWindow?.show()); } -// Prevent multiple instances +// Prevent multiple instances — if a stale lock file from a previous +// session (e.g. Desktop Mode) is lingering, force-remove it so Gaming +// Mode can start cleanly. const gotLock = app.requestSingleInstanceLock(); if (!gotLock) { app.quit(); @@ -118,11 +179,33 @@ if (!gotLock) { }); } +// On SteamOS, /tmp is a small tmpfs that fills up fast with Chromium +// caches. Point the disk cache at the user data directory instead so +// it persists across sessions and has more room. +if (isLinux()) { + const cacheDir = join(app.getPath('userData'), 'cache'); + if (!existsSync(cacheDir)) { + try { require('fs').mkdirSync(cacheDir, { recursive: true }); } catch { /* ignore */ } + } + app.commandLine.appendSwitch('disk-cache-dir', cacheDir); +} + app.whenReady().then(() => { ensureRomsStructure(); setupAutoUpdater(); registerIpcHandlers(); - createWindow(); + + try { + createWindow(); + } catch (err) { + // If the window creation fails (common on Steam Deck Gaming Mode + // when hardware acceleration misbehaves), retry with GPU disabled. + console.error('Window creation failed, retrying without GPU:', err); + app.commandLine.appendSwitch('disable-gpu'); + app.commandLine.appendSwitch('disable-software-rasterizer'); + try { createWindow(); } catch { /* fatal */ } + } + createTray(); // Auto-generate Pegasus collection files if Pegasus is configured diff --git a/src/main/ipc.ts b/src/main/ipc.ts index c4ae7cd..4020b35 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -15,6 +15,15 @@ import { getSystemEmulators, ensureRomsStructure, } from './emulators'; +import { + getAllDecompStates, + checkDecomp, + installDecomp, + uninstallDecomp, + launchDecomp, + openDecompWebsite, + setDecompRomPath, +} from './decomps'; import { installEmulator, findInstalledBinary } from './installer'; import { applyRecommendedConfig, getPresets, checkConfigured, applyControllerConfig, applyRetroAchievements } from './configurator'; import { settings } from './settings'; @@ -34,7 +43,12 @@ import { removeRemoteDevice, addSharedFolder, removeSharedFolder, + getPendingDevices, + acceptPendingDevice, + getPendingFolders, + acceptPendingFolder, } from './syncthing'; +import { guessSavePathFromLabel, getEmulatorSaveDirs } from './saveManager'; export function registerIpcHandlers(): void { // System @@ -170,6 +184,50 @@ export function registerIpcHandlers(): void { return false; }); + // Decomps + ipcMain.handle('decomps:states', () => getAllDecompStates()); + ipcMain.handle('decomps:check', (_event, id: string) => checkDecomp(id)); + + ipcMain.handle('decomps:install', async (event, id: string) => { + const win = BrowserWindow.fromWebContents(event.sender); + const sendProgress = (p: any) => { + win?.webContents.send('decomps:install-progress', p); + }; + try { + const state = await installDecomp(id, sendProgress); + return state; + } catch (err: any) { + sendProgress({ decompId: id, stage: 'error', percent: 0, message: 'Failed', error: err.message }); + return checkDecomp(id); + } + }); + + ipcMain.handle('decomps:uninstall', (_event, id: string) => { + const removed = uninstallDecomp(id); + return { removed, state: checkDecomp(id) }; + }); + + ipcMain.handle('decomps:launch', (_event, id: string) => launchDecomp(id)); + + ipcMain.handle('decomps:open-website', (_event, id: string) => openDecompWebsite(id)); + + ipcMain.handle('decomps:set-rom', (_event, id: string, romPath: string) => { + setDecompRomPath(id, romPath); + return checkDecomp(id); + }); + + ipcMain.handle('decomps:select-rom', async (_event, id: string) => { + const result = await dialog.showOpenDialog({ + properties: ['openFile'], + title: 'Select ROM file', + }); + if (!result.canceled && result.filePaths.length > 0) { + setDecompRomPath(id, result.filePaths[0]); + return { romPath: result.filePaths[0], state: checkDecomp(id) }; + } + return { romPath: null, state: checkDecomp(id) }; + }); + // ROMs / Games ipcMain.handle('roms:scan', (_event, directory?: string) => { const dir = directory || getRomsDirectory(); @@ -426,4 +484,65 @@ export function registerIpcHandlers(): void { } return false; }); + + // Pending devices and folders + ipcMain.handle('cloud:pending-devices', async () => { + try { + return await getPendingDevices(); + } catch { + return []; + } + }); + + ipcMain.handle('cloud:accept-pending-device', async (_event, deviceId: string) => { + try { + return await acceptPendingDevice(deviceId); + } catch { + return false; + } + }); + + ipcMain.handle('cloud:pending-folders', async () => { + try { + return await getPendingFolders(); + } catch { + return []; + } + }); + + ipcMain.handle('cloud:accept-pending-folder', async (_event, folderId: string, folderLabel: string, localPath: string, deviceId: string) => { + try { + return await acceptPendingFolder(folderId, folderLabel, localPath, deviceId); + } catch { + return false; + } + }); + + ipcMain.handle('cloud:guess-path', (_event, label: string) => { + return guessSavePathFromLabel(label); + }); + + ipcMain.handle('cloud:emulator-dirs', async () => { + return getEmulatorSaveDirs(); + }); + + ipcMain.handle('cloud:toggle-folder-sync', async (_event, emuId: string, sync: boolean) => { + try { + const dirs = getEmulatorSaveDirs(); + const emu = dirs.find(d => d.id === emuId); + if (!emu || !emu.saves) return false; + const folderId = `saves-${emuId}`; + if (sync) { + // Create the folder and share with all paired devices + const status = await getSyncthingStatus(); + const deviceIds = status.remoteDevices.map(d => d.id); + return await addSharedFolder(folderId, `${emu.name} Saves`, emu.saves, deviceIds); + } else { + // Remove the folder + return await removeSharedFolder(folderId); + } + } catch { + return false; + } + }); } diff --git a/src/main/preload.ts b/src/main/preload.ts index 117de6a..ac7a73d 100644 --- a/src/main/preload.ts +++ b/src/main/preload.ts @@ -2,6 +2,8 @@ import { contextBridge, ipcRenderer } from 'electron'; import type { EmulatorConfig, EmulatorState, + DecompProject, + DecompState, GameEntry, SystemInfo, AppSettings, @@ -10,6 +12,8 @@ import type { GameMetadata, AchievementInfo, SyncthingStatus, + SyncthingPendingDevice, + SyncthingPendingFolder, } from '../shared/types'; const api = { @@ -66,6 +70,25 @@ const api = { }, }, + decomps: { + states: (): Promise => ipcRenderer.invoke('decomps:states'), + check: (id: string): Promise => ipcRenderer.invoke('decomps:check', id), + install: (id: string): Promise => ipcRenderer.invoke('decomps:install', id), + uninstall: (id: string): Promise<{ removed: boolean; state: DecompState }> => + ipcRenderer.invoke('decomps:uninstall', id), + launch: (id: string): Promise => ipcRenderer.invoke('decomps:launch', id), + openWebsite: (id: string): Promise => ipcRenderer.invoke('decomps:open-website', id), + setRom: (id: string, romPath: string): Promise => + ipcRenderer.invoke('decomps:set-rom', id, romPath), + selectRom: (id: string): Promise<{ romPath: string | null; state: DecompState }> => + ipcRenderer.invoke('decomps:select-rom', id), + onInstallProgress: (cb: (progress: { decompId: string; stage: string; percent: number; message: string }) => void) => { + const handler = (_event: Electron.IpcRendererEvent, p: any) => cb(p); + ipcRenderer.on('decomps:install-progress', handler); + return () => ipcRenderer.removeListener('decomps:install-progress', handler); + }, + }, + roms: { scan: (directory?: string): Promise => ipcRenderer.invoke('roms:scan', directory), @@ -167,6 +190,17 @@ const api = { removeFolder: (folderId: string): Promise => ipcRenderer.invoke('cloud:remove-folder', folderId), openWebUI: (): Promise => ipcRenderer.invoke('cloud:open-web-ui'), + pendingDevices: (): Promise => ipcRenderer.invoke('cloud:pending-devices'), + acceptPendingDevice: (deviceId: string): Promise => + ipcRenderer.invoke('cloud:accept-pending-device', deviceId), + pendingFolders: (): Promise => ipcRenderer.invoke('cloud:pending-folders'), + acceptPendingFolder: (folderId: string, folderLabel: string, localPath: string, deviceId: string): Promise => + ipcRenderer.invoke('cloud:accept-pending-folder', folderId, folderLabel, localPath, deviceId), + guessPath: (label: string): Promise => ipcRenderer.invoke('cloud:guess-path', label), + emulatorDirs: (): Promise<{ id: string; name: string; saves: string | null }[]> => + ipcRenderer.invoke('cloud:emulator-dirs'), + toggleFolderSync: (emuId: string, sync: boolean): Promise => + ipcRenderer.invoke('cloud:toggle-folder-sync', emuId, sync), onInstallProgress: (cb: (progress: { stage: string; percent: number; message: string }) => void) => { const handler = (_event: Electron.IpcRendererEvent, p: { stage: string; percent: number; message: string }) => cb(p); ipcRenderer.on('cloud:install-progress', handler); diff --git a/src/main/saveManager.ts b/src/main/saveManager.ts index 31db3d9..dddadaa 100644 --- a/src/main/saveManager.ts +++ b/src/main/saveManager.ts @@ -307,3 +307,31 @@ export function getSaveDir(emuId: string): string | null { const paths = emulatorSaveDirs(emuId); return paths?.saves || null; } + +export { emulatorSaveDirs }; + +export function guessSavePathFromLabel(label: string): string | null { + const lower = label.toLowerCase(); + for (const emu of ['retroarch', 'dolphin', 'rpcs3', 'eden', 'pcsx2', 'duckstation', 'flycast', 'ppsspp']) { + if (lower.includes(emu)) return getSaveDir(emu); + } + return null; +} + +const EMU_SAVE_META: { id: string; name: string }[] = [ + { id: 'retroarch', name: 'RetroArch' }, + { id: 'dolphin', name: 'Dolphin' }, + { id: 'rpcs3', name: 'RPCS3' }, + { id: 'eden', name: 'Eden' }, + { id: 'pcsx2', name: 'PCSX2' }, + { id: 'duckstation', name: 'DuckStation' }, + { id: 'flycast', name: 'Flycast' }, + { id: 'ppsspp', name: 'PPSSPP' }, +]; + +export function getEmulatorSaveDirs() { + return EMU_SAVE_META.map(e => ({ + ...e, + saves: getSaveDir(e.id), + })).filter(e => e.saves); +} diff --git a/src/main/syncthing.ts b/src/main/syncthing.ts index 6921b44..3318887 100644 --- a/src/main/syncthing.ts +++ b/src/main/syncthing.ts @@ -458,4 +458,79 @@ export async function getSyncthingVersion(): Promise { } } +export interface PendingDeviceInfo { + id: string; + name: string; + address?: string; +} + +export interface PendingFolderInfo { + folderId: string; + folderLabel: string; + deviceId: string; +} + +export async function getPendingDevices(): Promise { + try { + const data = await apiRequest('GET', '/rest/cluster/pending/devices'); + if (!data) return []; + return Object.entries(data).map(([id, info]: [string, any]) => ({ + id, + name: info.name || '', + address: info.address || '', + })); + } catch { + return []; + } +} + +export async function acceptPendingDevice(deviceId: string): Promise { + try { + await apiRequest('PUT', `/rest/cluster/pending/devices?device=${deviceId}`); + return true; + } catch { + return false; + } +} + +export async function getPendingFolders(): Promise { + try { + const data = await apiRequest('GET', '/rest/cluster/pending/folders'); + if (!data) return []; + const results: PendingFolderInfo[] = []; + for (const [folderId, info] of Object.entries(data)) { + const deviceIds = info.offeredBy ? Object.keys(info.offeredBy) : []; + for (const deviceId of deviceIds) { + results.push({ folderId, folderLabel: info.label || folderId, deviceId }); + } + } + return results; + } catch { + return []; + } +} + +export async function acceptPendingFolder( + folderId: string, + folderLabel: string, + localPath: string, + deviceId: string +): Promise { + try { + await apiRequest('POST', '/rest/config/folders', { + id: folderId, + label: folderLabel, + path: localPath, + type: 'sendreceive', + rescanIntervalS: 3600, + fsWatcherEnabled: true, + fsWatcherDelayS: 10, + devices: [{ deviceID: deviceId }], + }); + return true; + } catch { + return false; + } +} + export { getBinaryPath, getPort, getApiKey, apiUrl, getSyncthingDir }; diff --git a/src/renderer/pages/CloudSyncPage.tsx b/src/renderer/pages/CloudSyncPage.tsx index 6eae21f..02ede5a 100644 --- a/src/renderer/pages/CloudSyncPage.tsx +++ b/src/renderer/pages/CloudSyncPage.tsx @@ -1,8 +1,14 @@ import React, { useEffect, useState, useCallback, useRef } from 'react'; -import type { SyncthingStatus } from '../../shared/types'; +import type { SyncthingStatus, SyncthingPendingDevice, SyncthingPendingFolder } from '../../shared/types'; type SetupStep = 'install' | 'start' | 'setup' | 'ready'; +interface EmuDir { + id: string; + name: string; + saves: string | null; +} + export function CloudSyncPage() { const [status, setStatus] = useState(null); const [loading, setLoading] = useState(true); @@ -14,41 +20,64 @@ export function CloudSyncPage() { const [remoteDeviceId, setRemoteDeviceId] = useState(''); const [remoteDeviceName, setRemoteDeviceName] = useState(''); const [addingDevice, setAddingDevice] = useState(false); - const [folderLabel, setFolderLabel] = useState(''); - const [folderPath, setFolderPath] = useState(''); - const [showAddFolder, setShowAddFolder] = useState(false); const [copied, setCopied] = useState(false); const [cloudEnabled, setCloudEnabled] = useState(false); - const uninstallRef = useRef(null); + const [forceReady, setForceReady] = useState(false); + const [pendingDevices, setPendingDevices] = useState([]); + const [pendingFolders, setPendingFolders] = useState([]); + const [pendingFolderPaths, setPendingFolderPaths] = useState>({}); + const [emuDirs, setEmuDirs] = useState([]); + const [emuSynced, setEmuSynced] = useState>({}); + const [togglingSync, setTogglingSync] = useState(''); + const [acceptingDevice, setAcceptingDevice] = useState(''); + const [acceptingFolder, setAcceptingFolder] = useState(''); + const pollRef = useRef | null>(null); + const idRef = useRef(null); const DEFAULT_STATUS: SyncthingStatus = { installed: false, running: false, deviceId: '', apiAddress: '', apiKey: '', version: '', folders: [], remoteDevices: [], }; - const loadStatus = useCallback(async () => { + const loadData = useCallback(async () => { setLoading(true); try { - const s = await Promise.race([ - window.omni.cloud.status(), - new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 8000)), + const [s, cloudStatus, pendingDev, pendingFol, dirs] = await Promise.all([ + window.omni.settings.get(), + window.omni.cloud.status().catch(() => null), + window.omni.cloud.pendingDevices().catch(() => [] as SyncthingPendingDevice[]), + window.omni.cloud.pendingFolders().catch(() => [] as SyncthingPendingFolder[]), + window.omni.cloud.emulatorDirs().catch(() => [] as EmuDir[]), ]); - if (s) setStatus(s); - else setStatus(DEFAULT_STATUS); - } catch { - setStatus(DEFAULT_STATUS); - } + setCloudEnabled(!!s.cloudSyncEnabled); + if (cloudStatus) { + setStatus(cloudStatus); + // Determine which emus are synced + const synced: Record = {}; + for (const d of dirs) { + synced[d.id] = cloudStatus.folders.some(f => f.id === `saves-${d.id}`); + } + setEmuSynced(synced); + } + setPendingDevices(pendingDev); + setPendingFolders(pendingFol); + setEmuDirs(dirs); + // Auto-resolve folder paths + const paths: Record = {}; + for (const fol of pendingFol) { + const resolved = await window.omni.cloud.guessPath(fol.folderLabel).catch(() => null); + paths[fol.folderId] = resolved || ''; + } + setPendingFolderPaths(paths); + } catch { /* ignore */ } setLoading(false); }, []); - const loadSettings = useCallback(async () => { - try { - const s = await window.omni.settings.get(); - setCloudEnabled(!!s.cloudSyncEnabled); - } catch { /* ignore */ } - }, []); + useEffect(() => { loadData(); }, [loadData]); - useEffect(() => { loadStatus(); loadSettings(); }, [loadStatus, loadSettings]); + useEffect(() => { + return () => { if (pollRef.current) clearInterval(pollRef.current); }; + }, []); useEffect(() => { const unsub = window.omni.cloud.onInstallProgress((p) => { @@ -56,25 +85,14 @@ export function CloudSyncPage() { setInstallPercent(p.percent); if (p.stage === 'done' || p.stage === 'error') { setInstalling(false); - if (p.stage === 'done') { - loadStatus(); - } + if (p.stage === 'done') loadData(); } }); return unsub; - }, [loadStatus]); + }, [loadData]); - const showSuccess = (msg: string) => { - setSuccess(msg); - setError(''); - setTimeout(() => setSuccess(''), 4000); - }; - - const showError = (msg: string) => { - setError(msg); - setSuccess(''); - setTimeout(() => setError(''), 4000); - }; + const showSuccess = (msg: string) => { setSuccess(msg); setError(''); setTimeout(() => setSuccess(''), 4000); }; + const showError = (msg: string) => { setError(msg); setSuccess(''); setTimeout(() => setError(''), 4000); }; const saveCloudEnabled = async (enabled: boolean) => { setCloudEnabled(enabled); @@ -82,189 +100,118 @@ export function CloudSyncPage() { }; const handleInstall = async () => { - setInstalling(true); - setInstallPercent(0); - setInstallMsg('Starting download...'); + setInstalling(true); setInstallPercent(0); setInstallMsg('Starting download...'); try { const ok = await window.omni.cloud.install(); - if (!ok) { - setInstalling(false); - showError('Installation failed'); - } - } catch (err) { - setInstalling(false); - showError(`Install error: ${err}`); - } + if (!ok) { setInstalling(false); showError('Installation failed'); } + } catch (err) { setInstalling(false); showError(`Install error: ${err}`); } }; const handleStart = async () => { setLoading(true); try { - // Start kicks off the process in the background const s = await window.omni.cloud.start(); if (s) { setStatus(s); - if (s.running) { - await saveCloudEnabled(true); - showSuccess('Syncthing started! Auto-start enabled.'); - } else { - // Process was kicked off but may need more time — poll + if (s.running) { await saveCloudEnabled(true); showSuccess('Syncthing started!'); setLoading(false); } + else { let attempts = 0; - const poll = setInterval(async () => { + pollRef.current = setInterval(async () => { attempts++; try { const latest = await window.omni.cloud.status(); setStatus(latest); - if (latest.running) { - clearInterval(poll); - await saveCloudEnabled(true); - showSuccess('Syncthing started! Auto-start enabled.'); - setLoading(false); - } else if (attempts >= 15) { - clearInterval(poll); - showError('Syncthing took too long to start. Check that the binary is not blocked by your OS.'); - setLoading(false); - } - } catch { - if (attempts >= 15) { - clearInterval(poll); - showError('Could not reach Syncthing.'); - setLoading(false); - } - } + if (latest.running) { clearInterval(pollRef.current!); pollRef.current = null; await saveCloudEnabled(true); showSuccess('Syncthing started!'); setLoading(false); } + else if (attempts >= 15) { clearInterval(pollRef.current!); pollRef.current = null; showError('Syncthing took too long to start.'); setLoading(false); } + } catch { if (attempts >= 15) { clearInterval(pollRef.current!); pollRef.current = null; showError('Could not reach Syncthing.'); setLoading(false); } } }, 1000); } - } else { - showError('Failed to start Syncthing — binary not found'); - } - } catch (err) { - showError(`Start error: ${err}`); - } - setLoading(false); + } else { showError('Failed to start Syncthing'); setLoading(false); } + } catch (err) { showError(`Start error: ${err}`); setLoading(false); } }; const handleStop = async () => { setLoading(true); - try { - const s = await window.omni.cloud.stop(); - setStatus(s); - await saveCloudEnabled(false); - showSuccess('Syncthing stopped. Auto-start disabled.'); - } catch (err) { - showError(`Stop error: ${err}`); - } + try { const s = await window.omni.cloud.stop(); setStatus(s); await saveCloudEnabled(false); showSuccess('Syncthing stopped.'); } + catch (err) { showError(`Stop error: ${err}`); } setLoading(false); }; const handleAddDevice = async () => { - if (!remoteDeviceId.trim()) { - showError('Enter a device ID'); - return; - } + if (!remoteDeviceId.trim()) { showError('Enter a device ID'); return; } setAddingDevice(true); try { const ok = await window.omni.cloud.addDevice(remoteDeviceId.trim(), remoteDeviceName.trim()); - if (ok) { - showSuccess('Device added! Wait for it to accept, or add this device on the other machine.'); - setRemoteDeviceId(''); - setRemoteDeviceName(''); - loadStatus(); - } else { - showError('Failed to add device'); - } - } catch (err) { - showError(`Error: ${err}`); - } + if (ok) { showSuccess('Device added!'); setRemoteDeviceId(''); setRemoteDeviceName(''); loadData(); } + else showError('Failed to add device'); + } catch (err) { showError(`Error: ${err}`); } setAddingDevice(false); }; + const handleAcceptPendingDevice = async (deviceId: string) => { + setAcceptingDevice(deviceId); + try { + const ok = await window.omni.cloud.acceptPendingDevice(deviceId); + if (ok) { showSuccess('Device paired!'); loadData(); } else showError('Failed to accept device'); + } catch (err) { showError(`Error: ${err}`); } + setAcceptingDevice(''); + }; + + const handleAcceptPendingFolder = async (fol: SyncthingPendingFolder) => { + const localPath = pendingFolderPaths[fol.folderId]; + if (!localPath?.trim()) { showError('Set a local path first'); return; } + setAcceptingFolder(fol.folderId); + try { + const ok = await window.omni.cloud.acceptPendingFolder(fol.folderId, fol.folderLabel, localPath.trim(), fol.deviceId); + if (ok) { showSuccess(`Folder "${fol.folderLabel}" accepted!`); loadData(); } else showError('Failed to accept folder'); + } catch (err) { showError(`Error: ${err}`); } + setAcceptingFolder(''); + }; + + const handleToggleSync = async (emuId: string, sync: boolean) => { + setTogglingSync(emuId); + try { + const ok = await window.omni.cloud.toggleFolderSync(emuId, sync); + if (ok) { showSuccess(sync ? 'Sync enabled' : 'Sync disabled'); loadData(); } + else showError('Failed to toggle sync'); + } catch (err) { showError(`Error: ${err}`); } + setTogglingSync(''); + }; + const handleRemoveDevice = async (deviceId: string) => { - try { - await window.omni.cloud.removeDevice(deviceId); - showSuccess('Device removed'); - loadStatus(); - } catch { /* ignore */ } - }; - - const handleAddFolder = async () => { - if (!folderLabel.trim() || !folderPath.trim()) { - showError('Enter folder label and path'); - return; - } - const id = folderLabel.toLowerCase().replace(/[^a-z0-9]/g, '-'); - const deviceIds = status?.remoteDevices?.map(d => d.id) || []; - try { - const ok = await window.omni.cloud.addFolder(id, folderLabel.trim(), folderPath.trim(), deviceIds); - if (ok) { - showSuccess('Shared folder added'); - setFolderLabel(''); - setFolderPath(''); - setShowAddFolder(false); - loadStatus(); - } else { - showError('Failed to add folder'); - } - } catch (err) { - showError(`Error: ${err}`); - } - }; - - const handleRemoveFolder = async (folderId: string) => { - try { - await window.omni.cloud.removeFolder(folderId); - showSuccess('Folder removed'); - loadStatus(); - } catch { /* ignore */ } + try { await window.omni.cloud.removeDevice(deviceId); showSuccess('Device removed'); loadData(); } catch { /* ignore */ } }; const handleCopyDeviceId = () => { - if (status?.deviceId) { - navigator.clipboard.writeText(status.deviceId); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } + if (status?.deviceId) { navigator.clipboard.writeText(status.deviceId); setCopied(true); setTimeout(() => setCopied(false), 2000); } }; - const handleCopyApiKey = () => { - if (status?.apiKey) { - navigator.clipboard.writeText(status.apiKey); - showSuccess('API key copied'); - } - }; - - const handleOpenWebUI = async () => { - await window.omni.cloud.openWebUI(); - }; - - if (loading && !status) { - return
Checking Syncthing status...
; - } + if (loading && !status) return
Checking Syncthing status...
; const installed = status?.installed ?? false; const running = status?.running ?? false; - // Determine current step let step: SetupStep; if (!installed) step = 'install'; else if (!running) step = 'start'; - else if (!cloudEnabled || (status?.remoteDevices?.length ?? 0) === 0) step = 'setup'; + else if (!forceReady && (status?.remoteDevices?.length ?? 0) === 0) step = 'setup'; else step = 'ready'; + const stepLabel = (s: SetupStep) => s === 'install' ? 'Install' : s === 'start' ? 'Start' : s === 'setup' ? 'Pair' : 'Sync'; + const stepIdx = (s: SetupStep) => (['install', 'start', 'setup', 'ready'] as SetupStep[]).indexOf(s); + const currentIdx = stepIdx(step); + return (
-

Cloud Sync

+

Cloud Sync Beta

- Sync your game saves between devices using Syncthing. Once set up, it runs automatically on launch. + Sync your game saves between devices. Once set up, it runs automatically.

- {error && ( -
{error}
- )} - {success && ( -
{success}
- )} + {error &&
{error}
} + {success &&
{success}
} - {/* Progress indicator */} + {/* Step indicator */}
i - ? 'var(--success, #44ff44)' : 'var(--bg-tertiary, #333)'), - color: step === s ? '#fff' : 'var(--text-muted, #888)', - transition: 'all 0.2s ease', + background: step === s ? 'var(--accent)' : currentIdx > i ? 'var(--success, #44ff44)' : 'var(--bg-tertiary, #333)', + color: step === s ? '#fff' : 'var(--text-muted, #888)', transition: 'all 0.2s ease', }}> - {['install', 'start', 'setup', 'ready'].indexOf(step) > i ? '✓' : i + 1} + {currentIdx > i ? '✓' : i + 1}
- {s === 'install' ? 'Install' : s === 'start' ? 'Start' : s === 'setup' ? 'Pair' : 'Syncing'} + {stepLabel(s)} - {i < 3 &&
} + {i < 3 &&
} ))}
@@ -308,32 +247,57 @@ export function CloudSyncPage() { border: `1px solid ${cloudEnabled ? 'rgba(68,255,68,0.3)' : 'rgba(255,200,68,0.3)'}`, color: cloudEnabled ? 'var(--success, #44ff44)' : '#ffc844', }}> - + {cloudEnabled ? 'Cloud sync active' : 'Running — not yet paired'}
)} + {/* Pending Device Requests */} + {running && pendingDevices.length > 0 && ( +
+
+

⏳ Pending Device Requests

+
+
+ {pendingDevices.map(dev => ( +
+
+
{dev.name || 'Unknown Device'}
+
+ {dev.id.slice(0, 12)}...{dev.id.slice(-6)} +
+
+ +
+ ))} +
+
+ )} + {/* Step 1: Install */} {!installed && !installing && (
-
-

Install Syncthing

-
+

Install Syncthing

- Syncthing is the engine behind cloud sync. It's free, open-source, and runs locally — no third-party accounts needed. + Syncthing is the engine behind cloud sync. Free, open-source, runs locally — no accounts needed.

-
@@ -342,20 +306,13 @@ export function CloudSyncPage() { {installing && (
-
-

Installing Syncthing...

-
+

Installing Syncthing...

{installMsg}
-
+
@@ -368,271 +325,252 @@ export function CloudSyncPage() { border: '2px solid var(--accent)', background: 'linear-gradient(135deg, rgba(108,99,255,0.08), rgba(108,99,255,0.02))', }}> -
-

Start Syncthing

-
+

Start Syncthing

- Start the sync service. It will auto-start on future app launches once enabled. + Start the sync service. It will auto-start on future launches.

-
)} - {/* Steps 3-4: Host & Pair (running) */} + {/* Steps 3-4 */} {running && ( <> - {/* Host section — show your device ID */} -
-
-

Host — Share This Device

-
-
-

- Copy this Device ID and paste it into the other machine's OmniEmu or Syncthing to pair. -

-
-